Skip to content

Instantly share code, notes, and snippets.

@ssoroka
Created June 30, 2011 15:32
Show Gist options
  • Select an option

  • Save ssoroka/1056480 to your computer and use it in GitHub Desktop.

Select an option

Save ssoroka/1056480 to your computer and use it in GitHub Desktop.
active_record_sql_counter.rb
module ActiveRecord
class SQLCounter
IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/]
# FIXME: this needs to be refactored so specific database can add their own
# ignored SQL. This ignored SQL is for Oracle.
IGNORED_SQL.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im]
def initialize
$queries_executed = []
end
def call(name, start, finish, message_id, values)
sql = values[:sql]
# FIXME: this seems bad. we should probably have a better way to indicate
# the query was cached
unless 'CACHE' == values[:name]
$queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r }
end
end
end
ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new)
end
class AssociationPreloadingTest < ActiveRecord::TestCase
test "association preloading doesn't fetch all records" do
assert_queries(3) {
@products = Product.limit(3).preload(:variants => :adjustments)
@products.each{|product|
product.variants.map{|v| v.adjustments.map{|arr| arr.map(&:quantity).sum }}
}
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment