Created
August 3, 2012 10:28
-
-
Save tvdeyen/3246525 to your computer and use it in GitHub Desktop.
Fast rails database truncation with sqlite support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This didn't work for me on heroku. I had to change line 2 to
and change all instances of
to
Also, see my adaptation of this code for truncating a single table: https://gist.github.com/bergonom/5173714