Forked from estysdesu/create_constraint_if_not_exists.sql
Created
March 17, 2023 09:25
-
-
Save concosminx/e58bb10cdee4a6821b4cc8c8dbe16bec to your computer and use it in GitHub Desktop.
[PostgreSQL: create constraint if not exists] not sure of sql compatibility with other engines #postgres #constraint #sql
This file contains 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
// vim: syntax=sql | |
CREATE OR REPLACE FUNCTION create_constraint_if_not_exists (t_name text, c_name text, constraint_sql text) | |
RETURNS void | |
AS | |
$BODY$ | |
BEGIN | |
-- Look for our constraint | |
IF NOT EXISTS (SELECT constraint_name | |
FROM information_schema.constraint_column_usage | |
WHERE constraint_name = c_name) THEN | |
EXECUTE 'ALTER TABLE ' || t_name || ' ADD CONSTRAINT ' || c_name || ' ' || constraint_sql; | |
END IF; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE; | |
SELECT create_constraint_if_not_exists('foo', 'bar', 'CHECK (foobies < 100);'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment