Module: PGSpecHelper::Tables

Included in:
PGSpecHelper
Defined in:
lib/pg_spec_helper/tables.rb

Instance Method Summary collapse

Instance Method Details

#create_table(schema_name, table_name) ⇒ Object

create a new table in the provided schema



6
7
8
9
10
11
12
# File 'lib/pg_spec_helper/tables.rb', line 6

def create_table schema_name, table_name
  connection.exec(<<~SQL)
    CREATE TABLE #{schema_name}.#{table_name}(
      -- tables are created empty, and have columns added to them later
    );
  SQL
end

#delete_tables(schema_name) ⇒ Object

delete all tables in the provided schema



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/pg_spec_helper/tables.rb', line 27

def delete_tables schema_name
  get_table_names(schema_name).each do |table_name|
    connection.exec(<<~SQL)
      -- temporarily set the client_min_messages to WARNING to
      -- suppress the NOTICE messages about cascading deletes
      SET client_min_messages TO WARNING;
      DROP TABLE #{schema_name}.#{table_name} CASCADE;
      SET client_min_messages TO NOTICE;
    SQL
  end
end

#get_table_names(schema_name) ⇒ Object

return an array of table names for the provided schema



15
16
17
18
19
20
21
22
23
24
# File 'lib/pg_spec_helper/tables.rb', line 15

def get_table_names schema_name
  rows = connection.exec_params(<<~SQL, [schema_name.to_s])
    SELECT table_name FROM information_schema.tables
      WHERE
        table_schema = $1
        AND table_name NOT LIKE 'pg_%';
  SQL
  table_names = rows.map { |row| row["table_name"].to_sym }
  table_names.sort
end