Created
March 28, 2014 19:17
-
-
Save gstark/9840818 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ActiveRecord | |
class Base | |
# Define a method that can be called on an ActiveRecord::Base class | |
# or on a Scope object. This will call the db-adapters select_and_yield | |
# to perform the query and yield back each row found. Each row is then | |
# instantiated into an object and yielded to the caller. | |
def self.yield_all(*args) | |
raise "Must supply block" unless block_given? | |
options = args.extract_options! | |
validate_find_options(options) | |
set_readonly_option!(options) | |
sql = construct_finder_sql(options) | |
connection.select_and_yield(sanitize_sql(sql), "#{name} Load") do |record| | |
record.readonly! if options[:readonly] && record.respond_to?(:readonly) | |
object = instantiate(record) | |
yield object | |
end | |
end | |
end | |
module ConnectionAdapters | |
module DatabaseStatements | |
def yield_all(sql, name = nil) | |
select_and_yield(sql, name) | |
end | |
end | |
class JdbcAdapter < AbstractAdapter | |
def select_and_yield(sql, name = nil) | |
select(sql, name).each do |row| | |
yield row | |
end | |
end | |
end | |
MYSQL_SUPERCLASS = defined?(JRuby) ? JdbcAdapter : AbstractAdapter | |
class MysqlAdapter < MYSQL_SUPERCLASS | |
def select_and_yield(sql, name = nil) | |
if @connection.respond_to?(:query_with_result) | |
@connection.query_with_result = true | |
end | |
result = execute(sql, name) | |
if @connection.respond_to?(:query_with_result) | |
result.each_hash do |row| | |
yield row | |
end | |
else | |
result.each do |row| | |
yield row | |
end | |
end | |
ensure | |
result.free if result.respond_to?(:free) | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment