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
|
|
|
|
2012-08-21 12:23:40 -04:00
|
|
|
def initialize(columns, rows, column_types = {})
|
2012-09-20 00:43:36 -04:00
|
|
|
@columns = columns
|
2012-02-07 14:51:30 -05:00
|
|
|
@rows = rows
|
|
|
|
@hash_rows = nil
|
2012-08-21 12:23:40 -04:00
|
|
|
@column_types = 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|
|
2012-09-20 00:43:36 -04:00
|
|
|
# We freeze the strings to prevent them getting duped when
|
|
|
|
# used as keys in ActiveRecord::Model's @attributes hash
|
|
|
|
columns = @columns.map { |c| c.freeze }
|
|
|
|
Hash[columns.zip(row)]
|
2010-10-12 18:57:26 -04:00
|
|
|
}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|