Search code examples
postgresqlplpgsqlpg-promise

Using PL/pgSQL conditionals without creating a function


I would like to create a Postgres table and alter it, but only if it does not exist in the first place. I don't think this should be a function, as this is ran only once during the app startup. I tried to execute this code from pg-promise nodejs lib using client.none(sql, params), but it gave me an error syntax error at or near "IF", so I'm guessing it has to be some other execution method, or my SQL is fundamentally flawed. Thanks!

BEGIN
IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = $1 AND table_name = $2
) THEN
    CREATE TABLE $2~ (zoom smallint, idx bigint, tile bytea, PRIMARY KEY (zoom, idx));
    ALTER TABLE $2~ ALTER COLUMN tile SET STORAGE EXTERNAL;
END IF;
END;

Solution

  • Your code is almost there

    do $$
    BEGIN
    IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = $1 AND table_name = $2
    ) THEN
    CREATE TABLE $2~ (zoom smallint, idx bigint, tile bytea, PRIMARY KEY (zoom, idx));
    ALTER TABLE $2~ ALTER COLUMN tile SET STORAGE EXTERNAL;
    END IF;
    END $$;