Transactions et gestion des erreurs dans PostgreSQL
Jason Myers
Principal Engineer
DO $$
BEGIN
UPDATE inventory SET quantity = quantity - 1 WHERE name in ('flour', 'sugar');
EXCEPTION
WHEN check_violation THEN
INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
RAISE INFO 'Quantity can not be less than 0.';
END;
$$ language 'plpgsql';
INFO: Quantity can not be less than 0.
DO
postgres=# select * from errors;
error_id | state | msg | detail | context
^---------+-------+----------------------------------+--------+---------
1 | | Quantity can not be less than 0. | |
(1 row)
| Nom de condition | Exemple |
|---|---|
| unique_violation | Insérer deux fois la même valeur dans une colonne unique |
| not_null_violation | Insérer null dans un champ qui n'accepte pas les valeurs nulles |
| check_violation | Échouer une contrainte CHECK, p. ex. « deliciousness » > 11 |
| division_by_zero | Diviser par 0 |
Bien d'autres au lien dans la citation ci‑dessous
DO $$
BEGIN
UPDATE inventory SET quantity = quantity - 6, cost = null
WHERE name='oatmeal dark chocolate';
-- Add check_violation exception
EXCEPTION
WHEN check_violation THEN
INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
RAISE INFO 'Quantity can not be less than 0.';
-- Add non-null exception
WHEN not_null_violation THEN
INSERT INTO errors (msg) VALUES ('Cost can not be null.');
RAISE INFO 'Cost can not be null.';
END; $$ language 'plpgsql';
INFO: Cost can not be null.
DO
postgres=# select * from errors;
error_id | state | msg | detail | context
^---------+-------+----------------------------------+--------+---------
2 | | Cost can not be null. | |
(1 row)
Transactions et gestion des erreurs dans PostgreSQL