2010-10-12 22:57:26 +00:00
|
|
|
module ActiveRecord
|
|
|
|
###
|
2011-04-11 02:08:20 +00:00
|
|
|
# This class encapsulates a Result returned from calling +exec_query+ on any
|
2011-05-23 23:58:25 +00:00
|
|
|
# database connection adapter. For example:
|
2010-10-12 22:57:26 +00:00
|
|
|
#
|
2011-04-11 02:08:20 +00:00
|
|
|
# x = ActiveRecord::Base.connection.exec_query('SELECT * FROM foo')
|
2010-10-12 22:57:26 +00:00
|
|
|
# x # => #<ActiveRecord::Result:0xdeadbeef>
|
|
|
|
class Result
|
|
|
|
include Enumerable
|
|
|
|
|
2012-02-07 19:51:30 +00:00
|
|
|
attr_reader :columns, :rows, :column_types
|
2010-10-12 22:57:26 +00:00
|
|
|
|
2012-08-21 16:23:40 +00:00
|
|
|
def initialize(columns, rows, column_types = {})
|
2012-09-20 04:43:36 +00:00
|
|
|
@columns = columns
|
2012-02-07 19:51:30 +00:00
|
|
|
@rows = rows
|
|
|
|
@hash_rows = nil
|
2012-08-21 16:23:40 +00:00
|
|
|
@column_types = column_types
|
2010-10-12 22:57:26 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def each
|
|
|
|
hash_rows.each { |row| yield row }
|
|
|
|
end
|
|
|
|
|
2011-02-05 02:08:31 +00:00
|
|
|
def to_hash
|
|
|
|
hash_rows
|
|
|
|
end
|
|
|
|
|
2012-01-26 23:16:12 +00:00
|
|
|
alias :map! :map
|
|
|
|
alias :collect! :map
|
|
|
|
|
2012-05-07 11:43:05 +00:00
|
|
|
# Returns true if there are no records.
|
2012-01-26 23:16:12 +00: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-27 00:51:54 +00:00
|
|
|
def initialize_copy(other)
|
|
|
|
@columns = columns.dup
|
|
|
|
@rows = rows.dup
|
|
|
|
@hash_rows = nil
|
|
|
|
end
|
|
|
|
|
2010-10-12 22:57:26 +00:00
|
|
|
private
|
|
|
|
def hash_rows
|
2012-09-20 15:59:31 +00:00
|
|
|
@hash_rows ||=
|
|
|
|
begin
|
|
|
|
# We freeze the strings to prevent them getting duped when
|
|
|
|
# used as keys in ActiveRecord::Model's @attributes hash
|
|
|
|
columns = @columns.map { |c| c.dup.freeze }
|
|
|
|
@rows.map { |row|
|
|
|
|
Hash[columns.zip(row)]
|
|
|
|
}
|
|
|
|
end
|
2010-10-12 22:57:26 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|