Zachytávání výjimek

Transakce a ošetření chyb v PostgreSQL

Jason Myers

Principal Engineer

Příkazy způsobující chybu

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).
Transakce a ošetření chyb v PostgreSQL

Obecné zachytávání výjimek

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;

Výsledky

     R: Boom!
Python: Boom!
   SQL: INFO: Boom!
Transakce a ošetření chyb v PostgreSQL

Příkazy DO v PL/pgSQL (anonymní funkce)

DO $$

DECLARE some_variable text;
BEGIN SELECT text from a table; END;
$$ language 'plpgsql';
Transakce a ošetření chyb v PostgreSQL

Funkce pro ošetření výjimek

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';
Transakce a ošetření chyb v PostgreSQL

Rozumné použití ošetření výjimek

  • Použití klauzule EXCEPTION zvyšuje režii
  • Ošetření výjimek v Pythonu nebo R je efektivnější
  • Neobětujte správný kontext pro vyřešení výjimky
  • Neoptimalizujte dříve, než výjimkám porozumíte.
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html {{1}}
Transakce a ošetření chyb v PostgreSQL

Změna datových sad

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
Transakce a ošetření chyb v PostgreSQL

Pojďme procvičovat!

Transakce a ošetření chyb v PostgreSQL

Preparing Video For Download...