3 ms·
Some additional techniques for triggers I've found helpful: - Triggers for validation are awesome. Avoid triggers for logic if you can help it -- harder to deb
by sa46 3y ago
Some additional techniques for triggers I've found helpful:
- Triggers for validation are awesome. Avoid triggers for logic if you can help it -- harder to debug and update than a server sending SQL and easier than you might think to cause performance problems and cascading triggers.
- Use custom error codes in validation triggers and add as much context as possible to the message when raising the exception. Future you will thank you.
RAISE EXCEPTION USING
ERRCODE = 'SR010',
MESSAGE = 'cannot add a draft invoice ' || new.invoice_id || ' to route ' || new.route_id;
- Postgres exceptions abort transactions, so if using explicit transactions, make sure you have a defer Rollback() so you don't return an aborted transaction to the server connection pool.
- For better trigger performance, prefer statement-level triggers [1] or conditional before-row-based triggers.
[1]: https://www.postgresql.org/docs/current/trigger-definition.html https://www.postgresql.org/docs/current/trigger-definition.h...