Created
January 13, 2012 08:21
-
-
Save kazukeyan/1605067 to your computer and use it in GitHub Desktop.
add rake task "db:truncate:x" and "db:truncate:all"
This file contains hidden or 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
データベースのTRUNCATEができるtaskの追加
PostgresQLは検証済み
こちらの方のスクリプトを参考に
【Nothing stays the same • rake task for truncate db tables:http://blog.agustinvinao.com.ar/post/10528516587/rake-task-for-truncate-db-tables 】