スタック診断で例外処理を強化する

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

Jason Myers

Principal Engineer

より多くのエラー情報を取得する

DO $$
BEGIN
   UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron';
   UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION
   WHEN others THEN
       INSERT INTO errors (msg) VALUES ('Max cost is 10!');
       RAISE INFO 'Max cost is 10!';
END; 
$$ language 'plpgsql';
PostgreSQL におけるトランザクションとエラー処理

スタック診断の使用

DO $$
DECLARE
   exc_message text;
   exc_detail text;

BEGIN UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron'; UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION WHEN others THEN GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT, exc_detail = PG_EXCEPTION_DETAIL; INSERT INTO errors (msg, detail) VALUES (exc_message, exc_detail); RAISE INFO 'Exception Messaage: % | Exception Details: %', exc_message, exc_detail; END$$;
PostgreSQL におけるトランザクションとエラー処理

診断出力の例

INFO:  Exception Messaage: new row for relation "inventory" violates check constraint 
"cost_check" | Exception Details: Failing row contains (7, 35, Macaron).
DO

postgres=# \x on
Expanded display is on.
postgres=# select msg, detail from errors;
-[ RECORD 1 ]-------------------------------------------------------------------
msg    | new row for relation "inventory" violates check constraint "cost_check"
detail | Failing row contains (7, 35, Macaron).
PostgreSQL におけるトランザクションとエラー処理

取得可能な項目

Name Description
RETURNED_SQLSTATE 例外のSQLSTATEエラーコード
COLUMN_NAME 例外に関連する列名
CONSTRAINT_NAME 例外に関連する制約名
MESSAGE_TEXT 例外の主要メッセージ
PG_EXCEPTION_DETAIL 例外の詳細メッセージ(ある場合)
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html
PostgreSQL におけるトランザクションとエラー処理

追加の診断データポイント

Name Description
PG_DATATYPE_NAME 例外に関連するデータ型名
TABLE_NAME 例外に関連するテーブル名
SCHEMA_NAME 例外に関連するスキーマ名
PG_EXCEPTION_HINT 例外のヒントメッセージ(ある場合)
PG_EXCEPTION_CONTEXT 例外発生時の呼び出しスタックの行
PostgreSQL におけるトランザクションとエラー処理

Passons à la pratique !

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

Preparing Video For Download...