postgresql: enum and character varying, updating

前端 未结 3 1675
孤城傲影
孤城傲影 2021-01-06 17:17

I have the ENUM type in postgresql

CREATE TYPE user_state AS ENUM (\'unconfirmed\', \'locked\', \'active\');
<         


        
3条回答
  •  误落风尘
    2021-01-06 17:57

    The problem with a simple attempt is you have a cast calling the cast, calling the cast, calling the cast...

    You need somehow to get away from varchar->enum in your cast. Simplest (most understandable) way is to just manually convert. Note the string literals being cast in the case statement aren't text they are quoted-unknown-type which sidesteps the infinite recursion.

    BEGIN;
    
    CREATE TYPE t_tl AS ENUM ('red', 'amber', 'green');
    
    CREATE FUNCTION dummy_cast(varchar) RETURNS t_tl AS $$
        SELECT CASE $1
            WHEN 'red' THEN 'red'::t_tl
            WHEN 'amber' THEN 'amber'::t_tl
            WHEN 'green' THEN 'green'::t_tl
        END;
    $$ LANGUAGE SQL;
    
    CREATE CAST (varchar AS t_tl) WITH FUNCTION dummy_cast(varchar) AS ASSIGNMENT;
    
    CREATE TABLE t (x t_tl);
    
    INSERT INTO t VALUES ('red');
    INSERT INTO t VALUES ('green'::varchar);
    
    SELECT * FROM t;
    
    ROLLBACK;
    

提交回复
热议问题