特定の例外処理とメッセージ

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';
PostgreSQL におけるトランザクションとエラー処理

例外ハンドラの出力

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)
PostgreSQL におけるトランザクションとエラー処理

一般的な例外条件の種類

条件名
unique_violation 一意列に同じ値を2回挿入
not_null_violation NULL不可の列にNULLを挿入
check_violation 「おいしさ」が11より大きいなどのCHECK制約に違反
division_by_zero 0で除算

他にも多数。下の参考リンクを参照

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
PostgreSQL におけるトランザクションとエラー処理

複数の例外を捕捉する

DO $$
BEGIN
    UPDATE inventory SET quantity = quantity - 6, cost = null 
    WHERE name='oatmeal dark chocolate';

PostgreSQL におけるトランザクションとエラー処理

複数の例外タイプを個別に捕捉する

-- 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';

PostgreSQL におけるトランザクションとエラー処理

複数例外の出力

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 におけるトランザクションとエラー処理

実践してみましょう

PostgreSQL におけるトランザクションとエラー処理

Preparing Video For Download...