-
-
Save bitkidd/907e8fdffb110e54cf28b8f44ead01ed to your computer and use it in GitHub Desktop.
add rake task "db:truncate:x" and "db:truncate:all"
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
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