Check if a user-defined type already exists in PostgreSQL

后端 未结 10 1600
离开以前
离开以前 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:24

    To solve @rog's dilemma to @bluish's answer it could be more appropriate to make use of regtype data type. Consider this:

    DO $$ BEGIN
        PERFORM 'my_schema.my_type'::regtype;
    EXCEPTION
        WHEN undefined_object THEN
            CREATE TYPE my_schema.my_type AS (/* fields go here */);
    END $$;
    

    PERFORM clause is like SELECT, but it discards results, so basically we're checking if it is possible to cast 'my_schema.my_type' (or just 'my_type' if you don't care to be schema specific) to actual registered type. If the type does exist, then nothing "wrong" will happen and because of RETURN whole block will end—no changes, since the type my_type is already there. But if the cast is not possible, then there will be thrown error code 42704 which has label of undefined_object. So in the next lines we try to catch that error and if that happens, we simply create our new data type.

提交回复
热议问题