Re: Best practice for naming temp table trigger functions

From: Sebastien Flaesch <sebastien(dot)flaesch(at)4js(dot)com>
To: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
Cc: "pgsql-sql(at)lists(dot)postgresql(dot)org" <pgsql-sql(at)lists(dot)postgresql(dot)org>
Subject: Re: Best practice for naming temp table trigger functions
Date: 2022-03-09 08:26:30
Message-ID: DBAP191MB128960431DC469430A58F521B00A9@DBAP191MB1289.EURP191.PROD.OUTLOOK.COM
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hello!

Using pg_temp as schema prefix for trigger function and sequence seems to do the job...

Just need confirmation that this is valid PostgreSQL code...

Tx!
Seb

CREATE TEMP TABLE tt1 (pk INTEGER NOT NULL, name VARCHAR(50));

CREATE SEQUENCE pg_temp.tt1_seq START 1;

CREATE FUNCTION pg_temp.tt1_srl() RETURNS TRIGGER AS
'DECLARE ls BIGINT;
BEGIN
SELECT INTO ls nextval(''pg_temp.tt1_seq'');
IF new.pk ISNULL OR new.pk=0 THEN
new.pk:=ls;
ELSE
IF new.pk>=ls THEN
PERFORM setval(''pg_temp.tt1_seq'',new.pk);
END IF;
END IF;
RETURN new;
END;'
LANGUAGE 'plpgsql';

CREATE TRIGGER tt1_srlt BEFORE INSERT ON tt1 FOR EACH ROW EXECUTE PROCEDURE pg_temp.tt1_srl();

INSERT INTO tt1 (name) VALUES ('aaaa');
SELECT 'Insert #1:', currval('pg_temp.tt1_seq');

INSERT INTO tt1 VALUES (0,'bbbb');
SELECT 'Insert #2:', currval('pg_temp.tt1_seq');

INSERT INTO tt1 VALUES (100,'cccc');
SELECT 'Insert #3:', currval('pg_temp.tt1_seq');

INSERT INTO tt1 (name) VALUES ('dddd');
SELECT 'Insert #4:', currval('pg_temp.tt1_seq');

SELECT * FROM tt1 ORDER BY pk;

Output:

CREATE TABLE
CREATE SEQUENCE
CREATE FUNCTION
CREATE TRIGGER
INSERT 0 1
?column? | currval
------------+---------
Insert #1: | 1
(1 row)

INSERT 0 1
?column? | currval
------------+---------
Insert #2: | 2
(1 row)

INSERT 0 1
?column? | currval
------------+---------
Insert #3: | 100
(1 row)

INSERT 0 1
?column? | currval
------------+---------
Insert #4: | 101
(1 row)

pk | name
-----+------
1 | aaaa
2 | bbbb
100 | cccc
101 | dddd
(4 rows)

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Shaozhong SHI 2022-03-16 20:14:43 Apparently table locks are the key issue to see red flags
Previous Message Sebastien Flaesch 2022-03-08 17:24:18 Re: Best practice for naming temp table trigger functions