การจัดการข้อยกเว้น

Transactions and Error Handling in 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).
Transactions and Error Handling in 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!
Transactions and Error Handling in PostgreSQL

คำสั่ง DO ของ PL/pgSQL (ฟังก์ชันนิรนาม)

DO $$

DECLARE some_variable text;
BEGIN SELECT text from a table; END;
$$ language 'plpgsql';
Transactions and Error Handling in 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';
Transactions and Error Handling in PostgreSQL

การใช้การจัดการข้อยกเว้นอย่างชาญฉลาด

  • การใช้ clause EXCEPTION เพิ่มภาระประมวลผลอย่างมีนัยสำคัญ
  • การจัดการข้อยกเว้นใน Python หรือ R มีประสิทธิภาพมากกว่า
  • อย่าละเลยบริบทที่จำเป็นในการแก้ไขข้อยกเว้น
  • อย่าเร่งปรับให้เหมาะสมก่อนเข้าใจข้อยกเว้นของตนเอง
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html {{1}}
Transactions and Error Handling in 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
Transactions and Error Handling in PostgreSQL

มาฝึกกันเถอะ!

Transactions and Error Handling in PostgreSQL

Preparing Video For Download...