Change - Know that nothing stays the same

rake task for truncate db tables

September 22, 2011

ruby

When I’m programming a new project it’s a common need clean the database in the first steps, to much models news, specs, etc.

Here you have one task, the method “detectenv” explains by it self, the task db:truncate to truncate the tables. Remember mysql use TRUNCATE instruction to reset the ID value, if we do a ModelName.deleteall the ID of the table doesn’t resets.

namespace :db 
  def detect_env
    ENV[RAILS_ENV] || 'development’
  end
  desc “truncate all the tables in the database”
  task :truncate => :environment do
    begin
      config = ActiveRecord::Base.configurations[detect_env]
      ActiveRecord::Base.establish_connection
      case config[“adapter”]
      when “mysql”, “mysql2”
        ActiveRecord::Base.connection.tables.each do |table|
          unless ['schema_migrations’].include?(table)
            ActiveRecord::Base.connection.execute(TRUNCATE #{table}”)
            puts “Table #{table} truncated!”
          end
        end
      when “sqlite”, “sqlite3”
        ActiveRecord::Base.connection.tables.each do |table|
         unless ['schema_migrations’].include?(table)
            ActiveRecord::Base.connection.execute(DELETE FROM #{table}”)
            ActiveRecord::Base.connection.execute(DELETE FROM sqlite_sequence where name=#{table}’”)
          end
        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 (Supported engine drivers mysql, mysql2, sqlite, sqlite3)end
  end
end

Agustin Vinao
Agustin Vinao.

Paradox: Life is a mystery. Don't waste time trying to figure it out.
Humor: Keep a sense of humor, especially about yourself. It is a strength beyond all measure.
Change: Know that nothing stays the same.