Tranzacții și gestionarea erorilor în PostgreSQL
Jason Myers
Principal Engineer
DO $$
BEGIN
UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron';
UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION
WHEN others THEN
INSERT INTO errors (msg) VALUES ('Max cost is 10!');
RAISE INFO 'Max cost is 10!';
END;
$$ language 'plpgsql';
DO $$ DECLARE exc_message text; exc_detail text;BEGIN UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron'; UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';EXCEPTION WHEN others THEN GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT, exc_detail = PG_EXCEPTION_DETAIL; INSERT INTO errors (msg, detail) VALUES (exc_message, exc_detail); RAISE INFO 'Exception Messaage: % | Exception Details: %', exc_message, exc_detail; END$$;
INFO: Exception Messaage: new row for relation "inventory" violates check constraint
"cost_check" | Exception Details: Failing row contains (7, 35, Macaron).
DO
postgres=# \x on
Expanded display is on.
postgres=# select msg, detail from errors;
-[ RECORD 1 ]-------------------------------------------------------------------
msg | new row for relation "inventory" violates check constraint "cost_check"
detail | Failing row contains (7, 35, Macaron).
| Nume | Descriere |
|---|---|
| RETURNED_SQLSTATE | codul de eroare SQLSTATE al excepției |
| COLUMN_NAME | numele coloanei asociate excepției |
| CONSTRAINT_NAME | numele constrângerii asociate excepției |
| MESSAGE_TEXT | textul mesajului principal al excepției |
| PG_EXCEPTION_DETAIL | textul mesajului de detaliu al excepției, dacă există |
| Nume | Descriere |
|---|---|
| PG_DATATYPE_NAME | numele tipului de date asociat excepției |
| TABLE_NAME | numele tabelei asociate excepției |
| SCHEMA_NAME | numele schemei asociate excepției |
| PG_EXCEPTION_HINT | textul mesajului de sugestie al excepției, dacă există |
| PG_EXCEPTION_CONTEXT | linie(i) de text ale stivei de apeluri la momentul excepției |
Tranzacții și gestionarea erorilor în PostgreSQL