Bắt ngoại lệ

Giao dịch và Xử lý Lỗi trong PostgreSQL

Jason Myers

Principal Engineer

Câu lệnh gây lỗi

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).
Giao dịch và Xử lý Lỗi trong PostgreSQL

Bắt ngoại lệ chung

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;

Kết quả

     R: Boom!
Python: Boom!
   SQL: INFO: Boom!
Giao dịch và Xử lý Lỗi trong PostgreSQL

Lệnh DO của PL/pgSQL (hàm ẩn danh)

DO $$

DECLARE some_variable text;
BEGIN SELECT text from a table; END;
$$ language 'plpgsql';
Giao dịch và Xử lý Lỗi trong PostgreSQL

Hàm xử lý ngoại lệ

DO $$
BEGIN
    SELECT SQRT("a");
EXCEPTION
    WHEN others THEN
       INSERT INTO errors (msg) VALUES ('Không thể lấy căn bậc hai của chuỗi.');
       RAISE INFO 'Không thể lấy căn bậc hai của chuỗi.';
END; 
$$ language 'plpgsql';
Giao dịch và Xử lý Lỗi trong PostgreSQL

Dùng xử lý ngoại lệ một cách khôn ngoan

  • Dùng mệnh đề EXCEPTION tăng chi phí đáng kể
  • Xử lý ngoại lệ bằng Python hoặc R hiệu quả hơn
  • Đừng bỏ qua ngữ cảnh phù hợp khi xử lý ngoại lệ
  • Đừng tối ưu trước khi hiểu rõ ngoại lệ của bạn
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html {{1}}
Giao dịch và Xử lý Lỗi trong PostgreSQL

Thay đổi tập dữ liệu

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
Giao dịch và Xử lý Lỗi trong PostgreSQL

Ayo berlatih!

Giao dịch và Xử lý Lỗi trong PostgreSQL

Preparing Video For Download...