Merge pull request #567 from buehmann/refactor/mysql-deletion

Refactor MySQL deletion strategy (AR)
This commit is contained in:
Ernesto Tagwerker 2018-11-20 00:00:46 -05:00 committed by GitHub
commit 4c2408ffdb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -53,30 +53,31 @@ module DatabaseCleaner::ActiveRecord
end
def tables_with_new_rows(connection)
@db_name ||= connection.instance_variable_get('@config')[:database]
stats = table_stats_query(connection, @db_name)
stats = table_stats_query(connection)
if stats != ''
connection.exec_query(stats).inject([]) {|all, stat| all << stat['table_name'] if stat['has_rows'] == 1; all }
connection.select_values(stats)
else
[]
end
end
def table_stats_query(connection, db_name)
if @cache_tables && !@table_stats_query.nil?
return @table_stats_query
else
tables = connection.select_values(<<-SQL)
SELECT table_name
FROM information_schema.tables
WHERE table_schema = '#{db_name}'
AND #{::DatabaseCleaner::ActiveRecord::Base.exclusion_condition('table_name')};
SQL
queries = tables.map do |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 ')
def table_stats_query(connection)
@table_stats_query ||= build_table_stats_query(connection)
ensure
@table_stats_query = nil unless @cache_tables
end
def build_table_stats_query(connection)
tables = connection.select_values(<<-SQL)
SELECT table_name
FROM information_schema.tables
WHERE table_schema = database()
AND #{::DatabaseCleaner::ActiveRecord::Base.exclusion_condition('table_name')};
SQL
queries = tables.map do |table|
"(SELECT #{connection.quote(table)} FROM #{connection.quote_table_name(table)} LIMIT 1)"
end
queries.join(' UNION ALL ')
end
def information_schema_exists? connection