Gestire le eccezioni

Transazioni e gestione degli errori in PostgreSQL

Jason Myers

Principal Engineer

Istruzioni che generano errori

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).
Transazioni e gestione degli errori in PostgreSQL

Cattura generica delle eccezioni

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;

Risultati

     R: Boom!
Python: Boom!
   SQL: INFO: Boom!
Transazioni e gestione degli errori in PostgreSQL

Comandi DO PL/pgSQL (funzioni anonime)

DO $$

DECLARE some_variable text;
BEGIN SELECT text from a table; END;
$$ language 'plpgsql';
Transazioni e gestione degli errori in PostgreSQL

Funzione di gestione delle eccezioni

DO $$
BEGIN
    SELECT SQRT("a");
EXCEPTION
    WHEN others THEN
       INSERT INTO errors (msg) VALUES ('Impossibile calcolare la radice quadrata di una stringa.');
       RAISE INFO 'Impossibile calcolare la radice quadrata di una stringa.';
END; 
$$ language 'plpgsql';
Transazioni e gestione degli errori in PostgreSQL

Usare bene la gestione delle eccezioni

  • Usare una clausola EXCEPTION aggiunge overhead significativo
  • La gestione delle eccezioni in Python o R è più efficiente
  • Non perdere il contesto giusto per risolvere l'eccezione
  • Non ottimizzare prima di capire le tue eccezioni
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html {{1}}
Transazioni e gestione degli errori in PostgreSQL

Modifica dei dataset

patients

colonna tipo
patient_id integer
a1c double (float)
glucose integer
fasting boolean
created_on timestamp

errors

colonna tipo
error_id integer
state string
msg string
detail string
context string
Transazioni e gestione degli errori in PostgreSQL

Ayo berlatih!

Transazioni e gestione degli errori in PostgreSQL

Preparing Video For Download...