mirror of
https://github.com/hasura/graphql-engine.git
synced 2024-12-15 09:22:43 +03:00
fc7ea9213c
Insert trigger function: If query affects no rows then return `null` Insert trigger function is modified to have `IF r IS NULL THEN RETURN null; ELSE RETURN r; END IF;` in return statement.
35 lines
1.7 KiB
Django/Jinja
35 lines
1.7 KiB
Django/Jinja
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 $$;
|