class SqlFixtures::TableRefresher

Constants

BASE_DIR
CONSTRAINTS_DIR
DATA_DIR
STRUCTURE_DIR

Public Instance Methods

refresh_tables!(*tables_to_reload) click to toggle source
# File lib/sql_fixtures/table_refresher.rb, line 11
def refresh_tables! *tables_to_reload
  unless Rails.env.test?
    ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration["test"])
  end
  all_tables = ActiveRecord::Base.connection.tables
  db_name = Rails.configuration.database_configuration["test"]["database"]

  # disable FK checks
  all_tables.each do |table|
    ActiveRecord::Base.connection.execute "ALTER TABLE #{table} DISABLE TRIGGER ALL;"
  end

  # reset the given tables
  tables_to_reload.each do |table|
    data_sql = DATA_DIR.join "#{table}.sql"

    ActiveRecord::Base.connection.execute %Q`DELETE FROM "#{table}";`
    system "psql #{db_name} < #{data_sql} > /dev/null"

    # TODO reset id sequences in case they're off
  end

  # re-enable FK checks
  all_tables.each do |table|
    ActiveRecord::Base.connection.execute "ALTER TABLE #{table} ENABLE TRIGGER ALL;"
  end
ensure
  unless Rails.env.test?
    ActiveRecord::Base.establish_connection(Rails.configuration.database_configuration[Rails.env])
  end
end