Thursday, February 25, 2010

TRUNCATE All Tables in a Ruby on Rails

There might be a case where you need to delete all the rows from all the tables in the database to end up with just the structure(a bare DB). The right thing to do is to run the TRUNCATE command on all the tables. It will delete all the data and also reset the auto increment value. But the only current way to get a bare DB in rails now is to run rake db:reset. This will run rake db:drop, rake db:create and rake db:migrate. The downside of this is that if you have a reasonable number of migrations this command can take quite some time to run which is really not efficient when you are iterating fast. Hence following rake task will
TRUNCATE all the tables.

namespace :db do
task :load_config => :rails_env do
require 'active_record'
ActiveRecord::Base.configurations = Rails::Configuration.new.database_configuration
end

desc "Create Sample Data for the application"
task(:truncate => :load_config) do
begin
config = ActiveRecord::Base.configurations[RAILS_ENV]
ActiveRecord::Base.establish_connection
case config["adapter"]
when "mysql"
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
end
when "sqlite", "sqlite3"
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute("DELETE FROM #{table}")
ActiveRecord::Base.connection.execute("DELETE FROM sqlite_sequence where name='#{table}'")
end
ActiveRecord::Base.connection.execute("VACUUM")
end
rescue
$stderr.puts "Error while truncating. Make sure you have a valid database.yml file and have created the database tables before running this command. You should be able to run rake db:migrate without an error"
end
end
end


Just create a file named db_truncate.rake in your lib/tasks directory
with this code in it. Save the file and then run rake db:truncate. Your
database now should have no data now. Before you run the task make sure
that you have a valid database.yml file and have created the database
tables before running this command. You should be able to run rake
db:migrate without an error

In case you want to truncate a single table from database all you have to do is
ActiveRecord::Base.connection.execute("TRUNCATE table_name")



No comments:

Post a Comment