Skip to content

Commit 05a09b7

Browse files
authored
Also provision fn_ensure_replica_identity helper function. (#1377)
1 parent c0b6f77 commit 05a09b7

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,29 @@ BEGIN
7171
EXECUTE 'ALTER TABLE ' || tname || ' ALTER COLUMN ' || cname || ' SET NOT NULL;';
7272
END IF;
7373
END
74+
$func$;
75+
76+
-- fn_ensure_replica_identity is a lock-friendly replacement for `ALTER TABLE ... REPLICA IDENTITY ...`.
77+
-- WARNING: This function translates all names into lowercase (as plain postgres would).
78+
-- If you want to use lowercase characters, (e.g. through quotation) do not use this funtion.
79+
-- Does not support index identities.
80+
--
81+
-- Example usage:
82+
--
83+
-- SELECT fn_ensure_replica_identity('testtable', 'FULL');
84+
CREATE OR REPLACE FUNCTION fn_ensure_replica_identity(tname TEXT, replident TEXT)
85+
RETURNS void
86+
LANGUAGE plpgsql AS
87+
$func$
88+
BEGIN
89+
IF NOT EXISTS (
90+
SELECT 1 FROM pg_class WHERE oid = tname::regclass AND CASE relreplident
91+
WHEN 'd' THEN 'default'
92+
WHEN 'n' THEN 'nothing'
93+
WHEN 'f' THEN 'full'
94+
END = LOWER(replident)
95+
) THEN
96+
EXECUTE 'ALTER TABLE ' || tname || ' REPLICA IDENTITY ' || replident || ';';
97+
END IF;
98+
END
7499
$func$;

0 commit comments

Comments
 (0)