graphql-engine/server/src-rsr/insert_trigger.sql.j2

35 lines
1.7 KiB
Plaintext
Raw Normal View History

CREATE OR REPLACE FUNCTION {{function_name}}() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE r {{table_name}}%ROWTYPE;
DECLARE conflict_clause jsonb;
DECLARE action text;
DECLARE constraint_name text;
DECLARE set_expression text;
BEGIN
conflict_clause = current_setting('hasura.conflict_clause')::jsonb;
IF ({{check_expression}}) THEN
CASE
WHEN conflict_clause = 'null'::jsonb THEN INSERT INTO {{table_name}} VALUES (NEW.*) RETURNING * INTO r;
ELSE
action = conflict_clause ->> 'action';
constraint_name = quote_ident(conflict_clause ->> 'constraint');
set_expression = conflict_clause ->> 'set_expression';
IF action is NOT NULL THEN
CASE
WHEN action = 'ignore'::text AND constraint_name IS NULL THEN
INSERT INTO {{table_name}} VALUES (NEW.*) ON CONFLICT DO NOTHING RETURNING * INTO r;
WHEN action = 'ignore'::text AND constraint_name is NOT NULL THEN
EXECUTE 'INSERT INTO {{table_name}} VALUES ($1.*) ON CONFLICT ON CONSTRAINT ' || constraint_name ||
' DO NOTHING RETURNING *' INTO r USING NEW;
ELSE
EXECUTE 'INSERT INTO {{table_name}} VALUES ($1.*) ON CONFLICT ON CONSTRAINT ' || constraint_name ||
' DO UPDATE ' || set_expression || ' RETURNING *' INTO r USING NEW;
END CASE;
ELSE
RAISE internal_error using message = 'action is not found'; RETURN NULL;
END IF;
END CASE;
IF r IS NULL THEN RETURN null; ELSE RETURN r; END IF;
ELSE RAISE check_violation using message = 'insert check constraint failed'; RETURN NULL;
END IF;
END $$;