Skip to content

Commit

Permalink
Merge pull request rails#44896 from philip-maina/add-schema-awareness…
Browse files Browse the repository at this point in the history
…-to-postgres-enum-creation

Add schema awareness to Postgres `create_enum`
  • Loading branch information
yahonda authored May 31, 2022
2 parents 66b9bb9 + 4d1b276 commit 502c472
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -462,13 +462,17 @@ def enum_types
query = <<~SQL
SELECT
type.typname AS name,
type.OID AS oid,
string_agg(enum.enumlabel, ',' ORDER BY enum.enumsortorder) AS value
FROM pg_enum AS enum
JOIN pg_type AS type
ON (type.oid = enum.enumtypid)
GROUP BY type.typname;
GROUP BY type.OID, type.typname;
SQL
exec_query(query, "SCHEMA").cast_values

exec_query(query, "SCHEMA").cast_values.each_with_object({}) do |row, memo|
memo[row.first] = row.last
end.to_a
end

# Given a name and an array of values, creates an enum type.
Expand All @@ -478,8 +482,11 @@ def create_enum(name, values)
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_type t
SELECT 1
FROM pg_type t
#{ "JOIN pg_namespace n ON (t.typnamespace = n.oid)" if schema_exists?(current_schema) }
WHERE t.typname = '#{name}'
#{ "AND n.nspname = '#{current_schema}'" if schema_exists?(current_schema) }
) THEN
CREATE TYPE \"#{name}\" AS ENUM (#{sql_values});
END IF;
Expand Down
18 changes: 18 additions & 0 deletions activerecord/test/cases/adapters/postgresql/enum_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,22 @@ def test_works_with_activerecord_enum
model = PostgresqlEnum.find(model.id)
assert model.current_mood_happy?
end

def test_enum_type_scoped_to_schemas
old_search_path = @connection.schema_search_path
@connection.create_schema("test_schema")
@connection.schema_search_path = "test_schema"
@connection.schema_cache.clear!
@connection.create_enum("mood", ["sad", "ok", "happy"])

assert_nothing_raised do
@connection.create_table("postgresql_enums") do |t|
t.column :current_mood, :mood, default: "happy", null: false
end
end
ensure
@connection.drop_schema("test_schema")
@connection.schema_search_path = old_search_path
@connection.schema_cache.clear!
end
end

0 comments on commit 502c472

Please sign in to comment.