Databases & SQL Master Course — 148. Application Transactions and Errors
Lesson 148 Application Transactions and Errors
Prerequisites and objectives
Complete connection lifecycles, guarded writes, and retryable concurrency failures. You will map statement results to application outcomes, recover a failed multi-write operation, and use a savepoint only when a deliberately optional sub-operation may be abandoned without invalidating the required business work.
Success has several layers
A driver returning normally means a statement executed, not necessarily that the business request succeeded. A guarded UPDATE may affect zero rows. A later INSERT may fail after an earlier change remains pending. A successful COMMIT accepts the transaction, while a lost connection around COMMIT can leave the client uncertain about that acceptance.
Define the operation before writing error handlers. This fictional order consumes stock and records its quantity together. A note is optional under this lesson’s stated contract. The application reports accepted only after the required transaction commits, insufficient stock when the guarded decrement finds no row, and a classified retryable outcome for bounded contention.
Do not build one generic catch block that retries every error. A duplicate business identity, invalid quantity, busy writer, and uncertain connection state require different decisions. Use structured driver error codes and transaction-state information, then preserve enough redacted context to diagnose the operation without exposing private input.
PRAGMA journal_mode=WAL;
CREATE TABLE lab_stock148(id INTEGER PRIMARY KEY,qty INTEGER NOT NULL CHECK(qty>=0));
CREATE TABLE lab_order148(id INTEGER PRIMARY KEY,units INTEGER NOT NULL CHECK(units>0));
CREATE TABLE lab_note148(order_id INTEGER PRIMARY KEY,note TEXT NOT NULL CHECK(length(note)<=10));
INSERT INTO lab_stock148 VALUES(1,5);
| Observation | Meaning | Application response |
|---|---|---|
| No guarded update row | Stock precondition failed | Rollback and reject the order |
| Constraint error | A declared data rule failed | Rollback required work or recover an explicitly optional unit |
| Busy before work | Writer contention | Bounded fresh attempt if appropriate |
| Unknown commit outcome | Acceptance cannot be inferred | Reconcile using operation identity |
Worked practice
Exercise 1
Complete the required stock decrement and order record together.
Worked solution
-- Connection A
BEGIN IMMEDIATE;
-- Connection A
UPDATE lab_stock148 SET qty=qty-2 WHERE id=1 AND qty>=2 RETURNING qty;
-- Connection A
INSERT INTO lab_order148 VALUES(1,2);
-- Connection A
COMMIT;
-- Connection A
SELECT qty,(SELECT SUM(units) FROM lab_order148) FROM lab_stock148;
The returned stock row confirms that the precondition held. The order INSERT then succeeds and COMMIT accepts both required effects. If the guarded UPDATE had returned no row, application control flow must skip the INSERT and roll back. Comments or examples cannot replace that branch in the actual calling code.
Exercise 2
Recover a duplicate order error without keeping the preceding decrement.
Worked solution
-- Connection A
INSERT INTO lab_order148 VALUES(9,1);
-- Connection A
UPDATE lab_stock148 SET qty=4 WHERE id=1;
-- Connection A
BEGIN IMMEDIATE;
-- Connection A
UPDATE lab_stock148 SET qty=qty-2 WHERE id=1 AND qty>=2 RETURNING qty;
-- Connection A
INSERT INTO lab_order148 VALUES(9,2);
-- Connection A
ROLLBACK;
-- Connection A
SELECT qty,(SELECT SUM(units) FROM lab_order148) FROM lab_stock148;
The fixture first establishes an accepted one-unit order. The new attempt reuses its identity and triggers SQLITE_CONSTRAINT_PRIMARYKEY. Rollback returns the stock to four rather than preserving the attempted extra debit. A complete idempotency design would compare the stored request and outcome; this exercise demonstrates cleanup, not automatic replay acceptance.
Exercise 3
Reject an invalid optional note while preserving valid required work.
Worked solution
-- Connection A
BEGIN IMMEDIATE;
-- Connection A
UPDATE lab_stock148 SET qty=qty-2 WHERE id=1 AND qty>=2 RETURNING qty;
-- Connection A
INSERT INTO lab_order148 VALUES(1,2);
-- Connection A
SAVEPOINT optional_note;
-- Connection A
INSERT INTO lab_note148 VALUES(1,'This note is too long');
-- Connection A
ROLLBACK TO optional_note;
-- Connection A
RELEASE optional_note;
-- Connection A
COMMIT;
-- Connection A
SELECT qty,(SELECT COUNT(*) FROM lab_order148),(SELECT COUNT(*) FROM lab_note148) FROM lab_stock148;
The note CHECK fails. Rolling back to the savepoint abandons the optional unit while retaining the earlier stock and order work. RELEASE removes the savepoint marker; the outer COMMIT accepts the required operation. This is valid only because the contract explicitly allows an order without a note. Do not use savepoints to conceal failure of a required audit or inventory step.
Exercise 4
Handle writer contention before starting an order attempt.
Worked solution
-- Connection A
BEGIN IMMEDIATE;
-- Connection B
BEGIN IMMEDIATE;
-- Connection A
ROLLBACK;
-- Connection B
BEGIN IMMEDIATE;
-- Connection B
UPDATE lab_stock148 SET qty=qty-1 WHERE id=1 AND qty>=1 RETURNING qty;
-- Connection B
INSERT INTO lab_order148 VALUES(2,1);
-- Connection B
COMMIT;
-- Connection A
SELECT qty FROM lab_stock148;
B’s first BEGIN fails before its business writes. After A releases the writer role, B starts a fresh complete attempt and commits one order. A production retry policy needs a deadline, an attempt limit, and a wait strategy. This deterministic lab controls timing directly and does not implement an unbounded automatic retry loop.
Own the transaction in one application layer
A repository function may execute SQL while a service layer owns the broader operation. Decide which layer begins, commits, and rolls back. Hidden commits inside helper functions can split a larger invariant, while nested BEGIN calls fail in SQLite rather than creating independent nested transactions.
Savepoints provide a scoped recovery mechanism inside an existing transaction. Releasing an inner savepoint is not an independent durable commit; an outer rollback can still abandon all its work. Propagate failures of required operations to the owner instead of converting them into misleading success values.
On exceptions or cancellation, inspect the connection’s transaction state and perform the appropriate cleanup. Some SQLite errors can end a transaction automatically, while ordinary constraint failures commonly abort only the statement. Do not assume one behavior for all error classes or all database engines. A connection whose state cannot be safely restored should not return to a pool.
Handle uncertain acceptance separately
The lab executes local statements with observed outcomes; it does not simulate a network break during COMMIT. In a client-server system, a missing commit response does not prove rollback. Repeating a non-idempotent operation with a new identity can duplicate it. Reconcile the original operation identity or use a designed idempotency protocol before deciding what to repeat.
External effects also need their own boundary. A database rollback cannot retract an already sent message. If a durable event must accompany the order, record an outbox entry in the required transaction and design its delivery for retries, rather than sending a notification inside every database attempt.
Pitfalls and summary
Check affected rows, classify failures, and keep the required operation atomic. Use savepoints only for explicitly recoverable sub-operations. Separate a known rejection from transient contention and uncertain commit acceptance. The user-facing outcome should describe what is actually known, not merely whether the last SQL call returned without an exception.
Knowledge check
Question 1
When may this application report an accepted order?
- Immediately after BEGIN succeeds
- After the guarded UPDATE returns no rows
- Whenever the INSERT text is syntactically valid
- After all required effects have committed successfully
Answer and explanation
D. Business acceptance requires the complete required transaction, not one intermediate statement.
Question 2
Why did the duplicate-order trial explicitly roll back?
- Its earlier successful stock decrement was still pending
- The duplicate-key error automatically inserted a replacement order
- The duplicate-key error ended the entire transaction, leaving nothing pending
- The failed INSERT automatically committed the preceding successful decrement
Answer and explanation
A. Whole-operation cleanup prevents a partial effect from surviving a later statement error.
Question 3
Why was savepoint recovery appropriate for the note trial?
- Every audit and inventory step is always optional
- RELEASE commits the order independently of the outer transaction
- The stated contract permits the order without that optional note
- Savepoints make constraint violations irrelevant to business rules
Answer and explanation
C. Partial recovery is justified by the operation’s explicit semantics.
Question 4
What does RELEASE of an inner savepoint do here?
- Durably commits all earlier changes despite a later outer rollback
- Creates a separate database connection
- Automatically retries the failed note INSERT
- Removes that recovery marker while the outer transaction still controls acceptance
Answer and explanation
D. An inner release does not replace the outer COMMIT boundary.
Question 5
What should an application infer from a lost commit acknowledgement?
- The transaction definitely rolled back
- The outcome may be uncertain and needs reconciliation
- The transaction definitely committed twice
- A new request identity automatically deduplicates the operation
Answer and explanation
B. A missing response alone does not establish the database’s accepted state.
Execution scope
These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.
Primary references
- Transactions and errors: Statement versus transaction failure and cleanup.
- Savepoints: ROLLBACK TO, RELEASE, and outer boundaries.
- Result codes: Constraint and busy error classification.
- RETURNING: Inspecting guarded write outcomes.