Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fast rails database truncation with sqlite support
def truncate_all_tables
config = ActiveRecord::Base.configurations[::Rails.env]
connection = ActiveRecord::Base.connection
connection.disable_referential_integrity do
connection.tables.each do |table_name|
next if connection.select_value("SELECT count(*) FROM #{table_name}") == 0
case config["adapter"]
when "mysql", "mysql2", "postgresql"
connection.execute("TRUNCATE #{table_name}")
when "sqlite", "sqlite3"
connection.execute("DELETE FROM #{table_name}")
connection.execute("DELETE FROM sqlite_sequence where name='#{table_name}'")
end
end
connection.execute("VACUUM") if config["adapter"] == "sqlite3"
end
end
@bergonom

This comment has been minimized.

Copy link

@bergonom bergonom commented Mar 15, 2013

This didn't work for me on heroku. I had to change line 2 to

config = Rails.configuration.database_configuration

and change all instances of

config["adapter"]

to

config[Rails.env]["adapter"]

Also, see my adaptation of this code for truncating a single table: https://gist.github.com/bergonom/5173714

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.