PG::
Result class
| Superclass | rb_cObject |
| Included Modules |
|
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 an immutable memory block attached to the PG::Result object unless streaming is used.
A PG::Result has various ways to retrieve the result data:
require 'pg' conn = PG.connect(dbname: 'test') res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.num_fields # 3 res.num_tuples # 1 res.fname(2) # "c" res.fields # ["a", "b", "c"] res.getvalue(0,0) # '1' res[0] # {"a" => "1", "b" => "2", "c" => "3"} res.tuple_values(0) # ["1", "2", nil] res.tuple(0) # #<PG::Tuple a: "1", b: "2", c: nil> res.values # [["1", "2", nil]] res.field_values(:a) # ["1"] res.column_values(1) # ["2"] res.each.first # {"a" => "1", "b" => "2", "c" => nil} res.each_row.first # ["1", "2", nil]
Whenever a value is accessed it is casted to a Ruby object by the assigned type_map which is PG::TypeMapAllStrings by default. Similarly field names can be retrieved either as strings (default) or as symbols which can be switched per field_name_type= .
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.type_map = PG::TypeMapByColumn.new([PG::TextDecoder::Integer.new]*3) res.field_name_type = :symbol res.fname(2) # :c res.fields # [:a, :b, :c] res.getvalue(0,0) # 1 res[0] # {a: 1, b: 2, c: nil} res.tuple_values(0) # [1, 2, nil] res.tuple(0) # #<PG::Tuple a: 1, b: 2, c: nil> res.values # [[1, 2, nil]] res.field_values(:a) # [1] res.column_values(1) # [2] res.each.first # {a: 1, b: 2, c: nil} res.each_row.first # [1, 2, nil]
Since pg-1.1 the amount of memory in use by a PG::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.
Public Class Methods
Returns the string representation of result_status.
Public Instance Methods
Returns tuple n as a hash.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res[0] # {"a" => "1", "b" => "2", "c" => "3"}
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 PG::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 PG::Result#clear .
Returns 1 if the PG::Result 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 PG::Result to contain text data in some columns and binary data in others. Result#fformat is preferred. binary_tuples returns 1 only if all columns of the result are binary (format 1).
Raises appropriate exception if PG::Result is in a bad state, which is:
-
PGRES_BAD_RESPONSE -
PGRES_FATAL_ERROR -
PGRES_NONFATAL_ERROR -
PGRES_PIPELINE_ABORTED
Raises appropriate exception if PG::Result is in a bad state, which is:
-
PGRES_BAD_RESPONSE -
PGRES_FATAL_ERROR -
PGRES_NONFATAL_ERROR -
PGRES_PIPELINE_ABORTED
Clears the PG::Result object as the result of a query. This frees all underlying memory consumed by the result object. Afterwards access to result methods raises PG::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 PG::Tuple objects are used. In this case clear must not be called unless all PG::Tuple objects of this result are fully materialized.
If PG::Result#autoclear? is true then the result is only marked as cleared but clearing the underlying C struct will happen when the callback returns.
Returns true if the backend result memory has been freed.
Returns the status string of the last query command.
Returns the number of tuples (rows) affected by the SQL command.
If the SQL command that generated the PG::Result was not one of:
-
SELECT -
CREATE TABLE AS -
INSERT -
UPDATE -
DELETE -
MOVE -
FETCH -
COPY -
an
EXECUTEof a prepared query that contains anINSERT,UPDATE, orDELETEstatement
or if no tuples were affected, 0 is returned.
Returns the number of tuples (rows) affected by the SQL command.
If the SQL command that generated the PG::Result was not one of:
-
SELECT -
CREATE TABLE AS -
INSERT -
UPDATE -
DELETE -
MOVE -
FETCH -
COPY -
an
EXECUTEof a prepared query that contains anINSERT,UPDATE, orDELETEstatement
or if no tuples were affected, 0 is returned.
Returns an Array of the values from the nth column of each tuple in the result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.column_values(1) # ["2"]
Yields a Hash object for each row in the result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.each.first # {"a" => "1", "b" => "2", "c" => nil}
Yields an Array object for each row in the result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.each_row.first # ["1", "2", nil]
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"]
Returns the error message of the command as a string.
Returns the format (0 for text, 1 for binary) of column column_number.
Raises ArgumentError if column_number is out of range.
Get type of field names.
See description at field_name_type=
Set type of field names specific to this result. It can be set to one of:
-
:stringto use String based field names -
:symbolto use Symbol based field names -
:static_symbolto use pinned Symbol (can not be garbage collected) - Don’t use this, it will probably be removed in future.
The default is retrieved from PG::Connection#field_name_type , which defaults to :string .
This setting affects several result methods:
-
keys of Hash returned by
[],eachandstream_each -
field names used by
tupleandstream_each_tuple
The type of field names can only be changed before any of the affected methods have been called.
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.
Returns an Array of the values from the given field of each tuple in the result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.field_values(:a) # ["1"]
Depending on field_name_type= returns an array of strings or symbols representing the names of the fields in the result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.fields # ["a", "b", "c"]
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.
Returns the name of the column corresponding to index. Depending on field_name_type= it’s a String or Symbol.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.fname(2) # "c"
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.
Freeze the PG::Result object and unlink the result from the related PG::Connection.
A frozen PG::Result object doesn’t allow any streaming and it can’t be cleared. It also denies setting a type_map or field_name_type.
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
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.
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.
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.
Returns true if the specified value is nil; false otherwise.
Returns the (String) length of the field in bytes.
Equivalent to res.value(tup_num,field_num).length.
Returns the value in tuple number tup_num, field field_num, or nil if the field is NULL.
Return a String representation of the object suitable for debugging.
Apply a type map for all value retrieving methods.
type_map: a PG::TypeMap instance.
This method is equal to type_map= , but returns self, so that calls can be chained.
See also PG::BasicTypeMapForResults
Returns the number of columns in the query result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.nfields # 3 res.num_fields # 3
Returns the number of parameters of a prepared statement. Only useful for the result returned by conn.describePrepared
Returns the number of tuples in the query result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.ntuples # 1 res.num_tuples # 1
Returns the number of columns in the query result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.nfields # 3 res.num_fields # 3
Returns the number of tuples in the query result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.ntuples # 1 res.num_tuples # 1
Returns the oid of the inserted row if applicable, otherwise nil.
Returns the Oid of the data type of parameter param_number. Only useful for the result returned by conn.describePrepared
res_status( status ) → String
Returns the string representation of the status of the result or of the provided result_status.
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"]
Returns the error message of the command as a string.
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_TUPLES_CHUNK -
PGRES_PIPELINE_SYNC -
PGRES_PIPELINE_ABORTED
Use res_status or Result.res_status to retrieve the string representation.
Returns a reformatted version of the error message associated with the PG::Result object.
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 PG::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 or PGRES_TUPLES_CHUNK. It iterates over all tuples until the status changes to PGRES_TUPLES_OK. A PG::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. Result#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)
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.
Yields each row of the result set in single row mode.
This method works equally to stream_each , but yields a PG::Tuple object.
Returns a PG::Tuple from the nth row of the result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.tuple(0) # #<PG::Tuple a: "1", b: "2", c: nil>
Returns an Array of the field values from the nth row of the result.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.tuple_values(0) # ["1", "2", nil]
Returns the PG::TypeMap that is currently set for type casts of result values to ruby objects. The default is retrieved from PG::Connection#type_map_for_results , which defaults to PG::TypeMapAllStrings .
Set the PG::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 PG::TypeMap .
See also map_types! and PG::BasicTypeMapForResults
Returns all tuples as an array of arrays.
res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') res.values # [["1", "2", nil]]
Returns a reformatted version of the error message associated with the PG::Result object.