class PG::Result

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.