Class: SqlFixtures::TableRefresher

Inherits:
Object
  • Object
show all
Defined in:
lib/sql_fixtures/table_refresher.rb

Constant Summary collapse

BASE_DIR =
Rails.root.join("spec", "db")
STRUCTURE_DIR =
BASE_DIR.join "structure"
DATA_DIR =
BASE_DIR.join "data"
CONSTRAINTS_DIR =
BASE_DIR.join "constraints"

Instance Method Summary collapse

Instance Method Details

#refresh_tables!(*tables_to_reload) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sql_fixtures/table_refresher.rb', line 9

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