攔截例外

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 ('Can not take the square root of a string.');
       RAISE INFO 'Can not take the square root of a string.';
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 的交易與錯誤處理

一起來練習吧!

PostgreSQL 的交易與錯誤處理

Preparing Video For Download...