Class: RDO::Result

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

Overview

The standard Result class returned by Connection#execute.

Both read and write queries receive results in this format.

Instance Method Summary collapse

Constructor Details

#initialize(tuples, info = {}) ⇒ Result

Initialize a new Result.

Parameters:

  • tuples (Enumerable)

    a list of tuples, provided by the driver

  • info (Hash) (defaults to: {})

    information about the result, including:

    • count

    • rows_affected

    • insert_id

    • execution_time



26
27
28
29
# File 'lib/rdo/result.rb', line 26

def initialize(tuples, info = {})
  @info   = info.dup
  @tuples = tuples
end

Instance Method Details

#affected_rowsFixnum

Return the number of rows affected by the query.

Returns:

  • (Fixnum)

    the number of rows affected



70
71
72
# File 'lib/rdo/result.rb', line 70

def affected_rows
  info[:affected_rows].to_i
end

#countObject

Get the number of rows in the result.

Many drivers provide the count, otherwise it will be computed at runtime.

Returns:

  • Fixnum the number of rows in the Result



80
81
82
83
84
85
86
# File 'lib/rdo/result.rb', line 80

def count
  if info[:count].nil? || block_given?
    super
  else
    info[:count].to_i
  end
end

#each(&block) ⇒ Object

Iterate over all rows returned by the connection.

For each row, a Symbol-keyed Hash is yielded into the block.



107
108
109
# File 'lib/rdo/result.rb', line 107

def each(&block)
  tap{ @tuples.each(&block) }
end

#empty?Boolean

Check if the result has no rows.

Returns:

  • (Boolean)

    true if the result has no returned rows



92
93
94
# File 'lib/rdo/result.rb', line 92

def empty?
  count.zero?
end

#execution_timeFloat

Get the time spent processing the statement.

Returns:

  • (Float)

    the time in seconds spent executing the query



100
101
102
# File 'lib/rdo/result.rb', line 100

def execution_time
  info[:execution_time].to_f
end

#first_valueObject

If only one column and one row is expected in the result, fetch it.

If no rows were returned, this method returns nil.

Returns:

  • (Object)

    a single value at the first column in the first row of the result



60
61
62
63
64
# File 'lib/rdo/result.rb', line 60

def first_value
  if row = first
    row.values.first
  end
end

#infoHash

Get raw result info provided by the driver.

Returns:

  • (Hash)

    aribitrary information provided about the result



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

def info
  @info
end

#insert_idObject

Return the inserted row ID.

For some drivers this requires that a RETURNING clause by used in SQL. It may be more desirable to simply check the rows in the result.

Returns:

  • (Object)

    the ID of the record just inserted, or nil



46
47
48
49
50
51
52
# File 'lib/rdo/result.rb', line 46

def insert_id
  if info.key?(:insert_id)
    info[:insert_id]
  else
    first_value
  end
end