Check if a user-defined type already exists in PostgreSQL

后端 未结 10 1601
离开以前
离开以前 2020-12-29 01:43

Say I have created some user-defined types in the DB,

i.e. CREATE TYPE abc ...

Is it then possible to determine if the user-defined type exists

10条回答
  •  生来不讨喜
    2020-12-29 02:39

    A more generic solution

    CREATE OR REPLACE FUNCTION create_type(name text, _type text) RETURNS 
    integer AS $$
    DECLARE v_exists INTEGER;
    
    BEGIN
        SELECT into v_exists (SELECT 1 FROM pg_type WHERE typname = name);
        IF v_exists IS NULL THEN
                EXECUTE format('CREATE TYPE %I AS %s', name, _type);
        END IF;
        RETURN v_exists;
    END;
    $$ LANGUAGE plpgsql;
    

    and then you can call it like this:

    select create_type('lwm2m_instancetype', 'enum (''single'',''multiple'')');

提交回复
热议问题