简体   繁体   中英

Is it possible to cast from one enum to another in PostgreSQL

I need to populate a new table in a second schema from an existing one, but having problems casting the "schema1.a.disclosure_level" column enum to the "schema2.b.disclosure_level" enum. A cast via::text or:: varchar did not help. Casting to::schema1.a.disclosure_level raises a cross-database reference error.

INSERT INTO schema1.a (id, disclosure_level)
SELECT schema2.b.id, schema2.b.disclosure_level
FROM schema2.b;

Any ideas?

@Bergi showed me the solution.

INSERT INTO schema1.a (id, disclosure_level)
SELECT schema2.b.id, schema2.b.disclosure_level::text:schema1.disclosure_level_enum
FROM schema2.b;

where my fault was to use the column name instead of the enum type definition in the cast: schema1.disclosure_level_enum (type) instead of schema1.a.disclosure_level (column)!

It can be possible if you cast to VARCHAR as first and second to another enum

 "valueType" = NEW."valueType"::VARCHAR::"enum_second"

From here:

https://www.postgresql.org/docs/current/datatype-enum.html

8.7.3. Type Safety

Each enumerated data type is separate and cannot be compared with other enumerated types.

Example:

CREATE TYPE animal AS ENUM ('dog', 'cat', 'rabbit');
CREATE TYPE animal_2 AS ENUM ('dog', 'cat', 'rabbit');

create table enum_test(id integer, a animal, a2 animal_2);
insert into enum_test values (1, 'dog', 'cat');

select a::animal from enum_test ;
  a  
-----
 dog

 
select a::animal_2 from enum_test ;
ERROR:  cannot cast type animal to animal_2
LINE 1: select a::animal_2 from enum_test ;

So the answer is no you can't cast one enum to another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM