Class: Rooq::Result

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/rooq/result.rb

Overview

Result wraps a database result set and provides:

  • Symbol keys instead of string keys
  • Automatic type coercion for JSON, JSONB, ARRAY, timestamps, dates
  • Enumerable interface

Examples:

result = ctx.fetch_all(query)
result.each do |row|
  puts row[:title]        # Symbol key access
  puts row[:tags].first   # Array is parsed
  puts row[:metadata]     # JSON is parsed to Hash
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_result, coercer: TypeCoercer.new) ⇒ Result

Returns a new instance of Result.

Parameters:

  • raw_result (PG::Result)

    the raw database result

  • coercer (TypeCoercer) (defaults to: TypeCoercer.new)

    optional custom type coercer



27
28
29
30
31
32
# File 'lib/rooq/result.rb', line 27

def initialize(raw_result, coercer: TypeCoercer.new)
  @raw_result = raw_result
  @coercer = coercer
  @field_info = build_field_info
  @rows = nil
end

Instance Attribute Details

#raw_resultObject (readonly)

Returns the value of attribute raw_result.



23
24
25
# File 'lib/rooq/result.rb', line 23

def raw_result
  @raw_result
end

Instance Method Details

#each {|Hash| ... } ⇒ Object

Yields:

  • (Hash)

    each row with symbol keys



35
36
37
# File 'lib/rooq/result.rb', line 35

def each(&block)
  rows.each(&block)
end

#empty?Boolean

Returns true if no rows.

Returns:

  • (Boolean)

    true if no rows



50
51
52
# File 'lib/rooq/result.rb', line 50

def empty?
  size.zero?
end

#firstHash?

Returns the first row or nil.

Returns:

  • (Hash, nil)

    the first row or nil



40
41
42
# File 'lib/rooq/result.rb', line 40

def first
  rows.first
end

#sizeInteger Also known as: length, count

Returns number of rows.

Returns:

  • (Integer)

    number of rows



55
56
57
# File 'lib/rooq/result.rb', line 55

def size
  @raw_result.ntuples
end

#to_aArray<Hash>

Returns all rows.

Returns:

  • (Array<Hash>)

    all rows



45
46
47
# File 'lib/rooq/result.rb', line 45

def to_a
  rows.dup
end