Testing triggers and choosing constraints
Overview
Test triggers as part of the complete data-modification workflow, not only as isolated functions. Check valid and invalid input, no-op updates, NULL transitions, multi-row statements, zero matches, rollbacks and downstream effects. Prefer declarative constraints for rules they can express, such as a nonnegative quantity; use triggers for appropriate procedural side effects.
First example
BEGIN;UPDATE tr_item SET qty=100 WHERE id=1;SELECT qty,(SELECT COUNT(*) FROM tr_audit) FROM tr_item WHERE id=1;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 100, 1 ]]How it works
The first script tests the upper boundary of the BEFORE guard and confirms that the AFTER audit event is generated. The second verifies an empty update produces no row-level audit entry. The separate edge suite checks rejection of qty=101, CHECK failure for negative stock, multi-row atomicity with RAISE(ABORT), rollback and recursion-depth failure. The validator uses a fresh database for every case and verifies expected errors and post-error state. In PostgreSQL a trigger error ordinarily leaves the transaction failed until rollback or savepoint recovery; SQLite ABORT normally undoes the failed statement, not prior work. Avoid brittle assumptions about event order across rows; sort results by business key where the processing order is not guaranteed. Add migration, permissions and concurrent tests before deploying.
Practical example
BEGIN;UPDATE tr_item SET qty=1 WHERE id=999;SELECT COUNT(*) FROM tr_audit;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 0 ]]Practice and mistakes
Practice: predict the result of updating item 1 to 5 and item 2 to 101 in one statement. Hint 1: use CASE on id. Hint 2: the second value violates the BEFORE guard; ABORT leaves both quantities and audit rows unchanged. Run the provided edge test, not a production database.