Module: PGSpecHelper::Schemas

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

Instance Method Summary collapse

Instance Method Details

#create_schema(schema_name) ⇒ Object

create a new schema in the database



6
7
8
9
10
# File 'lib/pg_spec_helper/schemas.rb', line 6

def create_schema schema_name
  connection.exec(<<~SQL)
    CREATE SCHEMA #{connection.quote_ident schema_name.to_s};
  SQL
end

#delete_all_schemasObject

delete all schemas in the database



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/pg_spec_helper/schemas.rb', line 28

def delete_all_schemas
  # delete all schemas except public
  get_schema_names.reject { |schema_name| schema_name == :public }.each do |schema_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 SCHEMA #{connection.quote_ident schema_name.to_s} CASCADE;
      SET client_min_messages TO NOTICE;
    SQL
  end
  # delete all the tables, functions and enums from within the public schema
  delete_tables :public
  delete_created_functions
  delete_created_enums
end

#get_schema_namesObject

return a list of the schema names in the database



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

def get_schema_names
  ignored_schemas_sql = ignored_schemas.join("', '")
  # return a list of the schema names from the database
  results = connection.exec(<<~SQL)
    SELECT schema_name
      FROM information_schema.schemata
    WHERE
      schema_name NOT IN ('#{ignored_schemas_sql}')
      AND schema_name NOT LIKE 'pg_%';
  SQL
  schema_names = results.map { |row| row["schema_name"].to_sym }
  schema_names.sort
end

#schema_exists?(schema_name) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/pg_spec_helper/schemas.rb', line 45

def schema_exists? schema_name
  get_schema_names.include? schema_name.to_sym
end