捕获异常

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...