PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi
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)
| Koşul Adı | Örnek |
|---|---|
| unique_violation | Benzersiz bir sütuna aynı değerden iki tane eklemek |
| not_null_violation | Null kabul etmeyen bir alana null eklemek |
| check_violation | Lezzetlilikte 11’in üzerinde olma gibi bir check kısıtını ihlal etmek |
| division_by_zero | 0’a bölmek |
Daha fazlası için aşağıdaki bağlantıya bakınız
DO $$
BEGIN
UPDATE inventory SET quantity = quantity - 6, cost = null
WHERE name='oatmeal dark chocolate';
-- check_violation istisnasını ekleyin
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.';
-- not_null istisnasını ekleyin
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)
PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi