Class: DB::Postgres::Native::Result

Inherits:
FFI::Pointer
  • Object
show all
Defined in:
lib/db/postgres/native/result.rb

Overview

A result set from a database query with row iteration and type casting.

Instance Method Summary collapse

Constructor Details

#initialize(connection, types = {}, address) ⇒ Result

Initialize a new result set wrapper.



47
48
49
50
51
52
53
54
# File 'lib/db/postgres/native/result.rb', line 47

def initialize(connection, types = {}, address)
	super(address)
	
	@connection = connection
	@fields = nil
	@types = types
	@casts = nil
end

Instance Method Details

#cast!(row) ⇒ Object

Cast row values to appropriate Ruby types.



83
84
85
86
87
88
89
90
91
92
93
# File 'lib/db/postgres/native/result.rb', line 83

def cast!(row)
	@casts ||= self.field_types
	
	row.size.times do |index|
		if cast = @casts[index]
			row[index] = cast.parse(row[index])
		end
	end
	
	return row
end

#eachObject

Iterate over each row in the result set.



98
99
100
101
102
103
104
# File 'lib/db/postgres/native/result.rb', line 98

def each
	row_count.times do |i|
		yield cast!(get_row(i))
	end
	
	Native.clear(self)
end

#field_countObject

Get the number of fields in this result set.



58
59
60
# File 'lib/db/postgres/native/result.rb', line 58

def field_count
	Native.field_count(self)
end

#field_namesObject

Get the field names for this result set.



70
71
72
# File 'lib/db/postgres/native/result.rb', line 70

def field_names
	field_count.times.collect{|i| Native.field_name(self, i)}
end

#field_typesObject

Get the type converters for each field.



64
65
66
# File 'lib/db/postgres/native/result.rb', line 64

def field_types
	field_count.times.collect{|i| @types[Native.field_type(self, i)]}
end

#map(&block) ⇒ Object

Map over each row in the result set.



110
111
112
113
114
115
116
117
118
# File 'lib/db/postgres/native/result.rb', line 110

def map(&block)
	results = []
	
	self.each do |row|
		results << yield(row)
	end
	
	return results
end

#row_countObject

Get the number of rows in this result set.



76
77
78
# File 'lib/db/postgres/native/result.rb', line 76

def row_count
	Native.row_count(self)
end

#to_aObject

Convert the entire result set to an array.



122
123
124
125
126
127
128
129
130
# File 'lib/db/postgres/native/result.rb', line 122

def to_a
	rows = []
	
	self.each do |row|
		rows << row
	end
	
	return rows
end