例外の捕捉

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

Jason Myers

Principal Engineer

エラーになる文

INSERT INTO sales (name, quantity, cost) 
VALUES 
  ('chocolate chip', 6, null);
ERROR:  null value in column "cost" violates not-null constraint
DETAIL:  Failing row contains 
(1, "chocolate chip", 6, null, 2020-04-28 19:58:55.715886).
PostgreSQL におけるトランザクションとエラー処理

一般的な例外の捕捉

R

tryCatch(
  sqrt("a"), 
  error=function(e) 
    print("Boom!")
)

Python

try:
   math.sqrt("a")
except Exception as e:
   print("Boom!")

PL/pgSQL

BEGIN 
SELECT 
  SQRT("a");
EXCEPTION WHEN others THEN RAISE INFO 'Boom!';
END;

結果

     R: Boom!
Python: Boom!
   SQL: INFO: Boom!
PostgreSQL におけるトランザクションとエラー処理

PL/pgSQL DO コマンド(無名関数)

DO $$

DECLARE some_variable text;
BEGIN SELECT text from a table; END;
$$ language 'plpgsql';
PostgreSQL におけるトランザクションとエラー処理

例外処理関数

DO $$
BEGIN
    SELECT SQRT("a");
EXCEPTION
    WHEN others THEN
       INSERT INTO errors (msg) VALUES ('文字列の平方根は計算できません。');
       RAISE INFO '文字列の平方根は計算できません。';
END; 
$$ language 'plpgsql';
PostgreSQL におけるトランザクションとエラー処理

例外処理を賢く使う

  • EXCEPTION 句は大きなオーバーヘッドを伴う
  • 例外処理は Python や R の方が効率的
  • 例外解決の文脈を取り違えない
  • 例外を理解する前に最適化しない
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html {{1}}
PostgreSQL におけるトランザクションとエラー処理

データセットの変更

patients

column type
patient_id integer
a1c double (float)
glucose integer
fasting boolean
created_on timestamp

errors

column type
error_id integer
state string
msg string
detail string
context string
PostgreSQL におけるトランザクションとエラー処理

¡Vamos a practicar!

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

Preparing Video For Download...