Module: PGSpecHelper::Enums

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

Instance Method Summary collapse

Instance Method Details

#create_enum(schema_name, enum_name, values) ⇒ Object

Create an enum



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

def create_enum schema_name, enum_name, values
  connection.exec(<<~SQL)
    CREATE TYPE #{schema_name}.#{enum_name} as ENUM ('#{values.join("','")}')
  SQL
  # so we can delete them later
  @created_enums ||= []
  @created_enums << {schema_name: schema_name, enum_name: enum_name}
end

#delete_created_enumsObject

delete all enums which were created by this helper



36
37
38
39
40
41
42
43
# File 'lib/pg_spec_helper/enums.rb', line 36

def delete_created_enums
  @created_enums&.each do |enum|
    connection.exec(<<~SQL)
      DROP TYPE IF EXISTS #{enum[:schema_name]}.#{enum[:enum_name]};
    SQL
  end
  @created_enums = []
end

#drop_enum(schema_name, enum_name) ⇒ Object

Drop an enum



16
17
18
19
20
# File 'lib/pg_spec_helper/enums.rb', line 16

def drop_enum schema_name, enum_name
  connection.exec(<<~SQL)
    DROP TYPE #{schema_name}.#{enum_name}
  SQL
end

#get_enum_names(schema_name) ⇒ Object

get a list of enum names for the provided schema



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/pg_spec_helper/enums.rb', line 23

def get_enum_names schema_name
  rows = connection.exec_params(<<~SQL, [schema_name.to_s])
    SELECT
      t.typname AS enum_name
    FROM pg_type t
      JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
    WHERE n.nspname = $1 AND t.typname[0] != '_'
    GROUP BY t.typname
  SQL
  rows.map { |row| row["enum_name"].to_sym }
end