autonic 모듈은 PPAS 제공해주는 모듈로서
저장된 trigger의 다음값이 integer 필드에 들어갈 경우, serial column처럼 동작할 수 있도록 해주는 모듈입니다.
#모듈 추가
create extension autoinc;
#test
#sequence 생성
CREATE SEQUENCE next_id START -2 MINVALUE -2;
#table 생성
CREATE TABLE ids (
id int4,
idesc text
);
#trigger 생성
CREATE TRIGGER ids_nextid
BEFORE INSERT OR UPDATE ON ids
FOR EACH ROW
EXECUTE PROCEDURE autoinc (id, next_id);
#insert 3개후의 nextval 결과가 -2 +3=1 이후 nextval을 수행하여 2인 것을 확인
INSERT INTO ids VALUES (0, 'first (-2 ?)');
INSERT INTO ids VALUES (null, 'second (-1 ?)');
INSERT INTO ids(idesc) VALUES ('third (1 ?!)');
test=# SELECT 'Wasn''t it 4 ?' as nextval, nextval ('next_id') as value;
nextval | value
---------------+-------
Wasn't it 4 ? | 2
(1 row)
test=# SELECT * FROM ids;
id | idesc
----+---------------
-2 | first (-2 ?)
-1 | second (-1 ?)
1 | third (1 ?!)
UPDATE ids SET id = null, idesc = 'first: -2 --> 2'
WHERE idesc = 'first (-2 ?)';
UPDATE ids SET id = 0, idesc = 'second: -1 --> 3'
WHERE id = -1;
UPDATE ids SET id = 4, idesc = 'third: 1 --> 4'
WHERE id = 1;
insert into ids (idesc) select textcat (idesc, '. Copy.') from ids;
king=# SELECT * FROM ids;
id | idesc
----+-------------------------
3 | first: -2 --> 2
4 | second: -1 --> 3
4 | third: 1 --> 4
5 | first: -2 --> 2. Copy.
6 | second: -1 --> 3. Copy.
7 | third: 1 --> 4. Copy.