PostgreSQL에서의 트랜잭션과 오류 처리
Jason Myers
Principal Engineer
DO $$
BEGIN
UPDATE inventory SET quantity = quantity - 1 WHERE name in ('flour', 'sugar');
EXCEPTION
WHEN check_violation THEN
INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
RAISE INFO 'Quantity can not be less than 0.';
END;
$$ language 'plpgsql';
INFO: Quantity can not be less than 0.
DO
postgres=# select * from errors;
error_id | state | msg | detail | context
^---------+-------+----------------------------------+--------+---------
1 | | Quantity can not be less than 0. | |
(1 row)
| Condition Name | Example |
|---|---|
| unique_violation | 유니크 컬럼에 중복 값 삽입 |
| not_null_violation | NULL을 허용하지 않는 필드에 NULL 삽입 |
| check_violation | 맛 점수 11 초과 같은 CHECK 제약 위반 |
| division_by_zero | 0으로 나누기 |
더 많은 예시는 아래 인용 링크에서 확인하세요
DO $$
BEGIN
UPDATE inventory SET quantity = quantity - 6, cost = null
WHERE name='oatmeal dark chocolate';
-- Add check_violation exception
EXCEPTION
WHEN check_violation THEN
INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
RAISE INFO 'Quantity can not be less than 0.';
-- Add non-null exception
WHEN not_null_violation THEN
INSERT INTO errors (msg) VALUES ('Cost can not be null.');
RAISE INFO 'Cost can not be null.';
END; $$ language 'plpgsql';
INFO: Cost can not be null.
DO
postgres=# select * from errors;
error_id | state | msg | detail | context
^---------+-------+----------------------------------+--------+---------
2 | | Cost can not be null. | |
(1 row)
PostgreSQL에서의 트랜잭션과 오류 처리