Skip to content

Commit bfd2a10

Browse files
Add lock-free ensure that column doesn't exist (#1383)
1 parent 9f1c619 commit bfd2a10

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

library/oss/postgres/prepare/database/functions.sql

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,27 @@ BEGIN
5252
END
5353
$func$;
5454

55+
-- fn_ensure_column_not_exists is a lock-friendly replacement for `ALTER TABLE ... DROP COLUMN IF EXISTS`.
56+
-- WARNING: This function translates all names into lowercase (as plain postgres would).
57+
-- If you want to use lowercase characters, (e.g. through quotation) do not use this funtion.
58+
--
59+
-- Example usage:
60+
--
61+
-- SELECT fn_ensure_column_not_exists('testtable', 'CreatedAt');
62+
CREATE OR REPLACE FUNCTION fn_ensure_column_not_exists(tname TEXT, cname TEXT)
63+
RETURNS void
64+
LANGUAGE plpgsql AS
65+
$func$
66+
BEGIN
67+
IF EXISTS (
68+
SELECT 1 FROM information_schema.columns
69+
WHERE table_name = LOWER(tname) AND column_name = LOWER(cname)
70+
) THEN
71+
EXECUTE 'ALTER TABLE ' || tname || ' DROP COLUMN IF EXISTS ' || cname || ';';
72+
END IF;
73+
END
74+
$func$;
75+
5576
-- fn_ensure_column_not_null is a lock-friendly replacement for `ALTER TABLE ... ALTER COLUMN ... SET NOT NULL`.
5677
-- WARNING: This function translates all names into lowercase (as plain postgres would).
5778
-- If you want to use lowercase characters, (e.g. through quotation) do not use this funtion.

0 commit comments

Comments
 (0)