Transactions and rollback
Transactions and rollback
A transaction groups statements into one unit of work. Commit makes the changes durable according to the database settings; rollback abandons uncommitted changes. A multi-row stock transfer should not subtract from one location without adding to the other. The database enforces constraints, while application code must choose the transaction boundary and handle failures.
Proposed baseline: .NET SDK 10.0.404, net10.0 / C# 14. Requires reviewed Microsoft.Data.Sqlite 10.0.15 candidate package and native dependencies. All databases are private in-memory fixtures; no network or disk database. C# results are reasoned, not executed. See the accompanying independent project fixture; approve dependencies and environment before restoring or building.
Commit a successful transfer
Both commands share the same open connection and transaction. The synthetic rows start at 5 and 2 units.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "CREATE TABLE Stock (Id INTEGER PRIMARY KEY, Units INTEGER NOT NULL CHECK(Units >= 0))";cmd.ExecuteNonQuery();cmd.CommandText = "INSERT INTO Stock VALUES (1, 5), (2, 2)";cmd.ExecuteNonQuery();using (var tx = db.BeginTransaction()){ cmd.Transaction = tx; cmd.CommandText = "UPDATE Stock SET Units = Units - 3 WHERE Id = 1"; if (cmd.ExecuteNonQuery() != 1) throw new InvalidOperationException("Missing source"); cmd.CommandText = "UPDATE Stock SET Units = Units + 3 WHERE Id = 2"; if (cmd.ExecuteNonQuery() != 1) throw new InvalidOperationException("Missing destination"); tx.Commit();}cmd.Transaction = null;cmd.CommandText = "SELECT Units FROM Stock ORDER BY Id";using var reader = cmd.ExecuteReader();while (reader.Read()) Console.WriteLine(reader.GetInt64(0));Both changes complete before Commit; row counts guard against a missing location. This in-memory fixture demonstrates transaction visibility on one connection, not crash durability.
Expected observation (reasoned, not executed):
25Rollback after a failed constraint
The second statement violates the nonnegative constraint after an earlier update succeeded. The catch rolls back the entire transaction.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "CREATE TABLE Stock (Id INTEGER PRIMARY KEY, Units INTEGER NOT NULL CHECK(Units >= 0))";cmd.ExecuteNonQuery();cmd.CommandText = "INSERT INTO Stock VALUES (1, 5), (2, 2)";cmd.ExecuteNonQuery();using (var tx = db.BeginTransaction()){ cmd.Transaction = tx; try { cmd.CommandText = "UPDATE Stock SET Units = Units + 3 WHERE Id = 1"; cmd.ExecuteNonQuery(); cmd.CommandText = "UPDATE Stock SET Units = Units - 3 WHERE Id = 2"; cmd.ExecuteNonQuery(); tx.Commit(); } catch (SqliteException) { tx.Rollback(); Console.WriteLine("Transfer rolled back"); }}cmd.Transaction = null;cmd.CommandText = "SELECT Units FROM Stock ORDER BY Id";using var reader = cmd.ExecuteReader();while (reader.Read()) Console.WriteLine(reader.GetInt64(0));The failing CHECK normally aborts the offending statement in this fixture; the explicit rollback also reverses the earlier successful statement. Do not assume every database error leaves a transaction in the same state.
Expected observation (reasoned, not executed):
Transfer rolled back52Guard a conditional update
An insufficient balance can be handled without a constraint error by expressing the precondition in the UPDATE and checking the affected row count.
using System;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();using var cmd = db.CreateCommand();cmd.CommandText = "CREATE TABLE Stock (Id INTEGER PRIMARY KEY, Units INTEGER NOT NULL CHECK(Units >= 0))";cmd.ExecuteNonQuery();cmd.CommandText = "INSERT INTO Stock VALUES (1, 2)";cmd.ExecuteNonQuery();using (var tx = db.BeginTransaction()){ cmd.Transaction = tx; cmd.CommandText = "UPDATE Stock SET Units = Units - $amount WHERE Id = 1 AND Units >= $amount"; cmd.Parameters.AddWithValue("$amount", 3); if (cmd.ExecuteNonQuery() == 1) { tx.Commit(); Console.WriteLine("Updated"); } else { tx.Rollback(); Console.WriteLine("Not enough stock or missing item"); }}cmd.Transaction = null;cmd.Parameters.Clear();cmd.CommandText = "SELECT Units FROM Stock WHERE Id = 1";Console.WriteLine(cmd.ExecuteScalar());The precondition and update are one SQL operation. Zero affected rows is a business failure here; no change is committed. A full transfer would also check destination existence and commit only after both changes.
Expected observation (reasoned, not executed):
Not enough stock or missing item2Common mistakes and edge cases
Atomicity is all-or-nothing for the transaction; isolation governs interaction with concurrent transactions and is not the same property. SQLite supports limited concurrent writes and has provider-specific transaction and timeout behavior; PostgreSQL and SQL Server differ. Never hold a transaction open while waiting for user input or external HTTP calls. For real retry logic distinguish transient errors from constraint failures and handle uncertain commit outcomes; blindly retrying a non-idempotent operation can duplicate work. Rollback itself can fail after certain connection errors, so production code must preserve the original failure and handle cleanup. These examples intentionally use single-connection in-memory data and do not establish crash recovery or multi-user isolation.
Practice and recap
Extend the transfer to move 4 units from a source containing 3 to an existing destination containing 7. Specify the result after rejection, a valid transfer of 2, and a missing-destination case. Use one transaction, positive amount validation and affected-row checks.
Hint: Check amount and source availability.
Learning objective: Verify atomic changes on a real fixture. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Transactions and rollback — knowledge check
Apply the lesson concepts to the following scenarios.
When should a two-row transfer commit?
What does rollback do here?
What does a zero affected-row count indicate in the guarded update?
Does an in-memory commit demonstrate crash durability?
What does transaction isolation describe?