Skip to content

Commit a01d6f8

Browse files
authored
Merge pull request rails#45707 from fatkodima/create_enum-schemas
Support explicit schemas in PostgreSQL's `create_enum`
2 parents fdc988b + 438862b commit a01d6f8

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -466,18 +466,19 @@ def enum_types
466466

467467
# Given a name and an array of values, creates an enum type.
468468
def create_enum(name, values)
469-
sql_values = values.map { |s| "'#{s}'" }.join(", ")
469+
sql_values = values.map { |s| quote(s) }.join(", ")
470+
scope = quoted_scope(name)
470471
query = <<~SQL
471472
DO $$
472473
BEGIN
473474
IF NOT EXISTS (
474475
SELECT 1
475476
FROM pg_type t
476-
#{ "JOIN pg_namespace n ON (t.typnamespace = n.oid)" if schema_exists?(current_schema) }
477-
WHERE t.typname = '#{name}'
478-
#{ "AND n.nspname = '#{current_schema}'" if schema_exists?(current_schema) }
477+
JOIN pg_namespace n ON t.typnamespace = n.oid
478+
WHERE t.typname = #{scope[:name]}
479+
AND n.nspname = #{scope[:schema]}
479480
) THEN
480-
CREATE TYPE \"#{name}\" AS ENUM (#{sql_values});
481+
CREATE TYPE #{quote_table_name(name)} AS ENUM (#{sql_values});
481482
END IF;
482483
END
483484
$$;

activerecord/test/cases/adapters/postgresql/enum_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,4 +157,17 @@ def test_enum_type_scoped_to_schemas
157157
@connection.schema_search_path = old_search_path
158158
@connection.schema_cache.clear!
159159
end
160+
161+
def test_enum_type_explicit_schema
162+
@connection.create_schema("test_schema")
163+
@connection.create_enum("test_schema.mood", ["sad", "ok", "happy"])
164+
165+
@connection.create_table("test_schema.postgresql_enums") do |t|
166+
t.column :current_mood, "test_schema.mood"
167+
end
168+
169+
assert @connection.table_exists?("test_schema.postgresql_enums")
170+
ensure
171+
@connection.drop_schema("test_schema", if_exists: true)
172+
end
160173
end

0 commit comments

Comments
 (0)