2010-10-12 18:57:26 -04:00
|
|
|
module ActiveRecord
|
|
|
|
###
|
2011-04-10 22:08:20 -04:00
|
|
|
# This class encapsulates a Result returned from calling +exec_query+ on any
|
2011-05-23 19:58:25 -04:00
|
|
|
# database connection adapter. For example:
|
2010-10-12 18:57:26 -04:00
|
|
|
#
|
2011-04-10 22:08:20 -04:00
|
|
|
# x = ActiveRecord::Base.connection.exec_query('SELECT * FROM foo')
|
2010-10-12 18:57:26 -04:00
|
|
|
# x # => #<ActiveRecord::Result:0xdeadbeef>
|
|
|
|
class Result
|
|
|
|
include Enumerable
|
|
|
|
|
2012-02-07 14:51:30 -05:00
|
|
|
attr_reader :columns, :rows, :column_types
|
2010-10-12 18:57:26 -04:00
|
|
|
|
|
|
|
def initialize(columns, rows)
|
2012-02-07 14:51:30 -05:00
|
|
|
@columns = columns
|
|
|
|
@rows = rows
|
|
|
|
@hash_rows = nil
|
|
|
|
@column_types = {}
|
2010-10-12 18:57:26 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def each
|
|
|
|
hash_rows.each { |row| yield row }
|
|
|
|
end
|
|
|
|
|
2011-02-04 21:08:31 -05:00
|
|
|
def to_hash
|
|
|
|
hash_rows
|
|
|
|
end
|
|
|
|
|
2012-01-26 18:16:12 -05:00
|
|
|
alias :map! :map
|
|
|
|
alias :collect! :map
|
|
|
|
|
2012-05-07 07:43:05 -04:00
|
|
|
# Returns true if there are no records.
|
2012-01-26 18:16:12 -05:00
|
|
|
def empty?
|
|
|
|
rows.empty?
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_ary
|
|
|
|
hash_rows
|
|
|
|
end
|
|
|
|
|
|
|
|
def [](idx)
|
|
|
|
hash_rows[idx]
|
|
|
|
end
|
|
|
|
|
|
|
|
def last
|
|
|
|
hash_rows.last
|
|
|
|
end
|
|
|
|
|
2012-01-26 19:51:54 -05:00
|
|
|
def initialize_copy(other)
|
|
|
|
@columns = columns.dup
|
|
|
|
@rows = rows.dup
|
|
|
|
@hash_rows = nil
|
|
|
|
end
|
|
|
|
|
2010-10-12 18:57:26 -04:00
|
|
|
private
|
|
|
|
def hash_rows
|
|
|
|
@hash_rows ||= @rows.map { |row|
|
2011-01-05 16:50:08 -05:00
|
|
|
Hash[@columns.zip(row)]
|
2010-10-12 18:57:26 -04:00
|
|
|
}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|