NielsCo / typespec-postgres

An expansion for TypeSpec enabling the definition of DB-Schema within the API-Definition in TypeSpec and emitting them to Postgres-Schema
Other
6 stars 0 forks source link

Implement Save-Mode for Enums #7

Open NielsCo opened 1 year ago

NielsCo commented 1 year ago

Enums are represented as types in postgres. There is no "IF NOT EXISTS" for types in the postgres-language. This is what ChatGPT came up with:

In PostgreSQL, you cannot directly use "IF NOT EXISTS" when creating an enum type. However, you can achieve the desired effect using a DO block with a PL/pgSQL anonymous code block to check if the enum type exists before attempting to create it.

Here's an example that demonstrates how to create an enum type called "example_enum" with values 'value1', 'value2', and 'value3', if it does not already exist:

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'example_enum') THEN
        CREATE TYPE example_enum AS ENUM ('value1', 'value2', 'value3');
    END IF;
END $$;

In this example, the DO block checks if the 'example_enum' type exists in the pg_type system catalog table. If it doesn't exist, the CREATE TYPE statement is executed to create the new enum type.