Merge pull request #45707 from fatkodima/create_enum-schemas

Support explicit schemas in PostgreSQL's `create_enum`
This commit is contained in:
Yasuo Honda 2022-07-31 12:08:45 +09:00 committed by GitHub
commit a01d6f8b08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 5 deletions

@ -466,18 +466,19 @@ def enum_types
# Given a name and an array of values, creates an enum type.
def create_enum(name, values)
sql_values = values.map { |s| "'#{s}'" }.join(", ")
sql_values = values.map { |s| quote(s) }.join(", ")
scope = quoted_scope(name)
query = <<~SQL
DO $$
BEGIN
IF NOT EXISTS (
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) }
JOIN pg_namespace n ON t.typnamespace = n.oid
WHERE t.typname = #{scope[:name]}
AND n.nspname = #{scope[:schema]}
) THEN
CREATE TYPE \"#{name}\" AS ENUM (#{sql_values});
CREATE TYPE #{quote_table_name(name)} AS ENUM (#{sql_values});
END IF;
END
$$;

@ -157,4 +157,17 @@ def test_enum_type_scoped_to_schemas
@connection.schema_search_path = old_search_path
@connection.schema_cache.clear!
end
def test_enum_type_explicit_schema
@connection.create_schema("test_schema")
@connection.create_enum("test_schema.mood", ["sad", "ok", "happy"])
@connection.create_table("test_schema.postgresql_enums") do |t|
t.column :current_mood, "test_schema.mood"
end
assert @connection.table_exists?("test_schema.postgresql_enums")
ensure
@connection.drop_schema("test_schema", if_exists: true)
end
end