Skip to content

Only send a single query for all deletion alterations #113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions lib/database_cleaner/active_record/deletion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,29 @@ def clean
private

def delete_tables(connection, table_names)
statements = []

table_names.each do |table_name|
delete_table(connection, table_name)
reset_id_sequence(connection, table_name) if @reset_ids
statements << delete_table_sql(connection, table_name)
statements << reset_id_sequence_sql(connection, table_name) if @reset_ids
end

connection.execute(statements.join)
end

def delete_table connection, table_name
connection.execute("DELETE FROM #{connection.quote_table_name(table_name)} WHERE 1=1")
def delete_table_sql connection, table_name
"DELETE FROM #{connection.quote_table_name(table_name)};"
end

def reset_id_sequence connection, table_name
def reset_id_sequence_sql connection, table_name
case connection.adapter_name
when 'Mysql2', 'Trilogy'
connection.execute("ALTER TABLE #{table_name} AUTO_INCREMENT = 1;")
when 'SQLite'
connection.execute("delete from sqlite_sequence where name='#{table_name}';")
when 'PostgreSQL'
connection.reset_pk_sequence!(table_name)
when "Mysql2", "Trilogy"
"ALTER TABLE #{table_name} AUTO_INCREMENT = 1;"
when "SQLite"
"delete from sqlite_sequence where name='#{table_name}';"
when "PostgreSQL"
_, sequence_name = pk_and_sequence_for(table)
"ALTER SEQUENCE #{sequence_name} RESTART WITH 1;"
else
raise "reset_id option not supported for #{connection.adapter_name}"
end
Expand Down