Skip to content

Instantly share code, notes, and snippets.

@jianhe-fun
Created April 3, 2023 12:20
Show Gist options
  • Save jianhe-fun/9c743be67e018c9925e958debf89a05a to your computer and use it in GitHub Desktop.
Save jianhe-fun/9c743be67e018c9925e958debf89a05a to your computer and use it in GitHub Desktop.
passing variable while do insert operation
/*
https://dba.stackexchange.com/questions/303502/pass-a-variable-with-insert-update-delete-statements/303546#303546
https://dbfiddle.uk/ZsFssnOW
*/
CREATE TABLE ins_tbl (
id int GENERATED ALWAYS AS IDENTITY,
name text
);
CREATE VIEW v_ins_tbl AS
SELECT
*,
NULL::int AS site_id
FROM
ins_tbl;
CREATE OR REPLACE FUNCTION trg_ins_tbl ()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $func$
BEGIN
CASE NEW.site_id
WHEN 1 THEN
INSERT INTO ins_tbl (name)
VALUES (NEW.name); RETURN new;
WHEN 2 THEN
INSERT INTO ins_tbl (name)
VALUES (NEW.name); RETURN NULL;
WHEN 0 THEN
RETURN NULL;
ELSE
RAISE EXCEPTION 'unexpected site_id: %', NEW.site_id;
END CASE;
END
$func$;
CREATE TRIGGER trg_insbef_ins_tbl
INSTEAD OF insert ON v_ins_tbl FOR EACH ROW
EXECUTE FUNCTION trg_ins_tbl ();
-- missing or unexpected site_id raises custom exception
INSERT INTO v_ins_tbl (name)
VALUES ('xxx');
-- missing or unexpected site_id raises custom exception
INSERT INTO v_ins_tbl (name, site_id)
VALUES ('xxx', 7);
/*
ERROR: unexpected site_id: 7
CONTEXT: PL/pgSQL function trg_ins_tbl() line 13 at RAISE
*/
-- propagated normally
INSERT INTO v_ins_tbl (name, site_id)
VALUES ('bar___1', 1)
RETURNING
*;
-- INSERT is propagated, but not reported and Postgres stops there
INSERT INTO v_ins_tbl (name, site_id)
VALUES ('foo', 2)
RETURNING
*;
TABLE ins_tbl;
-- INSERT cancelled silently
INSERT INTO v_ins_tbl (name, site_id)
VALUES ('xxx', 0)
RETURNING
*;
--normal way.
INSERT INTO v_ins_tbl (id, name, site_id)
VALUES (DEFAULT, 'test', 1)
RETURNING
*;
TABLE ins_tbl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment