[Postgresql] Trigger

Ja L·2023년 5월 15일
0

AgensSQL/PostgreSQL

목록 보기
12/37

트리거란?

Trigger는 방아쇠라는 뜻입니다.
총의 방아쇠를 당기면 총기 내부에서 일련의 과정을 통해 총알이 날아갑니다. 비슷하게 데이터베이스에서도 트리거는 특정 테이블에 INSERT, DELETE, UPDATE 같은 DML 문이 수행되었을 때, 데이터베이스에서 자동으로 동작하도록 작성된 프로그램입니다.

여기서 중요한 점은, 사용자가 직접 호출하는 것이 아닌 데이터베이스에서 자동으로 호출한다는 것입니다.

트리거는 테이블과 뷰 데이터베이스 작업을 대상으로 정의할 수 있으며, 전체 트랜잭션 작업에 대해 발생되는 트리거(Trigger)와 각 행에 발생되는 트리거(Trigger)가 있습니다.

트리거를 구현하기 위해 우선 절차형 SQL과 PL/SQL을 알아야 합니다.
아래 링크를 참고하세요.
https://velog.io/@dafld/PLSQL

트리거가 적용되는 예

참고 - https://www.postgresql.org/docs/current/plpgsql-trigger.html

Example 43.3 A PL/pgSQL Trigger Function

create table emp (
	empname text, 
    salary integer,
    last_date timestamp,
    last_user text
) ;
create function emp_stamp() returns trigger as $emp_stamp$
	begin
    	if new.empname is null then
        	raise exception 'empname cannot be null';
        end if;
        
        if new.salary is null then
        	raiser exception '% cannot have null salary', new.empname ;
        end if ;
        
        if new.salary < 0 then 
        	raise exception '% cannot have negative salary', new.empname ;
        end if ;
        
        new.last_date := current_timestamp ;
        new.last_user := currnet_user ;
        return new ; 
    end ;
$emp_stamp$ LANGUAGE plpgsql ;


create trigger emp_stamp before insert or update on emp 
	for each row exectue function emp_stamp() ;

43.4 A PL/pgSQL Trigger Function for Auditing

CREATE TABLE emp (
    empname           text NOT NULL,
    salary            integer
);

CREATE TABLE emp_audit(
    operation         char(1)   NOT NULL,
    stamp             timestamp NOT NULL,
    userid            text      NOT NULL,
    empname           text      NOT NULL,
    salary integer
);

CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
    BEGIN
        --
        -- Create a row in emp_audit to reflect the operation performed on emp,
        -- making use of the special variable TG_OP to work out the operation.
        --
        IF (TG_OP = 'DELETE') THEN
            INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
        ELSIF (TG_OP = 'UPDATE') THEN
            INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
        END IF;
        RETURN NULL; -- result is ignored since this is an AFTER trigger
    END;
$emp_audit$ LANGUAGE plpgsql;

CREATE TRIGGER emp_audit
AFTER INSERT OR UPDATE OR DELETE ON emp
    FOR EACH ROW EXECUTE FUNCTION process_emp_audit();

임의의 값을 삽입하고, emp 테이블과 emp_audit 테이블을 확인해보자.

INSERT INTO emp VALUES ('lee', 100000) ;

SELECT * FROM emp ;

 empname | salary
---------+--------
 lee     |  10000
(1 row)

SELECT * FROM emp_audit ;

 operation |           stamp            | userid | empname | salary
-----------+----------------------------+--------+---------+--------
 I         | 2023-05-15 13:51:08.609908 | agens  | lee     |  10000
(1 row)
profile
DB Engineer

0개의 댓글