Assume, i have 2 tables in my DB (postgresql-9.x)
CREATE TABLE FOLDER (
KEY BIGSERIAL PRIMARY KEY,
PATH TEXT,
NAME TEXT
);
CREATE TABLE FOLDERFILE (
FILEID BIGINT,
PATH TEXT,
PATHKEY BIGINT
);
I automatically update FOLDERFILE.PATHKEY
from FOLDER.KEY
whenever i insert into or update FOLDERFILE
:
CREATE OR REPLACE FUNCTION folderfile_fill_pathkey() RETURNS trigger AS $$
DECLARE
pathkey bigint;
changed boolean;
BEGIN
IF tg_op = 'INSERT' THEN
changed := TRUE;
ELSE IF old.FILEID != new.FILEID THEN
changed := TRUE;
END IF;
END IF;
IF changed THEN
SELECT INTO pathkey key FROM FOLDER WHERE PATH = new.path;
IF FOUND THEN
new.pathkey = pathkey;
ELSE
new.pathkey = NULL;
END IF;
END IF;
RETURN new;
END
$$ LANGUAGE plpgsql VOLATILE;
CREATE TRIGGER folderfile_fill_pathkey_trigger AFTER INSERT OR UPDATE
ON FOLDERFILE FOR EACH ROW EXECUTE PROCEDURE fcliplink_fill_pathkey();
So the question is about function folderfile_fill_pathkey()
volatility. Documentations says
Any function with side-effects must be labeled VOLATILE
But as far as i understand – this function does not change any data in the tables it rely on, so i can mark this function as IMMUTABLE
. It that correct?
Would there be any problem with IMMUTABLE trigger function if I bulk-insert many rows into FOLDERFILE
within the same transaction, like:
BEGIN;
INSERT INTO FOLDERFILE ( ... );
...
INSERT INTO FOLDERFILE ( ... );
COMMIT;
IMMUTABLE
, it's justSTABLE
(it selects from yourFOLDER
table, which can change over time: your function does not guarantee the same results for the same "parameters") -- but, it's a trigger, not a classical function: function volatility only matters for query optimizations, but it will only cause you troubles, if you optimize triggers, f.ex.STABLE
- It is inappropriate forAFTER
triggers that wish to query rows modified by the current command. – OmaromaraIMMUTABLE
andSTABLE
, so I'll have to fix few things now in my DB. So your comment is greatly appreciated. – HypozeugmaSTABLE
instead ofVOLATILE
will not give me any performance advantages? Would be nice also if you make it an answer so i can accept it – otherwise i'll have to do it myself. – HypozeugmaSTABLE
actually perform better, or not. Query optimization depends on a lot of things. (In your case -- i.e. you do not query the trigger's target tableFOLDERFILE
inside the function -- it should not matter). But, if you want to be precise, you should test both variants with real data. – Omaromara