Last active
May 10, 2021 11:17
-
-
Save tsnobip/831be3690a6282fc2fb8f77e23edcd91 to your computer and use it in GitHub Desktop.
Postgres: Rename column if exists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION column_exists( | |
pschema TEXT, | |
ptable TEXT, | |
pcolumn TEXT) | |
RETURNS BOOLEAN 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$ | |
LANGUAGE SQL stable strict; | |
CREATE OR REPLACE FUNCTION rename_column_if_exists( | |
pschema TEXT, | |
ptable TEXT, | |
pcolumn TEXT, | |
new_name TEXT) | |
RETURNS VOID AS $BODY$ | |
BEGIN | |
-- Rename the column if it exists. | |
IF column_exists(pschema, ptable, pcolumn) THEN | |
EXECUTE FORMAT('ALTER TABLE %I.%I RENAME COLUMN %I TO %I;', | |
pschema, ptable, pcolumn, new_name); | |
END IF; | |
END$BODY$ | |
LANGUAGE plpgsql VOLATILE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment