Exceptions afvangen

Transacties en foutafhandeling in PostgreSQL

Jason Myers

Principal Engineer

Foutgevende statements

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).
Transacties en foutafhandeling in PostgreSQL

Generieke exception-opvang

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;

Resultaten

     R: Boom!
Python: Boom!
   SQL: INFO: Boom!
Transacties en foutafhandeling in PostgreSQL

PL/pgSQL DO-commando's (anonieme functies)

DO $$

DECLARE some_variable text;
BEGIN SELECT text from a table; END;
$$ language 'plpgsql';
Transacties en foutafhandeling in PostgreSQL

Exception-handlingfunctie

DO $$
BEGIN
    SELECT SQRT("a");
EXCEPTION
    WHEN others THEN
       INSERT INTO errors (msg) VALUES ('Kan geen wortel nemen van een string.');
       RAISE INFO 'Kan geen wortel nemen van een string.';
END; 
$$ language 'plpgsql';
Transacties en foutafhandeling in PostgreSQL

Exceptions verstandig gebruiken

  • Een EXCEPTION-clause voegt flinke overhead toe
  • Exception handling in Python of R is efficiënter
  • Verlies geen context bij het oplossen van de exception
  • Optimaliseer niet vóór je je exceptions begrijpt
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html {{1}}
Transacties en foutafhandeling in PostgreSQL

Datasets wijzigen

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
Transacties en foutafhandeling in PostgreSQL

Laten we oefenen!

Transacties en foutafhandeling in PostgreSQL

Preparing Video For Download...