Patterncore
Unit of Work
Also called unit of work pattern, UoW, transactional write-behind.
A Unit of Work records the objects that a business transaction adds, changes and removes, and then writes all the changes to the database in one short transaction.
- Family
- architectural
- Intent
- Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.
Intent
A Unit of Work "Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."1 The program changes objects in memory. The Unit of Work remembers what changed and, at the end, writes all of it to the database in one transaction.
Problem
A business transaction, such as a money transfer, changes several objects: two accounts change their balances and two ledger entries are new. The database must get all of these changes or none of them.
If the program writes each change at once, it makes many small database calls. Fowler's catalogue says that this "can lead to lots of very small database calls, which ends up being very slow." It also needs a database transaction that stays open for the whole interaction, "which is impractical if you have a business transaction that spans multiple requests."1
If the program does not write each change at once, something must remember the changes. Otherwise "that data won't be written back into the database."1 The domain code should not do this bookkeeping itself, because then every business method must know which objects are new, which are changed and which are deleted, and in which order to write them.
Solution
Give the bookkeeping to one object. The business code tells the Unit of Work about each new, changed and removed object. When the business transaction is done, the program calls commit. The Unit of Work then opens a database transaction, writes the inserts, the updates and the deletes through the mappers, and commits. If one statement fails, it rolls back, and the database keeps none of the changes. "When you're done, it figures out everything that needs to be done to alter the database as a result of your work."12
business code UnitOfWork database
transfer(a, b, 30)
a.balance -= 30 ---------> register_dirty(a) dirty: [a, b]
b.balance += 30 ---------> register_dirty(b) new: [e1, e2]
new Entry e1, e2 ---------> register_new(e1, e2) removed: []
commit() ---------> BEGIN
insert e1, e2 ----------------> INSERT INTO entries
update a, b ----------------> UPDATE accounts
delete ... ----------------> DELETE FROM ...
COMMIT, or ROLLBACK on the first error
The participants are the business code, which changes objects and registers them; the Unit of Work, which keeps the lists of new, dirty and removed objects and controls the database transaction; and the mappers, which know the SQL for each kind of object.
The following program uses SQLite. It traces each SQL statement. The transfer function has no SQL. The first commit writes four statements in one transaction. The second commit fails on the CHECK constraint, and the rollback also removes the two entries that it had already inserted.
import sqlite3
from dataclasses import dataclass
@dataclass
class Account:
id: int
owner: str
balance: int
@dataclass
class Entry:
account_id: int
amount: int
# Each mapper has only the methods that this program needs.
class AccountMapper:
def update(self, db, a):
db.execute("UPDATE accounts SET owner = ?, balance = ? WHERE id = ?", (a.owner, a.balance, a.id))
class EntryMapper:
def insert(self, db, e):
db.execute("INSERT INTO entries (account_id, amount) VALUES (?, ?)", (e.account_id, e.amount))
class UnitOfWork:
"""Records what a business transaction changes, and writes it all in one database transaction."""
def __init__(self, db, mappers):
self.db, self.mappers = db, mappers
self.new, self.dirty, self.removed = [], [], []
def register_new(self, obj):
self.new.append(obj)
def register_dirty(self, obj):
if not any(o is obj for o in self.new + self.dirty):
self.dirty.append(obj)
def register_removed(self, obj):
self.removed.append(obj)
def commit(self):
try:
with self.db: # commits at the end, or rolls back if a statement fails
for obj in self.new:
self.mappers[type(obj)].insert(self.db, obj)
for obj in self.dirty:
self.mappers[type(obj)].update(self.db, obj)
for obj in self.removed:
self.mappers[type(obj)].delete(self.db, obj)
finally:
self.new, self.dirty, self.removed = [], [], []
def transfer(uow, source, target, amount):
"""Business logic: change objects in memory and tell the unit of work. No SQL here."""
source.balance -= amount
target.balance += amount
uow.register_dirty(source)
uow.register_dirty(target)
uow.register_new(Entry(source.id, -amount))
uow.register_new(Entry(target.id, amount))
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER CHECK (balance >= 0));
CREATE TABLE entries (id INTEGER PRIMARY KEY, account_id INTEGER, amount INTEGER);
INSERT INTO accounts VALUES (1, 'ann', 100), (2, 'bob', 0);
""")
db.set_trace_callback(lambda sql: print(" sql:", sql.split(" (")[0].strip()))
mappers = {Account: AccountMapper(), Entry: EntryMapper()}
ann, bob = Account(1, "ann", 100), Account(2, "bob", 0)
uow = UnitOfWork(db, mappers)
transfer(uow, ann, bob, 30)
print("nothing written yet:", db.execute("SELECT count(*) FROM entries").fetchone()[0], "entries")
print("commit 1")
uow.commit()
uow = UnitOfWork(db, mappers)
transfer(uow, bob, ann, 50) # bob has 30, so the CHECK constraint fails
print("commit 2")
try:
uow.commit()
except sqlite3.IntegrityError as e:
print(" failed:", type(e).__name__)
db.set_trace_callback(None)
print("accounts:", db.execute("SELECT * FROM accounts").fetchall())
print("entries:", db.execute("SELECT account_id, amount FROM entries").fetchall())
sql: SELECT count(*) FROM entries
nothing written yet: 0 entries
commit 1
sql: BEGIN
sql: INSERT INTO entries
sql: INSERT INTO entries
sql: UPDATE accounts SET owner = 'ann', balance = 70 WHERE id = 1
sql: UPDATE accounts SET owner = 'bob', balance = 30 WHERE id = 2
sql: COMMIT
commit 2
sql: BEGIN
sql: INSERT INTO entries
sql: INSERT INTO entries
sql: UPDATE accounts SET owner = 'bob', balance = -20 WHERE id = 2
sql: ROLLBACK
failed: IntegrityError
accounts: [(1, 'ann', 70), (2, 'bob', 30)]
entries: [(1, -30), (2, 30)]
The table has only the entries of the first transfer. After the failed commit, the objects ann and bob in memory still hold the balances 120 and -20. They no longer match the database, so a program must load them again or drop them. Doctrine closes its EntityManager when a commit fails, and the Doctrine documentation says that changes that are not yet written "are lost" when a Unit of Work is closed.34
Example
Each example file has an Account class, an Entry class, mappers for both, and a UnitOfWork with register_new, register_dirty, register_removed and commit. The program runs three business transactions: a transfer that succeeds, a transfer that fails and rolls back, and the close of an account, where the account is first dirty and then removed, so that the Unit of Work writes a DELETE and no UPDATE for it. The Python file uses SQLite. The JavaScript, Java, Go and Rust files keep the tables in memory, and their transaction method keeps a copy of the tables and puts it back when a statement fails, because the standard libraries of these languages have no database driver. The Unit of Work compares objects by identity, not by value, in every file.
import sqlite3
from dataclasses import dataclass
@dataclass
class Account:
id: int
owner: str
balance: int
@dataclass
class Entry:
account_id: int
amount: int
class AccountMapper:
def find(self, db, id):
return Account(*db.execute("SELECT id, owner, balance FROM accounts WHERE id = ?", (id,)).fetchone())
def update(self, db, a):
print(f" update accounts {a.id} {a.owner} {a.balance}")
db.execute("UPDATE accounts SET owner = ?, balance = ? WHERE id = ?", (a.owner, a.balance, a.id))
def delete(self, db, a):
print(f" delete accounts {a.id}")
db.execute("DELETE FROM accounts WHERE id = ?", (a.id,))
class EntryMapper:
def insert(self, db, e):
print(f" insert entries ({e.account_id}, {e.amount})")
db.execute("INSERT INTO entries (account_id, amount) VALUES (?, ?)", (e.account_id, e.amount))
class UnitOfWork:
def __init__(self, db, mappers):
self.db, self.mappers = db, mappers
self.new, self.dirty, self.removed = [], [], []
@staticmethod
def _has(objs, obj):
return any(o is obj for o in objs)
def register_new(self, obj):
self.new.append(obj)
def register_dirty(self, obj):
if not self._has(self.new, obj) and not self._has(self.dirty, obj):
self.dirty.append(obj)
def register_removed(self, obj):
if self._has(self.new, obj): # never written, so there is nothing to delete
self.new = [o for o in self.new if o is not obj]
return
self.dirty = [o for o in self.dirty if o is not obj] # no UPDATE before the DELETE
self.removed.append(obj)
def commit(self):
try:
with self.db: # one transaction: COMMIT at the end, ROLLBACK if a statement fails
for obj in self.new:
self.mappers[type(obj)].insert(self.db, obj)
for obj in self.dirty:
self.mappers[type(obj)].update(self.db, obj)
for obj in self.removed:
self.mappers[type(obj)].delete(self.db, obj)
print(" commit")
except sqlite3.IntegrityError as e:
print(" rollback:", e)
finally:
self.new, self.dirty, self.removed = [], [], []
def transfer(uow, source, target, amount):
source.balance -= amount
target.balance += amount
uow.register_dirty(source)
uow.register_dirty(target)
uow.register_new(Entry(source.id, -amount))
uow.register_new(Entry(target.id, amount))
def show(db):
print("accounts:", " | ".join(f"{i} {o} {b}" for i, o, b in db.execute("SELECT * FROM accounts ORDER BY id")))
print("entries:", " | ".join(f"{a} {m}" for a, m in db.execute("SELECT account_id, amount FROM entries ORDER BY id")))
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER CHECK (balance >= 0));
CREATE TABLE entries (id INTEGER PRIMARY KEY, account_id INTEGER, amount INTEGER);
INSERT INTO accounts VALUES (1, 'ann', 100), (2, 'bob', 0);
""")
accounts = AccountMapper()
mappers = {Account: accounts, Entry: EntryMapper()}
# Each business transaction loads fresh objects and has its own unit of work.
uow = UnitOfWork(db, mappers)
transfer(uow, accounts.find(db, 1), accounts.find(db, 2), 30)
print("pending:", len(uow.new), "new,", len(uow.dirty), "dirty; entries in the table:", db.execute("SELECT count(*) FROM entries").fetchone()[0])
print("commit 1")
uow.commit()
uow = UnitOfWork(db, mappers)
transfer(uow, accounts.find(db, 2), accounts.find(db, 1), 50) # bob has only 30
print("commit 2")
uow.commit()
show(db)
uow = UnitOfWork(db, mappers)
ann, bob = accounts.find(db, 1), accounts.find(db, 2)
transfer(uow, bob, ann, 30) # close bob's account: move the money, then remove it
uow.register_removed(bob)
print("commit 3")
uow.commit()
show(db)
pending: 2 new, 2 dirty; entries in the table: 0
commit 1
insert entries (1, -30)
insert entries (2, 30)
update accounts 1 ann 70
update accounts 2 bob 30
commit
commit 2
insert entries (2, -50)
insert entries (1, 50)
update accounts 2 bob -20
rollback: CHECK constraint failed: balance >= 0
accounts: 1 ann 70 | 2 bob 30
entries: 1 -30 | 2 30
commit 3
insert entries (2, -30)
insert entries (1, 30)
update accounts 1 ann 100
delete accounts 2
commit
accounts: 1 ann 100
entries: 1 -30 | 2 30 | 2 -30 | 1 30
- Verdict: idiom.
with self.db:makes the commit one SQLite transaction: it commits when the block ends and rolls back when a statement raises an exception. register_removeddrops a pendingUPDATEof the same object, so commit 3 writes aDELETEand noUPDATEfor account 2. The lists compare objects withis, because twoEntryobjects with the same fields are equal under==but are two rows.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
static final class Account {
final int id;
String owner;
int balance;
Account(int id, String owner, int balance) {
this.id = id;
this.owner = owner;
this.balance = balance;
}
}
record Entry(int accountId, int amount) {}
record AccountRow(String owner, int balance) {}
// A stand-in for the database, because the JDK has JDBC but no database driver.
// transaction() keeps a copy of the tables and puts it back when a statement fails.
static final class Database {
TreeMap<Integer, AccountRow> accounts = new TreeMap<>(Map.of(1, new AccountRow("ann", 100), 2, new AccountRow("bob", 0)));
List<Entry> entries = new ArrayList<>();
void transaction(Runnable work) {
var savedAccounts = new TreeMap<>(accounts);
var savedEntries = new ArrayList<>(entries);
try {
work.run();
} catch (IllegalStateException e) {
accounts = savedAccounts;
entries = savedEntries;
throw e;
}
}
void updateAccount(int id, String owner, int balance) {
if (balance < 0) throw new IllegalStateException("CHECK constraint failed: balance >= 0");
accounts.put(id, new AccountRow(owner, balance));
}
}
interface Mapper {
default void insert(Database db, Object obj) { throw new UnsupportedOperationException(); }
default void update(Database db, Object obj) { throw new UnsupportedOperationException(); }
default void delete(Database db, Object obj) { throw new UnsupportedOperationException(); }
}
static final class AccountMapper implements Mapper {
Account find(Database db, int id) {
var row = db.accounts.get(id);
return new Account(id, row.owner(), row.balance());
}
public void update(Database db, Object obj) {
var a = (Account) obj;
System.out.println(" update accounts " + a.id + " " + a.owner + " " + a.balance);
db.updateAccount(a.id, a.owner, a.balance);
}
public void delete(Database db, Object obj) {
var a = (Account) obj;
System.out.println(" delete accounts " + a.id);
db.accounts.remove(a.id);
}
}
static final class EntryMapper implements Mapper {
public void insert(Database db, Object obj) {
var e = (Entry) obj;
System.out.println(" insert entries (" + e.accountId() + ", " + e.amount() + ")");
db.entries.add(e);
}
}
static final class UnitOfWork {
private final Database db;
private final Map<Class<?>, Mapper> mappers;
private List<Object> created = new ArrayList<>(), dirty = new ArrayList<>(), removed = new ArrayList<>();
UnitOfWork(Database db, Map<Class<?>, Mapper> mappers) {
this.db = db;
this.mappers = mappers;
}
// Identity, not equals: two equal records are still two objects to write.
private static boolean has(List<Object> objs, Object obj) {
return objs.stream().anyMatch(o -> o == obj);
}
String pending() {
return created.size() + " new, " + dirty.size() + " dirty";
}
void registerNew(Object obj) {
created.add(obj);
}
void registerDirty(Object obj) {
if (!has(created, obj) && !has(dirty, obj)) dirty.add(obj);
}
void registerRemoved(Object obj) {
if (has(created, obj)) { // never written, nothing to delete
created.removeIf(o -> o == obj);
return;
}
dirty.removeIf(o -> o == obj); // no update before the delete
removed.add(obj);
}
void commit() {
try {
db.transaction(() -> {
for (var obj : created) mappers.get(obj.getClass()).insert(db, obj);
for (var obj : dirty) mappers.get(obj.getClass()).update(db, obj);
for (var obj : removed) mappers.get(obj.getClass()).delete(db, obj);
});
System.out.println(" commit");
} catch (IllegalStateException e) {
System.out.println(" rollback: " + e.getMessage());
} finally {
created = new ArrayList<>();
dirty = new ArrayList<>();
removed = new ArrayList<>();
}
}
}
static void transfer(UnitOfWork uow, Account source, Account target, int amount) {
source.balance -= amount;
target.balance += amount;
uow.registerDirty(source);
uow.registerDirty(target);
uow.registerNew(new Entry(source.id, -amount));
uow.registerNew(new Entry(target.id, amount));
}
static void show(Database db) {
System.out.println("accounts: " + db.accounts.entrySet().stream()
.map(e -> e.getKey() + " " + e.getValue().owner() + " " + e.getValue().balance())
.collect(Collectors.joining(" | ")));
System.out.println("entries: " + db.entries.stream()
.map(e -> e.accountId() + " " + e.amount())
.collect(Collectors.joining(" | ")));
}
public static void main(String[] args) {
var db = new Database();
var accounts = new AccountMapper();
Map<Class<?>, Mapper> mappers = new HashMap<>(Map.of(Account.class, accounts, Entry.class, new EntryMapper()));
var uow = new UnitOfWork(db, mappers);
transfer(uow, accounts.find(db, 1), accounts.find(db, 2), 30);
System.out.println("pending: " + uow.pending() + "; entries in the table: " + db.entries.size());
System.out.println("commit 1");
uow.commit();
uow = new UnitOfWork(db, mappers);
transfer(uow, accounts.find(db, 2), accounts.find(db, 1), 50); // bob has only 30
System.out.println("commit 2");
uow.commit();
show(db);
uow = new UnitOfWork(db, mappers);
var ann = accounts.find(db, 1);
var bob = accounts.find(db, 2);
transfer(uow, bob, ann, 30); // close bob's account: move the money, then remove it
uow.registerRemoved(bob);
System.out.println("commit 3");
uow.commit();
show(db);
}
}
pending: 2 new, 2 dirty; entries in the table: 0
commit 1
insert entries (1, -30)
insert entries (2, 30)
update accounts 1 ann 70
update accounts 2 bob 30
commit
commit 2
insert entries (2, -50)
insert entries (1, 50)
update accounts 2 bob -20
rollback: CHECK constraint failed: balance >= 0
accounts: 1 ann 70 | 2 bob 30
entries: 1 -30 | 2 30
commit 3
insert entries (2, -30)
insert entries (1, 30)
update accounts 1 ann 100
delete accounts 2
commit
accounts: 1 ann 100
entries: 1 -30 | 2 30 | 2 -30 | 1 30
- Verdict: idiom. The lists compare with
==, not withequals, because twoEntryrecords with the same fields are equal but are two rows. Database.transactiontakes aRunnable, keeps copies of the tables and puts them back when a statement throws, as a database rolls back a transaction.
class Account {
constructor(id, owner, balance) {
Object.assign(this, { id, owner, balance });
}
}
class Entry {
constructor(accountId, amount) {
Object.assign(this, { accountId, amount });
}
}
// A stand-in for the database, because Node has no SQL driver in its standard library.
// transaction() keeps a copy of the tables and puts it back when a statement fails.
class Database {
accounts = new Map([[1, { owner: "ann", balance: 100 }], [2, { owner: "bob", balance: 0 }]]);
entries = [];
transaction(work) {
const saved = [new Map(this.accounts), [...this.entries]];
try {
work();
} catch (e) {
[this.accounts, this.entries] = saved;
throw e;
}
}
updateAccount(id, owner, balance) {
if (balance < 0) throw new Error("CHECK constraint failed: balance >= 0");
this.accounts.set(id, { owner, balance });
}
}
const accountMapper = {
find: (db, id) => new Account(id, db.accounts.get(id).owner, db.accounts.get(id).balance),
update(db, a) {
console.log(` update accounts ${a.id} ${a.owner} ${a.balance}`);
db.updateAccount(a.id, a.owner, a.balance);
},
delete(db, a) {
console.log(` delete accounts ${a.id}`);
db.accounts.delete(a.id);
},
};
const entryMapper = {
insert(db, e) {
console.log(` insert entries (${e.accountId}, ${e.amount})`);
db.entries.push({ accountId: e.accountId, amount: e.amount });
},
};
class UnitOfWork {
#new = [];
#dirty = [];
#removed = [];
constructor(db, mappers) {
this.db = db;
this.mappers = mappers;
}
get pending() {
return `${this.#new.length} new, ${this.#dirty.length} dirty`;
}
registerNew(obj) {
this.#new.push(obj);
}
registerDirty(obj) {
if (!this.#new.includes(obj) && !this.#dirty.includes(obj)) this.#dirty.push(obj);
}
registerRemoved(obj) {
if (this.#new.includes(obj)) {
this.#new = this.#new.filter((o) => o !== obj); // never written, nothing to delete
return;
}
this.#dirty = this.#dirty.filter((o) => o !== obj); // no update before the delete
this.#removed.push(obj);
}
commit() {
const mapper = (obj) => this.mappers.get(obj.constructor);
try {
this.db.transaction(() => {
for (const obj of this.#new) mapper(obj).insert(this.db, obj);
for (const obj of this.#dirty) mapper(obj).update(this.db, obj);
for (const obj of this.#removed) mapper(obj).delete(this.db, obj);
});
console.log(" commit");
} catch (e) {
console.log(` rollback: ${e.message}`);
} finally {
this.#new = [];
this.#dirty = [];
this.#removed = [];
}
}
}
function transfer(uow, source, target, amount) {
source.balance -= amount;
target.balance += amount;
uow.registerDirty(source);
uow.registerDirty(target);
uow.registerNew(new Entry(source.id, -amount));
uow.registerNew(new Entry(target.id, amount));
}
function show(db) {
console.log("accounts: " + [...db.accounts].sort((a, b) => a[0] - b[0]).map(([id, r]) => `${id} ${r.owner} ${r.balance}`).join(" | "));
console.log("entries: " + db.entries.map((e) => `${e.accountId} ${e.amount}`).join(" | "));
}
const db = new Database();
const mappers = new Map([[Account, accountMapper], [Entry, entryMapper]]);
let uow = new UnitOfWork(db, mappers);
transfer(uow, accountMapper.find(db, 1), accountMapper.find(db, 2), 30);
console.log(`pending: ${uow.pending}; entries in the table: ${db.entries.length}`);
console.log("commit 1");
uow.commit();
uow = new UnitOfWork(db, mappers);
transfer(uow, accountMapper.find(db, 2), accountMapper.find(db, 1), 50); // bob has only 30
console.log("commit 2");
uow.commit();
show(db);
uow = new UnitOfWork(db, mappers);
const ann = accountMapper.find(db, 1);
const bob = accountMapper.find(db, 2);
transfer(uow, bob, ann, 30); // close bob's account: move the money, then remove it
uow.registerRemoved(bob);
console.log("commit 3");
uow.commit();
show(db);
pending: 2 new, 2 dirty; entries in the table: 0
commit 1
insert entries (1, -30)
insert entries (2, 30)
update accounts 1 ann 70
update accounts 2 bob 30
commit
commit 2
insert entries (2, -50)
insert entries (1, 50)
update accounts 2 bob -20
rollback: CHECK constraint failed: balance >= 0
accounts: 1 ann 70 | 2 bob 30
entries: 1 -30 | 2 30
commit 3
insert entries (2, -30)
insert entries (1, 30)
update accounts 1 ann 100
delete accounts 2
commit
accounts: 1 ann 100
entries: 1 -30 | 2 30 | 2 -30 | 1 30
- Verdict: idiom. The lists are private fields (
#new,#dirty,#removed), andincludescompares objects by reference, so two entries with the same fields are two rows. - The mappers are found by the constructor of the object, in a
Mapfrom class to mapper.
package main
import (
"errors"
"fmt"
"maps"
"slices"
"strings"
)
type Account struct {
ID int
Owner string
Balance int
}
type Entry struct {
AccountID, Amount int
}
// A stand-in for the database. The Go standard library has database/sql,
// but no driver for a real database.
type accountRow struct {
owner string
balance int
}
type Database struct {
accounts map[int]accountRow
entries []Entry
}
// Transaction keeps a copy of the tables and puts it back when work fails.
func (db *Database) Transaction(work func() error) error {
savedAccounts, savedEntries := maps.Clone(db.accounts), slices.Clone(db.entries)
if err := work(); err != nil {
db.accounts, db.entries = savedAccounts, savedEntries
return err
}
return nil
}
func (db *Database) updateAccount(id int, owner string, balance int) error {
if balance < 0 {
return errors.New("CHECK constraint failed: balance >= 0")
}
db.accounts[id] = accountRow{owner, balance}
return nil
}
func findAccount(db *Database, id int) *Account {
row := db.accounts[id]
return &Account{id, row.owner, row.balance}
}
// The mapper functions write each kind of object.
// A type switch chooses the code for the type of the object.
func insert(db *Database, obj any) error {
switch o := obj.(type) {
case *Entry:
fmt.Printf(" insert entries (%d, %d)\n", o.AccountID, o.Amount)
db.entries = append(db.entries, *o)
return nil
}
return fmt.Errorf("no insert for %T", obj)
}
func update(db *Database, obj any) error {
switch o := obj.(type) {
case *Account:
fmt.Printf(" update accounts %d %s %d\n", o.ID, o.Owner, o.Balance)
return db.updateAccount(o.ID, o.Owner, o.Balance)
}
return fmt.Errorf("no update for %T", obj)
}
func remove(db *Database, obj any) error {
switch o := obj.(type) {
case *Account:
fmt.Printf(" delete accounts %d\n", o.ID)
delete(db.accounts, o.ID)
return nil
}
return fmt.Errorf("no delete for %T", obj)
}
// UnitOfWork holds pointers, so == compares identity, not field values.
type UnitOfWork struct {
db *Database
created, dirty, gone []any
}
func (u *UnitOfWork) RegisterNew(obj any) { u.created = append(u.created, obj) }
func (u *UnitOfWork) RegisterDirty(obj any) {
if !slices.Contains(u.created, obj) && !slices.Contains(u.dirty, obj) {
u.dirty = append(u.dirty, obj)
}
}
func (u *UnitOfWork) RegisterRemoved(obj any) {
if slices.Contains(u.created, obj) { // never written, nothing to delete
u.created = slices.DeleteFunc(u.created, func(o any) bool { return o == obj })
return
}
u.dirty = slices.DeleteFunc(u.dirty, func(o any) bool { return o == obj }) // no update before the delete
u.gone = append(u.gone, obj)
}
func (u *UnitOfWork) Commit() {
err := u.db.Transaction(func() error {
for _, step := range []struct {
objs []any
write func(*Database, any) error
}{{u.created, insert}, {u.dirty, update}, {u.gone, remove}} {
for _, obj := range step.objs {
if err := step.write(u.db, obj); err != nil {
return err
}
}
}
return nil
})
u.created, u.dirty, u.gone = nil, nil, nil
if err != nil {
fmt.Println(" rollback:", err)
return
}
fmt.Println(" commit")
}
func transfer(u *UnitOfWork, source, target *Account, amount int) {
source.Balance -= amount
target.Balance += amount
u.RegisterDirty(source)
u.RegisterDirty(target)
u.RegisterNew(&Entry{source.ID, -amount})
u.RegisterNew(&Entry{target.ID, amount})
}
func show(db *Database) {
var accounts, entries []string
for _, id := range slices.Sorted(maps.Keys(db.accounts)) {
accounts = append(accounts, fmt.Sprintf("%d %s %d", id, db.accounts[id].owner, db.accounts[id].balance))
}
for _, e := range db.entries {
entries = append(entries, fmt.Sprintf("%d %d", e.AccountID, e.Amount))
}
fmt.Println("accounts: " + strings.Join(accounts, " | "))
fmt.Println("entries: " + strings.Join(entries, " | "))
}
func main() {
db := &Database{accounts: map[int]accountRow{1: {"ann", 100}, 2: {"bob", 0}}}
u := &UnitOfWork{db: db}
transfer(u, findAccount(db, 1), findAccount(db, 2), 30)
fmt.Printf("pending: %d new, %d dirty; entries in the table: %d\n", len(u.created), len(u.dirty), len(db.entries))
fmt.Println("commit 1")
u.Commit()
u = &UnitOfWork{db: db}
transfer(u, findAccount(db, 2), findAccount(db, 1), 50) // bob has only 30
fmt.Println("commit 2")
u.Commit()
show(db)
u = &UnitOfWork{db: db}
ann, bob := findAccount(db, 1), findAccount(db, 2)
transfer(u, bob, ann, 30) // close bob's account: move the money, then remove it
u.RegisterRemoved(bob)
fmt.Println("commit 3")
u.Commit()
show(db)
}
pending: 2 new, 2 dirty; entries in the table: 0
commit 1
insert entries (1, -30)
insert entries (2, 30)
update accounts 1 ann 70
update accounts 2 bob 30
commit
commit 2
insert entries (2, -50)
insert entries (1, 50)
update accounts 2 bob -20
rollback: CHECK constraint failed: balance >= 0
accounts: 1 ann 70 | 2 bob 30
entries: 1 -30 | 2 30
commit 3
insert entries (2, -30)
insert entries (1, 30)
update accounts 1 ann 100
delete accounts 2
commit
accounts: 1 ann 100
entries: 1 -30 | 2 30 | 2 -30 | 1 30
- Verdict: idiom. The lists hold pointers in
anyvalues, soslices.Containsand==compare identity, not field values. - The mapper functions use a type switch to choose the code for each kind of object, and
Commitstops at the first error, whichTransactionturns into a rollback.
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
struct Account {
id: u32,
owner: String,
balance: i64,
}
struct Entry {
account_id: u32,
amount: i64,
}
// The unit of work holds shared pointers, so it can compare identity with Rc::ptr_eq.
#[derive(Clone)]
enum Obj {
Account(Rc<RefCell<Account>>),
Entry(Rc<Entry>),
}
impl Obj {
fn same(&self, other: &Obj) -> bool {
match (self, other) {
(Obj::Account(a), Obj::Account(b)) => Rc::ptr_eq(a, b),
(Obj::Entry(a), Obj::Entry(b)) => Rc::ptr_eq(a, b),
_ => false,
}
}
}
// A stand-in for the database, because the standard library has no driver.
#[derive(Clone)]
struct Database {
accounts: BTreeMap<u32, (String, i64)>,
entries: Vec<(u32, i64)>,
}
impl Database {
// Runs the work on a copy of the tables and keeps the copy only when all of it succeeds.
fn transaction(&mut self, work: impl FnOnce(&mut Database) -> Result<(), String>) -> Result<(), String> {
let mut copy = self.clone();
work(&mut copy)?;
*self = copy;
Ok(())
}
}
fn find_account(db: &Database, id: u32) -> Rc<RefCell<Account>> {
let (owner, balance) = db.accounts[&id].clone();
Rc::new(RefCell::new(Account { id, owner, balance }))
}
// The mapper functions write each kind of object.
fn insert(db: &mut Database, obj: &Obj) -> Result<(), String> {
match obj {
Obj::Entry(e) => {
println!(" insert entries ({}, {})", e.account_id, e.amount);
db.entries.push((e.account_id, e.amount));
Ok(())
}
Obj::Account(_) => Err("no insert for accounts".into()),
}
}
fn update(db: &mut Database, obj: &Obj) -> Result<(), String> {
match obj {
Obj::Account(a) => {
let a = a.borrow();
println!(" update accounts {} {} {}", a.id, a.owner, a.balance);
if a.balance < 0 {
return Err("CHECK constraint failed: balance >= 0".into());
}
db.accounts.insert(a.id, (a.owner.clone(), a.balance));
Ok(())
}
Obj::Entry(_) => Err("no update for entries".into()),
}
}
fn delete(db: &mut Database, obj: &Obj) -> Result<(), String> {
match obj {
Obj::Account(a) => {
println!(" delete accounts {}", a.borrow().id);
db.accounts.remove(&a.borrow().id);
Ok(())
}
Obj::Entry(_) => Err("no delete for entries".into()),
}
}
#[derive(Default)]
struct UnitOfWork {
new: Vec<Obj>,
dirty: Vec<Obj>,
removed: Vec<Obj>,
}
impl UnitOfWork {
fn register_new(&mut self, obj: Obj) {
self.new.push(obj);
}
fn register_dirty(&mut self, obj: Obj) {
if !self.new.iter().chain(&self.dirty).any(|o| o.same(&obj)) {
self.dirty.push(obj);
}
}
fn register_removed(&mut self, obj: Obj) {
if self.new.iter().any(|o| o.same(&obj)) {
self.new.retain(|o| !o.same(&obj)); // never written, nothing to delete
return;
}
self.dirty.retain(|o| !o.same(&obj)); // no update before the delete
self.removed.push(obj);
}
fn commit(self, db: &mut Database) {
let result = db.transaction(|tx| {
self.new.iter().try_for_each(|o| insert(tx, o))?;
self.dirty.iter().try_for_each(|o| update(tx, o))?;
self.removed.iter().try_for_each(|o| delete(tx, o))
});
match result {
Ok(()) => println!(" commit"),
Err(e) => println!(" rollback: {e}"),
}
}
}
fn transfer(uow: &mut UnitOfWork, source: &Rc<RefCell<Account>>, target: &Rc<RefCell<Account>>, amount: i64) {
source.borrow_mut().balance -= amount;
target.borrow_mut().balance += amount;
uow.register_dirty(Obj::Account(source.clone()));
uow.register_dirty(Obj::Account(target.clone()));
uow.register_new(Obj::Entry(Rc::new(Entry { account_id: source.borrow().id, amount: -amount })));
uow.register_new(Obj::Entry(Rc::new(Entry { account_id: target.borrow().id, amount })));
}
fn show(db: &Database) {
let accounts: Vec<String> = db.accounts.iter().map(|(id, (o, b))| format!("{id} {o} {b}")).collect();
let entries: Vec<String> = db.entries.iter().map(|(a, m)| format!("{a} {m}")).collect();
println!("accounts: {}", accounts.join(" | "));
println!("entries: {}", entries.join(" | "));
}
fn main() {
let mut db = Database {
accounts: BTreeMap::from([(1, ("ann".to_string(), 100)), (2, ("bob".to_string(), 0))]),
entries: Vec::new(),
};
let mut uow = UnitOfWork::default();
transfer(&mut uow, &find_account(&db, 1), &find_account(&db, 2), 30);
println!("pending: {} new, {} dirty; entries in the table: {}", uow.new.len(), uow.dirty.len(), db.entries.len());
println!("commit 1");
uow.commit(&mut db);
let mut uow = UnitOfWork::default();
transfer(&mut uow, &find_account(&db, 2), &find_account(&db, 1), 50); // bob has only 30
println!("commit 2");
uow.commit(&mut db);
show(&db);
let mut uow = UnitOfWork::default();
let (ann, bob) = (find_account(&db, 1), find_account(&db, 2));
transfer(&mut uow, &bob, &ann, 30); // close bob's account: move the money, then remove it
uow.register_removed(Obj::Account(bob.clone()));
println!("commit 3");
uow.commit(&mut db);
show(&db);
}
pending: 2 new, 2 dirty; entries in the table: 0
commit 1
insert entries (1, -30)
insert entries (2, 30)
update accounts 1 ann 70
update accounts 2 bob 30
commit
commit 2
insert entries (2, -50)
insert entries (1, 50)
update accounts 2 bob -20
rollback: CHECK constraint failed: balance >= 0
accounts: 1 ann 70 | 2 bob 30
entries: 1 -30 | 2 30
commit 3
insert entries (2, -30)
insert entries (1, 30)
update accounts 1 ann 100
delete accounts 2
commit
accounts: 1 ann 100
entries: 1 -30 | 2 30 | 2 -30 | 1 30
- Verdict: idiom. The objects are
Rcvalues, andObj::samecompares them withRc::ptr_eq.Accountis in aRefCell, because the business code changes an account that the unit of work also holds. committakesself, so the compiler stops a second commit of the same unit of work.Database::transactionwrites to a copy of the tables and keeps the copy only when every step returnsOk.
Consequences
Benefits.
- One short transaction. The database transaction is open only during the commit, not during the whole business transaction. Doctrine calls this "transactional write-behind": it delays the SQL until the flush, and then writes it "in the most efficient way and a single, short transaction, taking care of maintaining referential integrity."3
- All or nothing. The commit writes all the changes or none of them. Entity Framework Core says that "For most database providers, SaveChanges is transactional."5
- The domain code has no SQL and no bookkeeping. The business code changes objects. The Unit of Work decides which statements to run, and in which order. SQLAlchemy "organizes them in order of dependency", so that, for example, a parent row is inserted before the rows that refer to it.6 Doctrine runs the entity inserts first, then the entity updates, and the entity deletions last.4
- Only changed values are written. Entity Framework Core says that with its change tracking, "Updates are limited to only those values that have actually changed."7
Liabilities.
Queries do not see pending changes. Until the commit, the changes exist only in memory. A query that runs before the commit reads the old rows. The Doctrine documentation warns: "Changes to managed entities that were not flushed yet are not taken into account by queries."3
This code runs but gives a wrong answer on purpose.
import sqlite3
class UnitOfWork:
def __init__(self, db):
self.db, self.new = db, []
def register_new(self, entry):
self.new.append(entry)
def commit(self):
with self.db:
self.db.executemany("INSERT INTO entries (account_id, amount) VALUES (?, ?)", self.new)
self.new = []
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE entries (account_id INTEGER, amount INTEGER)")
uow = UnitOfWork(db)
uow.register_new((1, -30))
# bug: the new entry is still pending, so the query does not count it
count = db.execute("SELECT count(*) FROM entries WHERE account_id = 1").fetchone()[0]
print("entries of account 1 before the commit:", count)
uow.commit()
count = db.execute("SELECT count(*) FROM entries WHERE account_id = 1").fetchone()[0]
print("entries of account 1 after the commit:", count)
entries of account 1 before the commit: 0
entries of account 1 after the commit: 1
The fix is to write the pending changes before such a query, inside the same transaction. SQLAlchemy does this by itself. Its Session flushes "before any individual SQL statement is issued as a result of a Query", and this is "known as autoflush".8 Doctrine leaves it to the program: "Call EntityManager#flush() before running queries when they should take pending changes into account."3
Change detection costs time. A Unit of Work that compares each object with a copy of its old values must visit every object that it holds. Doctrine says: "The larger the size of the UnitOfWork is, the longer this computation takes."9
Concurrent writers. The database transaction is short, so another user can change the same rows between the read and the commit. The Unit of Work must detect this, which is the "resolution of concurrency problems" of the intent.1 A common way is a version column: SQLAlchemy can use one "as a means of testing for stale data when a row is being UPDATEd with new information."10
When not to use it
When each operation is one statement. A script or a request that changes one row and returns gains nothing from a list of pending changes. An Active Record that saves itself at once is less code.
For bulk changes. A Unit of Work loads each object, changes it in memory and writes it back. An UPDATE ... WHERE statement that changes a million rows in the database is much faster than a million tracked objects.
For reads only. A report that only reads needs no change tracking. Entity Framework Core says: "If the entities retrieved from the database don't need to be updated, then a no-tracking query should be used."11
For a long time. A Unit of Work is for one business transaction. Entity Framework Core says that a "DbContext is designed to represent a short-lived unit-of-work", and that disposing the DbContext is the normal way to stop tracking entities.7 A long-lived one holds stale objects and grows without limit.
Variants and related patterns
How the Unit of Work learns about changes. In the code above, the business code registers each change. ORMs find the changes themselves, in two ways:
- Instrumented attributes. SQLAlchemy objects are instrumented "such that whenever an attribute or a collection is modified in the Python program, a change event is generated which is recorded by the Session."8
- Snapshots. Doctrine keeps a copy of the properties of each loaded object. At the flush, it "will iterate over the Identity Map and for each object compares the original property and association values with the values that are currently set on the object."9 Entity Framework Core "automatically tracks the state of queried entities and then detects any changes made to these entities when SaveChanges is called."7
Entity states. Instead of three lists, a Unit of Work can keep a state for each object. Entity Framework Core uses the states Detached, Added, Unchanged, Modified and Deleted.7
Identity Map. The Unit of Work usually holds an Identity Map, so that each row has one object in memory and each change is registered once. SQLAlchemy keeps its objects "inside a structure called the identity map".8 See Identity Map.
Data Mapper and Repository. The Unit of Work calls the mappers to write the objects, and a repository adds objects to it. See Data Mapper and Repository pattern.
Active Record. An Active Record object writes itself when the program calls its save method, so there is no separate Unit of Work. See Active Record.
Known uses
- SQLAlchemy: "SQLAlchemy's Session implements the unit of work pattern".10 The flush builds a UOWTransaction in unitofwork.py at 2.0.57. The module docstring says that it "assembles flush tasks based on mappers and their properties, organizes them in order of dependency, and executes."6
- Doctrine ORM, for PHP: "A Unit of Work is similar to an object-level transaction." It starts when an EntityManager is created, and
EntityManager#flush()commits it.3 In UnitOfWork.php at 3.8.0,commitbegins a transaction, runs the inserts, the updates and the deletions, and rolls back if a step fails.4 - Entity Framework Core, for .NET: "Each DbContext instance tracks changes made to entities. These tracked entities in turn drive the changes to the database when SaveChanges is called."7
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Unit of Work, pattern summary; the book's Chapter 11
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 11, Object-Relational Behavioral Patterns, Unit of Work
- Doctrine ORM 3.7 documentation, Working with Objects, introduction; Persisting entities; Entity State and the Identity Map
- Doctrine ORM 3.8.0 source, src/UnitOfWork.php, UnitOfWork::commit, lines 380 to 513
- Entity Framework Core documentation, Basic SaveChanges, Multiple operations in a single SaveChanges
- SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/unitofwork.py, module docstring and class UOWTransaction, lines 156 to 486
- Entity Framework Core documentation, Change Tracking in EF Core, Entity tracking; Entity states; Tracking from queries
- SQLAlchemy 2.0 documentation, Session Basics, What does the Session do; Flushing
- Doctrine ORM 3.7 documentation, Doctrine Internals explained, How Doctrine Detects Changes; Query Internals
- SQLAlchemy 2.0 documentation, Glossary, unit of work; version id column
- Entity Framework Core documentation, Tracking vs. No-Tracking Queries, No-tracking queries
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 5HCJ26 Edit this page History Report an error Markdown