始める無料で始める

スタック診断を取得する

スタック診断を使うと、PostgreSQL の内部エラーメッセージや例外の詳細を取得できます。patients テーブルに戻り、検査上限を超える A1C を追加してみましょう。これにより CHECK 制約の例外が発生し、捕捉できます。例外ハンドラー内でスタック診断を使うと、エラー記録を充実させられます。

この演習はコースの一部です

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

コースを見る

演習の手順

  • DECLAREexc_messageexc_detail の2つの変数を text 型として宣言します。
  • 診断スタックを取得し、exc_messageMESSAGE_TEXT を、exc_detailPG_EXCEPTION_DETAIL を設定します。
  • errors テーブルの msg フィールドと detail フィールドに、それぞれ exc_messageexc_detail を挿入します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

DO $$ 
-- Declare our text variables: exc_message and exc_detail 
___
   ___ text;
   exc_detail ___;
BEGIN 
    INSERT INTO patients (a1c, glucose, fasting) 
    values (20, 89, TRUE);
EXCEPTION 
WHEN others THEN
    -- Get the exception message and detail via stacked diagnostics
	___ ___ ___ 
    	exc_message = ___,
        exc_detail = ___;
    -- Record the exception message and detail in the errors table
    INSERT INTO errors (___, detail) VALUES (exc_message, ___);
END;
$$ language 'plpgsql';

-- Select all the errors recorded
SELECT * FROM errors;
コードを編集して実行