Thank you everybody for the great suggestions!
I've compiled a production ready solution for running migrations. I use the same function for checking if the column exists, but I've replaced the rename_table_if_exists
function with a procedure:
CREATE OR REPLACE FUNCTION "product".column_exists (ptable text, pcolumn text, pschema text DEFAULT 'public')
RETURNS boolean
LANGUAGE sql
STABLE STRICT
AS $BODY$
-- does the requested table.column exist in schema?
SELECT
EXISTS (
SELECT
NULL
FROM
information_schema.columns
WHERE
table_name = ptable
AND column_name = pcolumn
AND table_schema = pschema);
$BODY$;
CREATE OR REPLACE PROCEDURE "product".rename_column_if_exists (ptable TEXT, pcolumn TEXT, new_name TEXT, pschema text DEFAULT 'public')
LANGUAGE plpgsql
AS $$
BEGIN
-- Rename the column if it exists.
IF product.column_exists (ptable,
pcolumn,
pschema) THEN
EXECUTE FORMAT('ALTER TABLE %I.%I RENAME COLUMN %I TO %I;', pschema, ptable, pcolumn, new_name);
END IF;
END
$$;
It can be used like this:
CALL <schema?>.rename_column_if_exists ('users', 'name', 'first_name', <schema name - optional>);