Use count(*) > 0 instead of count(*)

count(*) requires searching the entire table, which may be large.
Querying for count(*) > 0 allows MySQL to give up after a single row
is found. Since all we are doing is checking whether the row has
a single table, it should be faster to use count(*) > 0.
This commit is contained in:
Kevin Burke 2018-04-23 15:20:15 -07:00
parent eeb56d7bf6
commit f3feaa36ba
No known key found for this signature in database
GPG key ID: 856E0AC03A576E7F
2 changed files with 3 additions and 3 deletions

View file

@ -56,7 +56,7 @@ module DatabaseCleaner::ActiveRecord
@db_name ||= connection.instance_variable_get('@config')[:database]
stats = table_stats_query(connection, @db_name)
if stats != ''
connection.exec_query(stats).inject([]) {|all, stat| all << stat['table_name'] if stat['exact_row_count'] > 0; all }
connection.exec_query(stats).inject([]) {|all, stat| all << stat['table_name'] if stat['has_rows'] == 1; all }
else
[]
end
@ -73,7 +73,7 @@ module DatabaseCleaner::ActiveRecord
AND #{::DatabaseCleaner::ActiveRecord::Base.exclusion_condition('table_name')};
SQL
queries = tables.map do |table|
"SELECT #{connection.quote(table)} AS table_name, COUNT(*) AS exact_row_count FROM #{connection.quote_table_name(table)}"
"SELECT #{connection.quote(table)} AS table_name, COUNT(*) > 0 AS has_rows FROM #{connection.quote_table_name(table)}"
end
@table_stats_query = queries.join(' UNION ')
end

View file

@ -25,7 +25,7 @@ module DatabaseCleaner
end
def ensure_counts(expected_counts)
# I had to add this sanity_check garbage because I was getting non-determinisc results from mongo at times..
# I had to add this sanity_check garbage because I was getting non-deterministic results from mongo at times..
# very odd and disconcerting...
expected_counts.each do |model_class, expected_count|
actual_count = model_class.count