Module: Noncommittal

Defined in:
lib/noncommittal.rb,
lib/noncommittal/version.rb

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.__gather_default_tables ⇒ Object



34
35
36
37
38
39
40
# File 'lib/noncommittal.rb', line 34

def self.__gather_default_tables
  ActiveRecord::Base.connection.select_values(
    "select table_name from information_schema.tables where table_schema = 'public' and table_type = 'BASE TABLE' and table_catalog = $1",
    "SQL",
    [ActiveRecord::Relation::QueryAttribute.new("catalog_name", ActiveRecord::Base.connection.current_database, ActiveRecord::Type::String.new)]
  ) - ["ar_internal_metadata", "schema_migrations"]
end

.start!(tables: nil, exclude_tables: []) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/noncommittal.rb', line 4

def self.start!(tables: nil, exclude_tables: [])
  raise "noncommittal is only designed to be run in your test environment!" unless Rails.env.test?

  tables ||= __gather_default_tables
  tables = tables.map(&:to_s) - exclude_tables.map(&:to_s)

  ActiveRecord::Base.connection.execute <<~SQL
    create table if not exists noncommittal_no_rows_allowed (id bigint unique);
    #{tables.map { |table_name|
      constraint_name = "noncommittal_#{table_name}"
      <<~SQL
        alter table #{table_name} drop constraint if exists #{constraint_name};
        alter table #{table_name} add constraint #{constraint_name} foreign key (id) references noncommittal_no_rows_allowed (id) deferrable initially deferred;
      SQL
    }.join("\n")}
  SQL
end

.stop!(tables: nil, exclude_tables: []) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/noncommittal.rb', line 22

def self.stop!(tables: nil, exclude_tables: [])
  tables ||= __gather_default_tables
  tables = tables.map(&:to_s) - exclude_tables.map(&:to_s)

  ActiveRecord::Base.connection.execute <<~SQL
    #{tables.map { |table_name|
      "alter table #{table_name} drop constraint if exists noncommittal_#{table_name};"
    }.join("\n")}
    drop table if exists noncommittal_no_rows_allowed;
  SQL
end