A simplified schema representing the issue I'm having is as follows:
CREATE TABLE a (
var1 text PRIMARY KEY
);
CREATE TABLE b (
var1 text,
var2 text PRIMARY KEY
);
CREATE TABLE c (
var1 text,
var2 text,
var3 text PRIMARY KEY
);
In table c
, var1
and var2
represent keys in tables a
and b
respectively.
From these values, we wish to generate a key for the new tuple being inserted into c
.
We do so by creating a trigger calling a function as follows:
CREATE TRIGGER key_Gen
BEFORE INSERT ON c
FOR EACH ROW
EXECUTE PROCEDURE key_Gen();
CREATE FUNCTION key_Gen() RETURNS trigger AS $key_Gen$
BEGIN
-- Check that new values are not null
IF NEW.var1 IS NULL THEN
RAISE EXCEPTION 'var1 cannot be null';
END IF;
IF NEW.var2 IS NULL THEN
RAISE EXCEPTION 'var2 cannot be null';
END IF;
INSERT INTO a VALUES (NEW.var1);
INSERT INTO b VALUES (NEW.var1 || NEW.var2);
INSERT INTO c VALUES (NEW.var1 || NEW.var2 || NEW.var3);
RETURN NEW;
END;
$key_Gen$ LANGUAGE plpgsql;
- For table
a
, the new key should bevar1
. - For table
b
, the new key should be a concatenation ofvar1
andvar2
. - For table
c
, the new key should be a concatenation ofvar1
,var2
, andvar3
.
Let's say I insert the following:
INSERT INTO c VALUES ( 'TEST', 'HAS', 'PASSED');
I get the following error message:
null value in column "var2" violates not-null constraint
I've tried changing various things around in the trigger and function, such as changing BEFORE INSERT
to AFTER INSERT
, but that doesn't affect its behavior.
I've also tried referencing the documentation and various other examples, but none of the one's I've seen address the particular conditions of this problem.
Can what I want to do with my function even be done?