Skip to content

Instantly share code, notes, and snippets.

@bitkidd
Forked from kazukeyan/db_truncate_x.rb
Created April 25, 2016 22:38
Show Gist options
  • Save bitkidd/907e8fdffb110e54cf28b8f44ead01ed to your computer and use it in GitHub Desktop.
Save bitkidd/907e8fdffb110e54cf28b8f44ead01ed to your computer and use it in GitHub Desktop.
add rake task "db:truncate:x" and "db:truncate:all"
namespace :db do
def detect_env
ENV['RAILS_ENV'] || 'development'
end
def truncate(table)
begin
case @config["adapter"]
when "mysql", "mysql2"
ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
puts "Table #{table} truncated!"
when "sqlite", "sqlite3"
ActiveRecord::Base.connection.execute("DELETE FROM #{table}")
puts "Table #{table} deleted!"
ActiveRecord::Base.connection.execute("DELETE FROM sqlite_sequence where name='#{table}'")
puts "sqlite_sequence of #{table} deleted!"
ActiveRecord::Base.connection.execute("VACUUM")
puts "database vacuumed!"
when "postgresql"
# if you use postgresql 8.4 or later, you can use "TRUNCATE XXX RESTART IDENTITY"
# ActiveRecord::Base.connection.execute("TRUNCATE #{table} RESTART IDENTITY")
# puts "Table #{table} truncated!(with RESTART IDENTITY)"
ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
puts "Table #{table} truncated!"
ActiveRecord::Base.connection.execute("SELECT setval('#{table}_id_seq', 1, false)");
puts "Sequence (#{table}_id_seq) is reset!"
end
rescue => ex
puts "#{ex}"
end
end
namespace :truncate do
data_source = YAML.load_file(Rails.root.join('config', 'database.yml'))
# ActiveRecord::Base.configurations[detect_env]
@config = data_source[detect_env]
@connection = ActiveRecord::Base.establish_connection(@config)
@tables = ActiveRecord::Base.connection.tables
@tables.each do |table|
unless ['schema_migrations'].include?(table)
desc "Truncate #{table} table"
task table => :environment do
truncate(table)
end
end
end
desc "Truncate all the tables in the database"
task :all => :environment do
puts 'Notice: db:truncate:all is disabled because preventing you to truncate tables by mistakes'
# @tables.each do |table|
# unless ['schema_migrations'].include?(table)
# truncate(table)
# end
# end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment