123456789_123456789_123456789_123456789_123456789_

Class: PG::Result

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
self, Enumerable, Constants
Inherits: Object
Defined in: ext/pg_result.c,
ext/pg_result.c,
lib/pg/result.rb

Overview

The class to represent the query result tuples (rows). An instance of this class is created as the result of every query. All result rows and columns are stored in a memory block attached to the Result object. Whenever a value is accessed it is casted to a Ruby object by the assigned #type_map .

Since pg-1.1 the amount of memory in use by a Result object is estimated and passed to ruby’s garbage collector. You can invoke the #clear method to force deallocation of memory of the instance when finished with the result for better memory performance.

Example:

require 'pg'
conn = PG.connect(:dbname => 'test')
res  = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
res.getvalue(0,0) # '1'
res[0]['b']       # '2'
res[0]['c']       # nil

Constant Summary

Constants - Included

CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_STANDBY, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, DEF_PGPORT, INVALID_OID, INV_READ, INV_WRITE, InvalidOid, PGRES_BAD_RESPONSE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, PGRES_PIPELINE_ABORTED, PGRES_PIPELINE_SYNC, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_SINGLE_TUPLE, PGRES_TUPLES_OK, PG_DIAG_COLUMN_NAME, PG_DIAG_CONSTRAINT_NAME, PG_DIAG_CONTEXT, PG_DIAG_DATATYPE_NAME, PG_DIAG_INTERNAL_POSITION, PG_DIAG_INTERNAL_QUERY, PG_DIAG_MESSAGE_DETAIL, PG_DIAG_MESSAGE_HINT, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SCHEMA_NAME, PG_DIAG_SEVERITY, PG_DIAG_SEVERITY_NONLOCALIZED, PG_DIAG_SOURCE_FILE, PG_DIAG_SOURCE_FUNCTION, PG_DIAG_SOURCE_LINE, PG_DIAG_SQLSTATE, PG_DIAG_STATEMENT_POSITION, PG_DIAG_TABLE_NAME, PQERRORS_DEFAULT, PQERRORS_SQLSTATE, PQERRORS_TERSE, PQERRORS_VERBOSE, PQPING_NO_ATTEMPT, PQPING_NO_RESPONSE, PQPING_OK, PQPING_REJECT, PQSHOW_CONTEXT_ALWAYS, PQSHOW_CONTEXT_ERRORS, PQSHOW_CONTEXT_NEVER, PQTRANS_ACTIVE, PQTRANS_IDLE, PQTRANS_INERROR, PQTRANS_INTRANS, PQTRANS_UNKNOWN, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, SEEK_CUR, SEEK_END, SEEK_SET

Class Method Summary

Instance Attribute Summary

Instance Method Summary

Class Method Details

.res_status(status) ⇒ String

Returns the string representation of status.

[ GitHub ]

  
# File 'ext/pg_result.c', line 570

static VALUE
pgresult_s_res_status(VALUE self, VALUE status)
{
	return rb_utf8_str_new_cstr(PQresStatus(NUM2INT(status)));
}

Instance Attribute Details

#autoclear?Boolean (readonly)

Returns true if the underlying C struct will be cleared at the end of a callback. This applies only to Result objects received by the block to Connection#set_notice_receiver .

All other Result objects are automatically cleared by the GC when the object is no longer in use or manually by #clear .

[ GitHub ]

  
# File 'ext/pg_result.c', line 427

static VALUE
pgresult_autoclear_p( VALUE self )
{
	t_pg_result *this = pgresult_get_this(self);
	return this->autoclear ? Qtrue : Qfalse;
}

#cleared?Boolean (readonly)

Returns true if the backend result memory has been freed.

[ GitHub ]

  
# File 'ext/pg_result.c', line 410

static VALUE
pgresult_cleared_p( VALUE self )
{
	t_pg_result *this = pgresult_get_this(self);
	return this->pgresult ? Qfalse : Qtrue;
}

#field_name_typeSymbol (rw)

Get type of field names.

See description at #field_name_type=

[ GitHub ]

  
# File 'ext/pg_result.c', line 1679

static VALUE
pgresult_field_name_type_get(VALUE self)
{
	t_pg_result *this = pgresult_get_this(self);
	if( this->flags & PG_RESULT_FIELD_NAMES_SYMBOL ){
		return sym_symbol;
	} else if( this->flags & PG_RESULT_FIELD_NAMES_STATIC_SYMBOL ){
		return sym_static_symbol;
	} else {
		return sym_string;
	}
}

#field_name_type=(Symbol) (rw)

Set type of field names specific to this result. It can be set to one of:

  • :string to use String based field names

  • :symbol to use Symbol based field names

  • :static_symbol to use pinned Symbol (can not be garbage collected) - Don’t use this, it will probably be removed in future.

The default is retrieved from Connection#field_name_type , which defaults to :string .

This setting affects several result methods:

The type of field names can only be changed before any of the affected methods have been called.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1654

static VALUE
pgresult_field_name_type_set(VALUE self, VALUE sym)
{
	t_pg_result *this = pgresult_get_this(self);

	rb_check_frozen(self);
	if( this->nfields != -1 ) rb_raise(rb_eArgError, "field names are already materialized");

	this->flags &= ~PG_RESULT_FIELD_NAMES_MASK;
	if( sym == sym_symbol ) this->flags |= PG_RESULT_FIELD_NAMES_SYMBOL;
	else if ( sym == sym_static_symbol ) this->flags |= PG_RESULT_FIELD_NAMES_STATIC_SYMBOL;
	else if ( sym == sym_string );
	else rb_raise(rb_eArgError, "invalid argument %+"PRIsVALUE, sym);

	return sym;
}

#type_mapvalue (rw)

Returns the TypeMap that is currently set for type casts of result values to ruby objects.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1441

static VALUE
pgresult_type_map_get(VALUE self)
{
	t_pg_result *this = pgresult_get_this(self);

	return this->typemap;
}

#type_map=(typemap) (rw)

Set the TypeMap that is used for type casts of result values to ruby objects.

All value retrieval methods will respect the type map and will do the type casts from PostgreSQL’s wire format to Ruby objects on the fly, according to the rules and decoders defined in the given typemap.

typemap must be a kind of TypeMap .

[ GitHub ]

  
# File 'ext/pg_result.c', line 1417

static VALUE
pgresult_type_map_set(VALUE self, VALUE typemap)
{
	t_pg_result *this = pgresult_get_this(self);
	t_typemap *p_typemap;

	rb_check_frozen(self);
	/* Check type of method param */
	TypedData_Get_Struct(typemap, t_typemap, &pg_typemap_type, p_typemap);

	typemap = p_typemap->funcs.fit_to_result( typemap, self );
	RB_OBJ_WRITE(self, &this->typemap, typemap);
	this->p_typemap = RTYPEDDATA_DATA( typemap );

	return typemap;
}

Instance Method Details

#[](n ) ⇒ Hash

Returns tuple n as a hash.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1129

static VALUE
pgresult_aref(VALUE self, VALUE index)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	int tuple_num = NUM2INT(index);
	int field_num;
	int num_tuples = PQntuples(this->pgresult);
	VALUE tuple;

	if( this->nfields == -1 )
		pgresult_init_fnames( self );

	if ( tuple_num < 0 || tuple_num >= num_tuples )
		rb_raise( rb_eIndexError, "Index %d is out of range", tuple_num );

	/* We reuse the Hash of the previous output for larger row counts.
	 * This is somewhat faster than populating an empty Hash object. */
	tuple = NIL_P(this->tuple_hash) ? rb_hash_new() : this->tuple_hash;
	for ( field_num = 0; field_num < this->nfields; field_num++ ) {
		VALUE val = this->p_typemap->funcs.typecast_result_value(this->p_typemap, self, tuple_num, field_num);
		rb_hash_aset( tuple, this->fnames[field_num], val );
	}
	/* Store a copy of the filled hash for use at the next row. */
	if( num_tuples > 10 )
		RB_OBJ_WRITE(self, &this->tuple_hash, rb_hash_dup(tuple));

	return tuple;
}

#binary_tuplesInteger

Returns 1 if the PGresult contains binary data and 0 if it contains text data.

This function is deprecated (except for its use in connection with COPY), because it is possible for a single PGresult to contain text data in some columns and binary data in others. #fformat is preferred. binary_tuples returns 1 only if all columns of the result are binary (format 1).

[ GitHub ]

  
# File 'ext/pg_result.c', line 745

static VALUE
pgresult_binary_tuples(VALUE self)
{
	return INT2NUM(PQbinaryTuples(pgresult_get(self)));
}

#checknil Also known as: #check_result

Raises appropriate exception if Result is in a bad state, which is:

  • PGRES_BAD_RESPONSE

  • PGRES_FATAL_ERROR

  • PGRES_NONFATAL_ERROR

  • PGRES_PIPELINE_ABORTED

[ GitHub ]

  
# File 'ext/pg_result.c', line 301

VALUE
pg_result_check( VALUE self )
{
	t_pg_result *this = pgresult_get_this(self);
	VALUE error, exception, klass;
	char * sqlstate;

	if(this->pgresult == NULL)
	{
		PGconn *conn = pg_get_pgconn(this->connection);
		error = rb_str_new2( PQerrorMessage(conn) );
	}
	else
	{
		switch (PQresultStatus(this->pgresult))
		{
		case PGRES_TUPLES_OK:
		case PGRES_COPY_OUT:
		case PGRES_COPY_IN:
		case PGRES_COPY_BOTH:
		case PGRES_SINGLE_TUPLE:
		case PGRES_EMPTY_QUERY:
		case PGRES_COMMAND_OK:
#ifdef HAVE_PQENTERPIPELINEMODE
		case PGRES_PIPELINE_SYNC:
#endif
			return self;
		case PGRES_BAD_RESPONSE:
		case PGRES_FATAL_ERROR:
		case PGRES_NONFATAL_ERROR:
#ifdef HAVE_PQENTERPIPELINEMODE
		case PGRES_PIPELINE_ABORTED:
#endif
			error = rb_str_new2( PQresultErrorMessage(this->pgresult) );
			break;
		default:
			error = rb_str_new2( "internal error : unknown result status." );
		}
	}

	PG_ENCODING_SET_NOCHECK( error, this->enc_idx );

	sqlstate = PQresultErrorField( this->pgresult, PG_DIAG_SQLSTATE );
	klass = lookup_error_class( sqlstate );
	exception = rb_exc_new3( klass, error );
	rb_iv_set( exception, "@connection", this->connection );
	rb_iv_set( exception, "@result", this->pgresult ? self : Qnil );
	rb_exc_raise( exception );

	/* Not reached */
	return self;
}

#checknil #check_resultnil

Alias for #check.

#clearnil

Clears the Result object as the result of a query. This frees all underlying memory consumed by the result object. Afterwards access to result methods raises Error “result has been cleared”.

Explicit calling #clear can lead to better memory performance, but is not generally necessary. Special care must be taken when Tuple objects are used. In this case #clear must not be called unless all Tuple objects of this result are fully materialized.

If #autoclear? is true then the result is only marked as cleared but clearing the underlying C struct will happen when the callback returns.

[ GitHub ]

  
# File 'ext/pg_result.c', line 376

VALUE
pg_result_clear(VALUE self)
{
	t_pg_result *this = pgresult_get_this(self);
	rb_check_frozen(self);
	pgresult_clear( this );
	return Qnil;
}

#cmd_statusString

Returns the status string of the last query command.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1067

static VALUE
pgresult_cmd_status(VALUE self)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	VALUE ret = rb_str_new2(PQcmdStatus(this->pgresult));
	PG_ENCODING_SET_NOCHECK(ret, this->enc_idx);
	return ret;
}

#cmdtuplesInteger #cmd_tuplesInteger

Alias for #cmdtuples.

#cmdtuplesInteger Also known as: #cmd_tuples

Returns the number of tuples (rows) affected by the SQL command.

If the SQL command that generated the Result was not one of:

  • SELECT

  • CREATE TABLE AS

  • INSERT

  • UPDATE

  • DELETE

  • MOVE

  • FETCH

  • COPY

  • an EXECUTE of a prepared query that contains an INSERT, UPDATE, or DELETE statement

or if no tuples were affected, 0 is returned.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1096

static VALUE
pgresult_cmd_tuples(VALUE self)
{
	long n;
	n = strtol(PQcmdTuples(pgresult_get(self)),NULL, 10);
	return LONG2NUM(n);
}

#column_values(n) ⇒ Array

Returns an Array of the values from the nth column of each tuple in the result.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1253

static VALUE
pgresult_column_values(VALUE self, VALUE index)
{
	int col = NUM2INT( index );
	return make_column_result_array( self, col );
}

#each {|tuple| ... }

Invokes block for each tuple in the result set.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1371

static VALUE
pgresult_each(VALUE self)
{
	PGresult *result;
	int tuple_num;

	RETURN_SIZED_ENUMERATOR(self, 0, NULL, pgresult_ntuples_for_enum);

	result = pgresult_get(self);

	for(tuple_num = 0; tuple_num < PQntuples(result); tuple_num++) {
		rb_yield(pgresult_aref(self, INT2NUM(tuple_num)));
	}
	return self;
}

#each_row {|row| ... }

Yields each row of the result. The row is a list of column values.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1164

static VALUE
pgresult_each_row(VALUE self)
{
	t_pg_result *this;
	int row;
	int field;
	int num_rows;
	int num_fields;

	RETURN_SIZED_ENUMERATOR(self, 0, NULL, pgresult_ntuples_for_enum);

	this = pgresult_get_this_safe(self);
	num_rows = PQntuples(this->pgresult);
	num_fields = PQnfields(this->pgresult);

	for ( row = 0; row < num_rows; row++ ) {
		PG_VARIABLE_LENGTH_ARRAY(VALUE, row_values, num_fields, PG_MAX_COLUMNS)

		/* populate the row */
		for ( field = 0; field < num_fields; field++ ) {
			row_values[field] = this->p_typemap->funcs.typecast_result_value(this->p_typemap, self, row, field);
		}
		rb_yield( rb_ary_new4( num_fields, row_values ));
	}

	return Qnil;
}

#error_field(fieldcode) ⇒ String Also known as: #result_error_field

Returns the individual field of an error.

fieldcode is one of:

  • PG_DIAG_SEVERITY

  • PG_DIAG_SQLSTATE

  • PG_DIAG_MESSAGE_PRIMARY

  • PG_DIAG_MESSAGE_DETAIL

  • PG_DIAG_MESSAGE_HINT

  • PG_DIAG_STATEMENT_POSITION

  • PG_DIAG_INTERNAL_POSITION

  • PG_DIAG_INTERNAL_QUERY

  • PG_DIAG_CONTEXT

  • PG_DIAG_SOURCE_FILE

  • PG_DIAG_SOURCE_LINE

  • PG_DIAG_SOURCE_FUNCTION

An example:

begin
    conn.exec( "SELECT * FROM nonexistent_table" )
rescue PG::Error => err
    p [
        err.result.error_field( PG::Result::PG_DIAG_SEVERITY ),
        err.result.error_field( PG::Result::PG_DIAG_SQLSTATE ),
        err.result.error_field( PG::Result::PG_DIAG_MESSAGE_PRIMARY ),
        err.result.error_field( PG::Result::PG_DIAG_MESSAGE_DETAIL ),
        err.result.error_field( PG::Result::PG_DIAG_MESSAGE_HINT ),
        err.result.error_field( PG::Result::PG_DIAG_STATEMENT_POSITION ),
        err.result.error_field( PG::Result::PG_DIAG_INTERNAL_POSITION ),
        err.result.error_field( PG::Result::PG_DIAG_INTERNAL_QUERY ),
        err.result.error_field( PG::Result::PG_DIAG_CONTEXT ),
        err.result.error_field( PG::Result::PG_DIAG_SOURCE_FILE ),
        err.result.error_field( PG::Result::PG_DIAG_SOURCE_LINE ),
        err.result.error_field( PG::Result::PG_DIAG_SOURCE_FUNCTION ),
    ]
end

Outputs:

["ERROR", "42P01", "relation \"nonexistent_table\" does not exist", nil, nil,
 "15", nil, nil, nil, "path/to/parse_relation.c", "857", "parserOpenTable"]
[ GitHub ]

  
# File 'ext/pg_result.c', line 690

static VALUE
pgresult_error_field(VALUE self, VALUE field)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	int fieldcode = NUM2INT( field );
	char * fieldstr = PQresultErrorField( this->pgresult, fieldcode );
	VALUE ret = Qnil;

	if ( fieldstr ) {
		ret = rb_str_new2( fieldstr );
		PG_ENCODING_SET_NOCHECK( ret, this->enc_idx );
	}

	return ret;
}

#error_messageString Also known as: #result_error_message

Returns the error message of the command as a string.

[ GitHub ]

  
# File 'ext/pg_result.c', line 607

static VALUE
pgresult_error_message(VALUE self)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	VALUE ret = rb_str_new2(PQresultErrorMessage(this->pgresult));
	PG_ENCODING_SET_NOCHECK(ret, this->enc_idx);
	return ret;
}

#fformat(column_number) ⇒ Integer

Returns the format (0 for text, 1 for binary) of column column_number.

Raises ArgumentError if column_number is out of range.

[ GitHub ]

  
# File 'ext/pg_result.c', line 869

static VALUE
pgresult_fformat(VALUE self, VALUE column_number)
{
	PGresult *result = pgresult_get(self);
	int fnumber = NUM2INT(column_number);
	if (fnumber < 0 || fnumber >= PQnfields(result)) {
		rb_raise(rb_eArgError, "Column number is out of range: %d",
			fnumber);
	}
	return INT2FIX(PQfformat(result, fnumber));
}

#field_names_as(type)

Set the data type for all field name returning methods.

type: a Symbol defining the field name type.

This method is equal to #field_name_type= , but returns self, so that calls can be chained.

[ GitHub ]

  
# File 'lib/pg/result.rb', line 26

def field_names_as(type)
	self.field_name_type = type
	return self
end

#field_values(field) ⇒ Array

Returns an Array of the values from the given field of each tuple in the result.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1268

static VALUE
pgresult_field_values( VALUE self, VALUE field )
{
	PGresult *result = pgresult_get( self );
	const char *fieldname;
	int fnum;

	if( RB_TYPE_P(field, T_SYMBOL) ) field = rb_sym_to_s( field );
	fieldname = StringValueCStr( field );
	fnum = PQfnumber( result, fieldname );

	if ( fnum < 0 )
		rb_raise( rb_eIndexError, "no such field '%s' in result", fieldname );

	return make_column_result_array( self, fnum );
}

#fieldsArray

Depending on #field_name_type= returns an array of strings or symbols representing the names of the fields in the result.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1393

static VALUE
pgresult_fields(VALUE self)
{
	t_pg_result *this = pgresult_get_this_safe(self);

	if( this->nfields == -1 )
		pgresult_init_fnames( self );

	return rb_ary_new4( this->nfields, this->fnames );
}

#fmod(column_number)

Returns the type modifier associated with column column_number. See the #ftype method for an example of how to use this.

Raises an ArgumentError if column_number is out of range.

[ GitHub ]

  
# File 'ext/pg_result.c', line 919

static VALUE
pgresult_fmod(VALUE self, VALUE column_number)
{
	PGresult *result = pgresult_get(self);
	int fnumber = NUM2INT(column_number);
	int modifier;
	if (fnumber < 0 || fnumber >= PQnfields(result)) {
		rb_raise(rb_eArgError, "Column number is out of range: %d",
			fnumber);
	}
	modifier = PQfmod(result,fnumber);

	return INT2NUM(modifier);
}

#fname(index) ⇒ String, Symbol

Returns the name of the column corresponding to index. Depending on #field_name_type= it’s a String or Symbol.

[ GitHub ]

  
# File 'ext/pg_result.c', line 759

static VALUE
pgresult_fname(VALUE self, VALUE index)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	int i = NUM2INT(index);
	char *cfname;

	if (i < 0 || i >= PQnfields(this->pgresult)) {
		rb_raise(rb_eArgError,"invalid field number %d", i);
	}

	cfname = PQfname(this->pgresult, i);
	return pg_cstr_to_sym(cfname, this->flags, this->enc_idx);
}

#fnumber(name) ⇒ Integer

Returns the index of the field specified by the string name. The given name is treated like an identifier in an SQL command, that is, it is downcased unless double-quoted. For example, given a query result generated from the SQL command:

result = conn.exec( %{SELECT 1 AS FOO, 2 AS "BAR"} )

we would have the results:

result.fname( 0 )            # => "foo"
result.fname( 1 )            # => "BAR"
result.fnumber( "FOO" )      # => 0
result.fnumber( "foo" )      # => 0
result.fnumber( "BAR" )      # => ArgumentError
result.fnumber( %{"BAR"} )   # => 1

Raises an ArgumentError if the specified name isn’t one of the field names; raises a TypeError if name is not a String.

[ GitHub ]

  
# File 'ext/pg_result.c', line 797

static VALUE
pgresult_fnumber(VALUE self, VALUE name)
{
	int n;

	Check_Type(name, T_STRING);

	n = PQfnumber(pgresult_get(self), StringValueCStr(name));
	if (n == -1) {
		rb_raise(rb_eArgError,"Unknown field: %s", StringValueCStr(name));
	}
	return INT2FIX(n);
}

#freeze

Freeze the Result object and unlink the result from the related Connection.

A frozen Result object doesn’t allow any streaming and it can’t be cleared. It also denies setting a type_map or field_name_type.

[ GitHub ]

  
# File 'ext/pg_result.c', line 395

static VALUE
pg_result_freeze(VALUE self)
{
	t_pg_result *this = pgresult_get_this(self);

	RB_OBJ_WRITE(self, &this->connection, Qnil);
	return rb_call_super(0, NULL);
}

#fsize(index)

Returns the size of the field type in bytes. Returns -1 if the field is variable sized.

res = conn.exec("SELECT myInt, myVarChar50 FROM foo")
res.size(0) => 4
res.size(1) => -1
[ GitHub ]

  
# File 'ext/pg_result.c', line 944

static VALUE
pgresult_fsize(VALUE self, VALUE index)
{
	PGresult *result;
	int i = NUM2INT(index);

	result = pgresult_get(self);
	if (i < 0 || i >= PQnfields(result)) {
		rb_raise(rb_eArgError,"invalid field number %d", i);
	}
	return INT2NUM(PQfsize(result, i));
}

#ftable(column_number) ⇒ Integer

Returns the Oid of the table from which the column column_number was fetched.

Raises ArgumentError if column_number is out of range or if the Oid is undefined for that column.

[ GitHub ]

  
# File 'ext/pg_result.c', line 821

static VALUE
pgresult_ftable(VALUE self, VALUE column_number)
{
	Oid n ;
	int col_number = NUM2INT(column_number);
	PGresult *pgresult = pgresult_get(self);

	if( col_number < 0 || col_number >= PQnfields(pgresult))
		rb_raise(rb_eArgError,"Invalid column index: %d", col_number);

	n = PQftable(pgresult, col_number);
	return UINT2NUM(n);
}

#ftablecol(column_number) ⇒ Integer

Returns the column number (within its table) of the table from which the column column_number is made up.

Raises ArgumentError if column_number is out of range or if the column number from its table is undefined for that column.

[ GitHub ]

  
# File 'ext/pg_result.c', line 845

static VALUE
pgresult_ftablecol(VALUE self, VALUE column_number)
{
	int col_number = NUM2INT(column_number);
	PGresult *pgresult = pgresult_get(self);

	int n;

	if( col_number < 0 || col_number >= PQnfields(pgresult))
		rb_raise(rb_eArgError,"Invalid column index: %d", col_number);

	n = PQftablecol(pgresult, col_number);
	return INT2FIX(n);
}

#ftype(column_number) ⇒ Integer

Returns the data type associated with column_number.

The integer returned is the internal OID number (in PostgreSQL) of the type. To get a human-readable value for the type, use the returned OID and the field’s #fmod value with the format_type() SQL function:

# Get the type of the second column of the result 'res'
typename = conn.
  exec( "SELECT format_type($1,$2)", [res.ftype(1), res.fmod(1)] ).
  getvalue( 0, 0 )

Raises an ArgumentError if column_number is out of range.

[ GitHub ]

  
# File 'ext/pg_result.c', line 899

static VALUE
pgresult_ftype(VALUE self, VALUE index)
{
	PGresult* result = pgresult_get(self);
	int i = NUM2INT(index);
	if (i < 0 || i >= PQnfields(result)) {
		rb_raise(rb_eArgError, "invalid field number %d", i);
	}
	return UINT2NUM(PQftype(result, i));
}

#getisnull(tuple_position, field_position) ⇒ Boolean

Returns true if the specified value is nil; false otherwise.

[ GitHub ]

  
# File 'ext/pg_result.c', line 987

static VALUE
pgresult_getisnull(VALUE self, VALUE tup_num, VALUE field_num)
{
	PGresult *result;
	int i = NUM2INT(tup_num);
	int j = NUM2INT(field_num);

	result = pgresult_get(self);
	if (i < 0 || i >= PQntuples(result)) {
		rb_raise(rb_eArgError,"invalid tuple number %d", i);
	}
	if (j < 0 || j >= PQnfields(result)) {
		rb_raise(rb_eArgError,"invalid field number %d", j);
	}
	return PQgetisnull(result, i, j) ? Qtrue : Qfalse;
}

#getlength(tup_num, field_num) ⇒ Integer

Returns the (String) length of the field in bytes.

Equivalent to res.value(tup_num,field_num).length.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1012

static VALUE
pgresult_getlength(VALUE self, VALUE tup_num, VALUE field_num)
{
	PGresult *result;
	int i = NUM2INT(tup_num);
	int j = NUM2INT(field_num);

	result = pgresult_get(self);
	if (i < 0 || i >= PQntuples(result)) {
		rb_raise(rb_eArgError,"invalid tuple number %d", i);
	}
	if (j < 0 || j >= PQnfields(result)) {
		rb_raise(rb_eArgError,"invalid field number %d", j);
	}
	return INT2FIX(PQgetlength(result, i, j));
}

#getvalue(tup_num, field_num)

Returns the value in tuple number tup_num, field field_num, or nil if the field is NULL.

[ GitHub ]

  
# File 'ext/pg_result.c', line 965

static VALUE
pgresult_getvalue(VALUE self, VALUE tup_num, VALUE field_num)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	int i = NUM2INT(tup_num);
	int j = NUM2INT(field_num);

	if(i < 0 || i >= PQntuples(this->pgresult)) {
		rb_raise(rb_eArgError,"invalid tuple number %d", i);
	}
	if(j < 0 || j >= PQnfields(this->pgresult)) {
		rb_raise(rb_eArgError,"invalid field number %d", j);
	}
	return this->p_typemap->funcs.typecast_result_value(this->p_typemap, self, i, j);
}

#inspect

Return a String representation of the object suitable for debugging.

[ GitHub ]

  
# File 'lib/pg/result.rb', line 32

def inspect
	str = self.to_s
	str[-1,0] = if cleared?
		" cleared"
	else
		" status=#{res_status(result_status)} ntuples=#{ntuples} nfields=#{nfields} cmd_tuples=#{cmd_tuples}"
	end
	return str
end

#map_types!(type_map)

Apply a type map for all value retrieving methods.

#type_map: a TypeMap instance.

This method is equal to #type_map= , but returns self, so that calls can be chained.

See also BasicTypeMapForResults

[ GitHub ]

  
# File 'lib/pg/result.rb', line 16

def map_types!(type_map)
	self.type_map = type_map
	return self
end

#nfieldsInteger Also known as: #num_fields

Returns the number of columns in the query result.

[ GitHub ]

  
# File 'ext/pg_result.c', line 730

static VALUE
pgresult_nfields(VALUE self)
{
	return INT2NUM(PQnfields(pgresult_get(self)));
}

#nparamsInteger

Returns the number of parameters of a prepared statement. Only useful for the result returned by conn.describePrepared

[ GitHub ]

  
# File 'ext/pg_result.c', line 1036

static VALUE
pgresult_nparams(VALUE self)
{
	PGresult *result;

	result = pgresult_get(self);
	return INT2FIX(PQnparams(result));
}

#ntuplesInteger Also known as: #num_tuples

Returns the number of tuples in the query result.

[ GitHub ]

  
# File 'ext/pg_result.c', line 712

static VALUE
pgresult_ntuples(VALUE self)
{
	return INT2FIX(PQntuples(pgresult_get(self)));
}

#nfieldsInteger #num_fieldsInteger

Alias for #nfields.

#ntuplesInteger #num_tuplesInteger

Alias for #ntuples.

#oid_valueInteger

Returns the oid of the inserted row if applicable, otherwise nil.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1111

static VALUE
pgresult_oid_value(VALUE self)
{
	Oid n = PQoidValue(pgresult_get(self));
	if (n == InvalidOid)
		return Qnil;
	else
		return UINT2NUM(n);
}

#paramtype(param_number) ⇒ Oid

Returns the Oid of the data type of parameter param_number. Only useful for the result returned by conn.describePrepared

[ GitHub ]

  
# File 'ext/pg_result.c', line 1052

static VALUE
pgresult_paramtype(VALUE self, VALUE param_number)
{
	PGresult *result;

	result = pgresult_get(self);
	return UINT2NUM(PQparamtype(result,NUM2INT(param_number)));
}

#res_statusString #res_status(status) ⇒ String

Returns the string representation of the status of the result or of the provided status.

[ GitHub ]

  
# File 'ext/pg_result.c', line 584

static VALUE
pgresult_res_status(int argc, VALUE *argv, VALUE self)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	VALUE ret;

	if( argc == 0 ){
		ret = rb_str_new2(PQresStatus(PQresultStatus(this->pgresult)));
	}else if( argc == 1 ){
		ret = rb_str_new2(PQresStatus(NUM2INT(argv[0])));
	}else{
		rb_raise(rb_eArgError, "only 0 or 1 arguments expected");
	}
	PG_ENCODING_SET_NOCHECK(ret, this->enc_idx);
	return ret;
}

#error_field(fieldcode) ⇒ String #result_error_field(fieldcode) ⇒ String

Alias for #error_field.

#error_messageString #result_error_messageString

Alias for #error_message.

#result_statusInteger

Returns the status of the query. The status value is one of:

  • PGRES_EMPTY_QUERY

  • PGRES_COMMAND_OK

  • PGRES_TUPLES_OK

  • PGRES_COPY_OUT

  • PGRES_COPY_IN

  • PGRES_BAD_RESPONSE

  • PGRES_NONFATAL_ERROR

  • PGRES_FATAL_ERROR

  • PGRES_COPY_BOTH

  • PGRES_SINGLE_TUPLE

  • PGRES_PIPELINE_SYNC

  • PGRES_PIPELINE_ABORTED

Use res.res_status to retrieve the string representation.

[ GitHub ]

  
# File 'ext/pg_result.c', line 557

static VALUE
pgresult_result_status(VALUE self)
{
	return INT2FIX(PQresultStatus(pgresult_get(self)));
}

#verbose_error_message(verbosity, show_context) ⇒ String #result_verbose_error_message(verbosity, show_context) ⇒ String

#stream_each {|tuple| ... }

Invokes block for each tuple in the result set in single row mode.

This is a convenience method for retrieving all result tuples as they are transferred. It is an alternative to repeated calls of Connection#get_result , but given that it avoids the overhead of wrapping each row into a dedicated result object, it delivers data in nearly the same speed as with ordinary results.

The base result must be in status PGRES_SINGLE_TUPLE. It iterates over all tuples until the status changes to PGRES_TUPLES_OK. A Error is raised for any errors from the server.

Row description data does not change while the iteration. All value retrieval methods refer to only the current row. #ntuples returns 1 while the iteration and 0 after all tuples were yielded.

Example:

conn.send_query( "first SQL query; second SQL query" )
conn.set_single_row_mode
conn.get_result.stream_each do |row|
  # do something with each received row of the first query
end
conn.get_result.stream_each do |row|
  # do something with each received row of the second query
end
conn.get_result  # => nil   (no more results)
[ GitHub ]

  
# File 'ext/pg_result.c', line 1594

static VALUE
pgresult_stream_each(VALUE self)
{
	return pgresult_stream_any(self, yield_hash, NULL);
}

#stream_each_row {|row| ... }

Yields each row of the result set in single row mode. The row is a list of column values.

This method works equally to #stream_each , but yields an Array of values.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1610

static VALUE
pgresult_stream_each_row(VALUE self)
{
	return pgresult_stream_any(self, yield_array, NULL);
}

#stream_each_tuple {|tuple| ... }

Yields each row of the result set in single row mode.

This method works equally to #stream_each , but yields a Tuple object.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1624

static VALUE
pgresult_stream_each_tuple(VALUE self)
{
	/* allocate VALUEs that are shared between all streamed tuples */
	ensure_init_for_tuple(self);

	return pgresult_stream_any(self, yield_tuple, NULL);
}

#tuple(n) ⇒ PG::Tuple

Returns a Tuple from the nth row of the result.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1346

static VALUE
pgresult_tuple(VALUE self, VALUE index)
{
	int tuple_num = NUM2INT( index );
	t_pg_result *this;
	int num_tuples;

	this = pgresult_get_this_safe(self);
	num_tuples = PQntuples(this->pgresult);

	if ( tuple_num < 0 || tuple_num >= num_tuples )
		rb_raise( rb_eIndexError, "Index %d is out of range", tuple_num );

	ensure_init_for_tuple(self);

  return pg_tuple_new(self, tuple_num);
}

#tuple_values(n) ⇒ Array

Returns an Array of the field values from the nth row of the result.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1293

static VALUE
pgresult_tuple_values(VALUE self, VALUE index)
{
	int tuple_num = NUM2INT( index );
	t_pg_result *this;
	int field;
	int num_tuples;
	int num_fields;

	this = pgresult_get_this_safe(self);
	num_tuples = PQntuples(this->pgresult);
	num_fields = PQnfields(this->pgresult);

	if ( tuple_num < 0 || tuple_num >= num_tuples )
		rb_raise( rb_eIndexError, "Index %d is out of range", tuple_num );

	{
		PG_VARIABLE_LENGTH_ARRAY(VALUE, row_values, num_fields, PG_MAX_COLUMNS)

		/* populate the row */
		for ( field = 0; field < num_fields; field++ ) {
			row_values[field] = this->p_typemap->funcs.typecast_result_value(this->p_typemap, self, tuple_num, field);
		}
		return rb_ary_new4( num_fields, row_values );
	}
}

#valuesArray

Returns all tuples as an array of arrays.

[ GitHub ]

  
# File 'ext/pg_result.c', line 1198

static VALUE
pgresult_values(VALUE self)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	int row;
	int field;
	int num_rows = PQntuples(this->pgresult);
	int num_fields = PQnfields(this->pgresult);
	VALUE results = rb_ary_new2( num_rows );

	for ( row = 0; row < num_rows; row++ ) {
		PG_VARIABLE_LENGTH_ARRAY(VALUE, row_values, num_fields, PG_MAX_COLUMNS)

		/* populate the row */
		for ( field = 0; field < num_fields; field++ ) {
			row_values[field] = this->p_typemap->funcs.typecast_result_value(this->p_typemap, self, row, field);
		}
		rb_ary_store( results, row, rb_ary_new4( num_fields, row_values ) );
	}

	return results;
}

#verbose_error_message(verbosity, show_context) ⇒ String Also known as: #result_verbose_error_message

Returns a reformatted version of the error message associated with a PGresult object.

Available since PostgreSQL-9.6

[ GitHub ]

  
# File 'ext/pg_result.c', line 625

static VALUE
pgresult_verbose_error_message(VALUE self, VALUE verbosity, VALUE show_context)
{
	t_pg_result *this = pgresult_get_this_safe(self);
	VALUE ret;
	char *c_str;

	c_str = PQresultVerboseErrorMessage(this->pgresult, NUM2INT(verbosity), NUM2INT(show_context));
	if(!c_str)
		rb_raise(rb_eNoMemError, "insufficient memory to format error message");

	ret = rb_str_new2(c_str);
	PQfreemem(c_str);
	PG_ENCODING_SET_NOCHECK(ret, this->enc_idx);

	return ret;
}