Data Persistence in Design: Repositories, Mapping & Boundaries
"Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." — Rob Mee and Edward Hieatt, Repository, Patterns of Enterprise Application Architecture catalog, martinfowler.com
Summary: Persistence is a design problem before it is a database problem: decide which objects know about storage, who owns a transaction, how much of the object graph you load, and which service may touch which table. The tools (Eloquent, GORM, sqlc, Doctrine) only implement those decisions. Focus: Persistence ignorance, the object-relational impedance mismatch, Active Record vs Data Mapper vs Table and Row Data Gateway, Repository and aggregates, Specification and Query Object, Unit of Work, Identity Map, lazy vs eager loading, DTOs and read models, value-object and JSON mapping, optimistic locking, soft deletes, testing, and persistence boundaries from monolith to microservices, in Go and Laravel. Learning goal: Given a feature, choose where the SQL lives, what the transaction boundary is, whether a repository earns its keep, and how the same Order aggregate looks as an Eloquent model, as a plain object behind a repository, and as a row in another service's database.
This is the design view of persistence. It does not teach engines, schema design, migrations or ORM performance traps; those belong to the Databases path and are linked where they matter: ORM Pitfalls (N+1, lazy loading, bulk operations), Schema Design (normal forms, keys, JSONB), Zero-Downtime Schema Migrations, ACID & Transactions, Isolation Levels, Optimistic vs Pessimistic Locking and Connection Pooling. Neighbouring design chapters: Dependency Inversion explains why the repository interface lives with the domain, Single Responsibility explains why a god model is a design smell, Designing for Concurrency and Distribution of Components cover what happens when persistence crosses threads and networks. The tactical DDD details are on Repositories, Aggregates & Factories, Entities & Value Objects and Anemic vs Rich Models; service-level data ownership is on Data Ownership in Microservices.
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in a few tables | Everything in one minute |
| Why persistence needs design at all | Why it exists |
| Fowler, Evans, the ORM debate | Where it comes from |
| Domain objects that know nothing about storage | Persistence ignorance |
| Why objects and tables do not fit | Impedance mismatch |
| Eloquent, Rails-style models | Active Record |
| Doctrine, hand-written mappers, sqlc adapters | Data Mapper, Gateways |
| A collection-like interface for aggregates | Repository, Aggregate boundary |
| Finder methods, Specification, Query Object | Querying through a repository |
| "Do I wrap Eloquent in a repository?" | Repository over Eloquent |
| Who opens and closes the transaction | Unit of Work |
| Same row, one object; cache in front | Identity Map and caching |
| Load now or load later | Lazy vs eager loading |
| Screens and reports without aggregates | DTOs and read models |
| Money, enums, addresses, JSON columns | Mapping value objects |
| Lost updates in the object layer | Optimistic locking |
deleted_at, who-changed-what | Soft deletes and auditing |
| Fakes, real databases, rollback tests | Testing persistence |
| How Eloquent, GORM, sqlc, ent, Doctrine compare | Per-language and per-framework view |
| Dirty checking, emitted SQL, knobs | Mechanics |
Code: Order in Go and Laravel | Go, Laravel |
| Classic problems with fixes | Solving the classic problems |
| Which pattern for which situation | Choosing |
| Monolith to microservices, strangler, data sync | In architecture |
| Run the tests and break things | Lab |
| Wrong beliefs, cheat sheet, questions, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concepts section.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Persistence ignorance | Domain objects do not know how or where they are stored | Order::place() has no SQL and no save() | Rules cannot be tested without a database |
| Impedance mismatch | Objects and tables model data differently | An Order holds a list of lines; a table holds one flat row per line | Mapping code grows and leaks into the domain |
| Active Record | One object wraps one row and saves itself | $order->save() in Eloquent | Rules, SQL and framework in one class |
| Data Mapper | A separate layer moves data between objects and tables | Doctrine EntityManager, a hand-written mapper | More code up front, more classes |
| Table / Row Data Gateway | One object holds the SQL of a table, or of a row | OrderTable::find($id) | Duplicated SQL everywhere |
| Repository | A collection-like facade over storage for one aggregate | orders.Get(ctx, id) | Query code scattered across the app |
| Aggregate | A cluster of objects saved and locked as one unit | Order + its OrderLine rows | Half-saved invariants, huge locks |
| Specification / Query Object | A reusable statement of "which objects" | OverdueOrders | Finder-method explosion |
| Unit of Work | Tracks changes and commits them together | One DB::transaction per use case | Partial writes, chatty commits |
| Identity Map | One row, one object, per business transaction | Two find(7) calls return the same instance | Two copies edited, one silently lost |
| Lazy / eager loading | Load related data on first use, or up front | $order->lines vs with('lines') | N+1 queries or giant joins |
| DTO / read model | A data-only shape for one screen or response | OrderSummary | Aggregates loaded to show a list |
| Optimistic lock | A version number detects concurrent edits | UPDATE ... WHERE version = ? | Lost updates, no error |
| Soft delete | Mark a row deleted instead of removing it | deleted_at | Ghost rows leak into queries |
| Database per service | Each service owns its tables, nobody else reads them | orders DB vs billing DB | A shared schema nobody can change |
The four ways to put an object next to a table (Fowler's catalog, details in the concepts):
| Pattern | Who knows SQL | Where business rules live | Typical tools | Best when |
|---|---|---|---|---|
| Active Record | The domain object itself | Same class as the SQL | Eloquent, Rails Active Record | Rules are simple, tables and objects look alike |
| Data Mapper | A separate mapper | A pure domain class | Doctrine, Hibernate, hand-written mappers | Rich domain, schema and model differ |
| Table Data Gateway | One gateway per table | Elsewhere (transaction scripts) | OrderTable classes, Queries struct from sqlc | Mostly queries, few rules |
| Row Data Gateway | One gateway object per row | Elsewhere | Generated row classes | Rows exposed as typed objects without rules |
Where each idea lives in your tools.
| Level | Go | Laravel |
|---|---|---|
| Row mapping | rows.Scan, sqlc structs, GORM models | Eloquent models, query builder stdClass rows |
| Repository | Interface in the domain package, adapter next to the driver | Interface in the domain namespace, Eloquent adapter in Infrastructure |
| Unit of Work | db.BeginTx plus a closure; gorm.DB.Transaction | DB::transaction(fn) |
| Identity Map | Not built in; per-request map if you want one | Not built in (Doctrine has one; Eloquent does not) |
| Lazy loading | Rare; you call Preload or a second query | Default for relations; Model::preventLazyLoading() |
| Value mapping | sql.Scanner and driver.Valuer | Attribute casts, CastsAttributes, enum casts |
| Soft delete | GORM gorm.DeletedAt; hand-written deleted_at IS NULL | SoftDeletes trait |
| Optimistic lock | WHERE version = $n plus RowsAffected | where('version', $n)->update(...) returns affected rows |
Why it exists
A business object lives in memory, is connected through references and carries rules. Storage lives on disk, is connected through keys and carries rows. Something has to translate, and that something has a cost: Fowler's 2012 essay on ORMs says the object/relational mapping problem "is hard" because you are "synchronizing between two quite different representations of data", with changes on either side and several people editing at once. Design decides where that translation sits and how much of the rest of the code is allowed to see it.
| Persistence woven through the code | Persistence behind a boundary |
|---|---|
| Fewest classes, fastest first feature | More classes, more names, a mapping layer |
| Any layer can query any table | Only repositories and read models touch tables |
| Rules testable only with a database | Rules testable with plain objects |
| Schema change touches controllers, jobs, views | Schema change touches one adapter |
| Transactions open wherever someone remembered | One use case, one transaction |
| Risk: god model, N+1, shared tables | Risk: ceremony, anemic repositories, premature layers |
The left half is Active Record: the use case calls one model that holds fields, rules and save(), and that model runs SQL. The right half is Data Mapper with a repository: the use case asks a repository for a pure Order; only the mapper talks to the database. Neither is "right"; the next sections say when each wins.
The analogy we reuse on this page: a library desk. You can walk the stacks and pull books yourself (Active Record: the object fetches and shelves its own row), or you can ask the librarian for "the book about X" (Repository: you speak in the language of books, not shelf codes). Reference books that never leave the building are an aggregate, borrowed copies tracked by a card are a Unit of Work, and the monthly list of loans the director reads is a read model. A second library that keeps its own catalogue is another service: you ask it, you do not walk into its stacks.
Three common misunderstandings, up front
- "A repository is a wrapper around the ORM." It is a domain-facing collection: methods named in business language that return aggregates. Wrapping every Eloquent method one-to-one adds a layer and removes nothing (see Repository over Eloquent).
- "Active Record is a bad pattern." It is a pattern with a price tag. For a CRUD-shaped feature with few rules it is the cheapest correct choice; the price appears when rules grow and tests need a database.
- "Hiding the database behind an interface means I can swap databases." You can swap an adapter, but transactions, locking, indexes, JSON support and consistency semantics leak. The honest goal is testability and a single place to change, not a free database swap.
Where it comes from
Fowler and co-authors, the PoEAA catalog. Patterns of Enterprise Application Architecture gave the vocabulary this chapter uses. We read the one-paragraph catalog entries on martinfowler.com (all dated 5 March 2003 on the site), not the book chapters, so we quote only those entries. Active Record: "An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data." Data Mapper: "A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." Table Data Gateway: "An object that acts as a gateway to a database table. One instance handles all the rows in the table." Row Data Gateway: "An object that acts as a gateway to a single record in a data source. There is one instance per row." 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." Identity Map: "Ensures that each object gets loaded only once by keeping every loaded object in a map." Lazy Load: "An object that doesn't contain all of the data you need but knows how to get it." Query Object: "An object that represents a database query." Repository (Hieatt and Mee) is the epigraph above, and Optimistic Offline Lock is by David Rice.
"With Data Mapper the in-memory objects needn't know even that there's a database present; they need no SQL interface code, and certainly no knowledge of the database schema." — Martin Fowler, Data Mapper, PoEAA catalog
That sentence is the definition of what practitioners later called persistence ignorance. The phrase itself is a community term; we found no primary definition to quote, so on this page it means exactly what the sentence above says.
Evans, 2003 (summarised in the 2015 DDD Reference). Eric Evans put the aggregate and the repository into one story: aggregates "govern transactions and distribution", and the repository gives access to them.
"For each type of aggregate that needs global access, create a service that can provide the illusion of an in-memory collection of all objects of that aggregate's root type." — Eric Evans, Domain-Driven Design Reference (2015), Repositories
"Provide repositories only for aggregate roots that actually need direct access." — Eric Evans, Domain-Driven Design Reference (2015), Repositories
Evans also names the failure the repository prevents: unconstrained queries "instantiate a few specific objects from the interior of an aggregate, blindsiding the aggregate root", so "entities and value objects become mere data containers."
Evans and Fowler, Specifications. The paper separates "the statement of how to match a candidate" from "the candidate object that it is matched against", and describes three implementations: hard-coded, parameterized and composite specifications.
Fowler, "OrmHate", 2012. The honest defence of ORMs: the mapping problem is hard, "you can't just rely on transactions", and the alternatives are "solve the problem differently (and better), or avoid the problem", both with "significant flaws". It is the best single read on why this chapter exists.
Ambler and the impedance mismatch. Scott Ambler's mapping essay puts it in one line: "Classes implement both behavior and data whereas relational database tables just implement data." The Wikipedia article on the mismatch is a secondary source for the longer lists of differences.
The tools. Laravel's own words are modest: "Eloquent, an object-relational mapper (ORM)" where "each database table has a corresponding 'Model'". Calling that Active Record is our classification from Fowler's definition (the 13.x docs do not use the term). Doctrine documents entities, an EntityManager, a Unit of Work and an Identity Map; calling it a Data Mapper is likewise our classification. Go's culture took a third path: write SQL, generate typed code. sqlc says it "generates fully type-safe idiomatic Go code from SQL".
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, what provides it per tool, and the fix in SQL, Go and Laravel.
Persistence ignorance Must-know
In plain words: the objects that hold your business rules do not import the database, the ORM or the framework. They are plain data plus behaviour.
Common misunderstanding: "Persistence ignorance means the domain model must look nothing like the tables." No. It means the domain type has no storage code; the shapes can still be close. The test is what the class imports, not how it looks.
Definition: a domain object is persistence-ignorant when it can be compiled, constructed and exercised in a test with no database driver, ORM and framework on the import path. Storage concerns (table names, column types, save(), relations as query builders) live in an adapter.
Test an overtime rule (Go) Test an overtime rule (Active Record, Laravel)
1 o, _ := domain.NewOrder("o1", "c1", "USD") $order = Order::factory()->create(); -- INSERT
2 o.AddLine("sku", 2, 500) $order->lines()->create([...]); -- INSERT
3 err := o.Place() $order->place(); -- SELECT count, UPDATE
4 -- no I/O, microseconds -- needs a database, milliseconds, RefreshDatabaseReal scenario: an order that may not be placed without lines; a loan that may not exceed a limit; a booking that must not overlap; a wallet that must never go negative. Each is a rule worth testing a thousand times, which you only do if a test costs microseconds.
| Where | What persistence ignorance costs | What it buys |
|---|---|---|
| Go | A Rehydrate constructor and a repository interface | Domain tests with go test, no driver |
| Laravel | A plain PHP class next to the Eloquent model, plus mapping | Unit tests with PHPUnit\Framework\TestCase, no app boot |
| Both | Mapping code, two representations | One place where storage changes |
// Domain package imports: context, errors, fmt. Nothing else.
o, _ := domain.NewOrder("o-1", "c-1", "USD")
_ = o.AddLine("sku-1", 2, 500)
err := o.Place() // pure rule check// Domain class: no `use Illuminate\...` line at all.
$order = new Order('o-1', 'c-1', 'USD');
$order->addLine('sku-1', 2, 500);
$order->place();Fix / how to use it: decide per bounded context. A reporting module that only reads needs none; a pricing engine with forty rules wants all of it. Pair it with the Dependency Inversion rule: the repository interface is owned by the domain, the adapter depends on it.
The object-relational impedance mismatch Must-know
In plain words: objects and tables are different shapes of the same facts, so every ORM, mapper and hand-written query is a translator, and translators lose or distort things.
Common misunderstanding: "The mismatch is an object-oriented problem, an ORM would not have it in a functional language." Fowler says the opposite: "there is really nothing to do with objects here"; it is an in-memory/relational mapping problem for any in-memory structure.
Definition: a set of structural and semantic differences between in-memory object models and relational schemas. The five that matter in design:
| Difference | Objects | Tables | What goes wrong | Common mapping | Go / Laravel handling |
|---|---|---|---|---|---|
| Identity | Two references are the same object (==), or equal by value | Identity is the primary key; two rows with equal values are two rows | Two copies of one row, divergent edits | Identity Map, key equality, value objects without identity | Go compares ids; Doctrine has an Identity Map; Eloquent returns new instances per query |
| Inheritance | Subclasses, polymorphism | No inheritance | Which table holds which class | Single Table Inheritance, Class Table Inheritance, Concrete Table Inheritance | Neither Eloquent nor GORM maps class inheritance for you (Eloquent's polymorphic relations are about associations, not subclasses); prefer composition and a type column |
| Associations | Reference fields, collections, both directions | Foreign keys, one direction, join tables | Cycles, ownership unclear | Foreign Key Mapping, Association Table Mapping | Eloquent hasMany/belongsToMany; GORM tags; sqlc leaves it to your joins |
| Granularity | Many small classes (Money, Address) | Few wide tables | One object, several columns, or several objects, one column | Embedded Value, Serialized LOB (JSON) | Casts, Scanner/Valuer, JSON columns |
| Navigation | Follow references one hop at a time | Join sets of rows at once | N+1: one query per hop | Eager loading, explicit queries, read models | with(), Preload, joins in sqlc |
| Behaviour | Methods | Data only | getTotalTax() mapped to a column | Keep behaviour in the object, store inputs | Compute in domain, store the facts |
| Types and null | Rich types, enums | Column types, NULL | Silent coercion | Custom types | Valuer and enum casts |
Fowler's catalog names the inheritance mappings: Single Table Inheritance "Represents an inheritance hierarchy of classes as a single table that has columns for all the fields of the various classes"; Class Table Inheritance uses one table per class; Concrete Table Inheritance one per concrete class. Embedded Value and Serialized LOB handle granularity; Foreign Key Mapping and Association Table Mapping handle associations. We read only the catalog summaries.
Navigation: print 3 orders with their lines
1 SELECT * FROM orders WHERE customer_id = 'c1' LIMIT 3; -- 1 query
2 SELECT * FROM order_lines WHERE order_id = 'o1'; -- lazy load, order 1
3 SELECT * FROM order_lines WHERE order_id = 'o2'; -- lazy load, order 2
4 SELECT * FROM order_lines WHERE order_id = 'o3'; -- lazy load, order 3 => 1 + N
5 SELECT * FROM order_lines WHERE order_id IN ('o1','o2','o3'); -- eager load: 2 queries totalReal scenario: a Payment hierarchy (card, bank transfer, wallet) stored in one table with a type column and eleven nullable columns; an Address object spread over four columns; a bidirectional Customer <-> Order reference that makes JSON serialisation recurse forever.
What provides it: no tool removes the mismatch; they choose where it hurts. Doctrine and Hibernate-style mappers hide most of it and make you learn their rules; Eloquent hides the simple cases and exposes the rest through relations and casts; sqlc exposes everything and generates the boring half.
Fix / how to use it:
-- Single Table Inheritance for payments: one table, a discriminator, nullable columns.
CREATE TABLE payments (
id bigint PRIMARY KEY,
order_id text NOT NULL,
type text NOT NULL CHECK (type IN ('card', 'bank', 'wallet')),
card_last4 char(4), -- only for type = 'card'
iban text, -- only for type = 'bank'
wallet_id text, -- only for type = 'wallet'
amount_cents bigint NOT NULL
);// Go: the domain keeps one interface; the adapter switches on the discriminator.
type Payment interface{ Amount() domain.Money }
func fromRow(r paymentRow) (Payment, error) {
switch r.Type {
case "card":
return CardPayment{Last4: r.CardLast4.String, Cents: r.AmountCents}, nil
case "bank":
return BankPayment{IBAN: r.IBAN.String, Cents: r.AmountCents}, nil
}
return nil, fmt.Errorf("unknown payment type %q", r.Type)
}// Laravel: composition beats Eloquent inheritance. The type column picks the strategy object.
$payment = match ($record->type) {
'card' => new CardPayment($record->card_last4, $record->amount_cents),
'bank' => new BankPayment($record->iban, $record->amount_cents),
default => throw new \UnexpectedValueException("Unknown payment type {$record->type}"),
};The schema-design side (normal forms, keys, JSONB) is in Schema Design.
Active Record Must-know
In plain words: one object is one row. It has the columns as fields, it knows its table, and it calls save() on itself. Eloquent is the framework most PHP developers know it from.
Common misunderstanding: "Active Record means the model is anemic or it must be fat." Neither is required. The pattern says the object carries data access and may add domain logic (Fowler's words). The failure mode is not the pattern but unlimited growth of one class.
Definition: Fowler: "An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data." Its forces: fast to write, easy to read, domain and schema evolve together; it works best when the object model is close to the schema.
Eloquent: place an order
1 $order = Order::findOrFail($id); -- SELECT * FROM orders WHERE id = ? AND deleted_at IS NULL
2 $order->status = OrderStatus::Placed; -- in memory, marks `status` dirty
3 $order->save(); -- UPDATE orders SET status = ?, updated_at = ? WHERE id = ?
4 -- no version check, no transaction unless you opened oneReal scenario: an admin panel for categories; a blog; a settings table; a CRUD API where the table and the resource are the same thing. Also the first six months of almost every Laravel product.
| Strength | Cost |
|---|---|
| Least code to a working feature | The class has three reasons to change (rules, SQL, framework) |
| Relations, casts, scopes, events included | Rules testable only with a database, or with heavy mocking |
| Great tooling and a huge community | The table shape leaks into the API shape |
| Obvious where to look | Anything can call save(), in any layer, in any transaction |
What provides it: Eloquent (Laravel 13), Rails Active Record, GORM when you use models as domain objects. Laravel's introduction: "each database table has a corresponding 'Model' that is used to interact with that table".
Fix / how to use it: keep it for the CRUD parts, and when rules grow, extract them (Action classes, domain services, or a plain domain class). Cross-reference: Single Responsibility and Code Smells & Refactoring (large class, divergent change). The full AR example is in the Laravel section.
Data Mapper Must-know
In plain words: a go-between that knows both the object and the table, so neither knows the other.
Common misunderstanding: "Data Mapper is just a heavier ORM." A Data Mapper is a role, not a product: a hand-written OrderMapper, a Doctrine EntityManager and a sqlc-based adapter all play it. The defining property is that the domain object has no storage code.
Definition: Fowler: "A layer of mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself." It exists because object and relational schemas diverge (collections, inheritance), and "changes in one tend to ripple to the other" when the object knows the schema.
Data Mapper: place an order
1 use case -> orders.Get(ctx, "o-1") -- repository
2 mapper -> SELECT ... FROM orders; SELECT ... FROM order_lines -- two queries
3 mapper -> domain.Rehydrate(...) -- builds the pure aggregate
4 domain -> o.Place() -- rules, no I/O
5 use case -> orders.Save(ctx, o)
6 mapper -> UPDATE orders ... WHERE version = $n; DELETE/INSERT lines -- one transactionReal scenario: an insurance policy with forty rules and a legacy schema nobody dares change; a domain where the same table backs two aggregates; a service whose domain model must outlive three database migrations.
What provides it: Doctrine ORM (Unit of Work, Identity Map, entities as plain classes, per its docs), Hibernate in the Java world, hand-written mappers, and in Go any repository adapter over database/sql, sqlc or GORM models used only inside the adapter.
| Strength | Cost |
|---|---|
| Domain tests need no database | Two models to keep in sync (domain and persistence) |
| Schema can change without touching rules | More files, more names |
| Loading rules for the aggregate are in one place | Easy to over-build for CRUD |
Fix / how to use it: see the Go adapters in after/sqlcrepo and after/gormrepo and the Laravel adapter EloquentOrderRepository in the Go and Laravel sections. Note that the adapter uses Eloquent models internally: Data Mapper and Eloquent can coexist, with Eloquent demoted to a persistence model.
Table Data Gateway and Row Data Gateway Important
In plain words: instead of an object per row that does everything, keep the SQL in one place per table (Table Data Gateway), or give each row a typed handle with no rules (Row Data Gateway).
Common misunderstanding: "A gateway is just a repository." A repository speaks about aggregates in domain language and may span several tables; a gateway speaks about one table or row in table language.
Definition: Fowler: Table Data Gateway "holds all the SQL for accessing a single table or view: selects, inserts, updates, and deletes. Other code calls its methods for all interaction with the database." Row Data Gateway gives "objects that look exactly like the record in your record structure but can be accessed with the regular mechanisms of your programming language."
Table Data Gateway
1 orders := OrderTable{db}
2 row, err := orders.Find(ctx, "o-1") -- SELECT ... FROM orders WHERE id = $1
3 err = orders.UpdateStatus(ctx, "o-1", "placed") -- UPDATE orders SET status = $2 ...
4 -- rules live in a service that calls these methodsReal scenario: a reporting job; a transaction script ("import 10,000 rows"); a service where almost all logic is SQL. In Go, the generated sqlc Queries type is a Table Data Gateway for the whole schema (strictly: one gateway object with typed methods and row structs).
| Pattern | Unit | Holds rules? | Go example | Laravel example |
|---|---|---|---|---|
| Table Data Gateway | One object per table | No | sqlc Queries | A class around DB::table('orders') |
| Row Data Gateway | One object per row | No | sqlc row structs | stdClass rows from the query builder |
| Active Record | One object per row | Yes | GORM model with methods | Eloquent model |
Fix / how to use it: use them when the logic is mostly set-based SQL; put rules in a service. Do not call a bag of find/save methods a repository; see Repository.
Repository Must-know
In plain words: a repository is the "bookshelf" for one kind of business object: you add, get and remove aggregates from it as if it were an in-memory collection, and it deals with storage behind the scenes.
Common misunderstanding: "One repository per table" or "a repository must have findAll, find, save, delete for everything." Evans says repositories exist for aggregate roots that need direct access, and its methods select "based on criteria meaningful to domain experts".
Definition: the Hieatt and Mee entry: "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." A repository (1) is defined in domain terms, (2) returns whole aggregates, (3) hides the query technology, (4) is the only door to the aggregate's tables.
Repository, in use
1 orders := repo (interface domain.Repository)
2 o, err := orders.Get(ctx, id) -- ErrNotFound if missing
3 o.Place() -- domain rule
4 err = orders.Save(ctx, o) -- ErrConflict if version changed
5 -- the use case never sees SQL, a table, an ORM type or a transaction handleReal scenario: OrderRepository, AccountRepository, BookingRepository: each loads and stores one aggregate and knows its invariants and its locking strategy.
| Repository design choice | Good | Bad |
|---|---|---|
| Interface placement | In the domain package (DIP) | In the infrastructure package next to the ORM |
| Return type | Aggregate (*domain.Order) | ORM model, query builder, *sql.Rows |
| Method names | ByCustomerOverdue, NextToShip | FindBy(field, value) |
| Granularity | One per aggregate root | One per table |
| Errors | Domain errors (ErrNotFound, ErrConflict) | Raw driver errors |
| Collection feel | Add, Get, Save | Insert, Update, Select |
What provides it: nothing in Eloquent or GORM; it is a design you write. The Go and PHP interfaces in the snippets are the reference.
Fix / how to use it:
// Go: the port, defined in the domain package.
type Repository interface {
Add(ctx context.Context, o *Order) error
Get(ctx context.Context, id OrderID) (*Order, error)
Save(ctx context.Context, o *Order) error
}// Laravel: the port, in the domain namespace.
interface OrderRepository
{
public function add(Order $order): void;
public function get(string $id): Order; // throws OrderNotFound
public function save(Order $order): void; // throws ConcurrencyConflict
}See also Repositories for the DDD tactical rules.
Aggregate boundary: one repository per aggregate Must-know
In plain words: things that must always be consistent together (an order and its lines) are loaded, changed and saved together; anything else is referenced by id.
Common misunderstanding: "An aggregate is a collection class or a table with its children." Fowler: "DDD Aggregates are sometimes confused with collection classes... DDD aggregates are domain concepts (order, clinic visit, playlist)".
Definition: Fowler: "A DDD aggregate is a cluster of domain objects that can be treated as a single unit... Aggregates are the basic element of transfer of data storage - you request to load or save whole aggregates. Transactions should not cross aggregate boundaries." Evans: "Within an aggregate boundary, apply consistency rules synchronously. Across boundaries, handle updates asynchronously."
Why the boundary matters
1 T1: load Order o-1 (root + 3 lines), AddLine, Save -- version 4 -> 5
2 T2: load Order o-1, Place, Save -- expected version 4, finds 5: ErrConflict
3 T3: load Customer c-1 to change the address -- different aggregate, no conflict with T1/T2
4 Rule: o-1's lines never change except through Order, so one version number guards the whole clusterReal scenario: a shopping cart with items, a playlist with tracks, a booking with guests. Counter-scenario: loading a Customer with all 20,000 orders as part of one aggregate: the aggregate is too large; reference orders by customer_id instead.
| Question | Inside the aggregate | Across aggregates |
|---|---|---|
| Consistency | Immediate, one transaction | Eventual (events, outbox) |
| References | Objects | Ids |
| Locking | One version column on the root | One per aggregate |
| Repository | The root's | Separate |
| Typical bug | Aggregate too big: contention, slow loads | Aggregate too small: broken invariants |
What provides it: design discipline. Neither Eloquent nor GORM enforces it; relations make it easy to navigate across boundaries by accident.
Fix / how to use it: the Order aggregate in the snippets keeps Lines() as a copy and exposes only AddLine; the repository rewrites lines inside the same transaction as the root update. More: Aggregates & Factories.
Querying through a repository: finder methods, Specification, Query Object Important
In plain words: you will want "all overdue orders for this customer, newest first, page 3". Either you add a method for each question, or you pass an object that describes the question.
Common misunderstanding: "A Specification replaces SQL." It describes which objects qualify; something still has to turn it into SQL or evaluate it in memory.
Definition: three techniques.
| Technique | What it is | Source | Good for | Cost |
|---|---|---|---|---|
| Finder methods | One named method per question | Evans: criteria meaningful to domain experts | A handful of stable queries | Method explosion, boolean flag parameters |
| Specification | An object that states whether a candidate matches; can be combined with AND, OR, NOT | Evans and Fowler, Specifications | Reusable business predicates; validation and selection | Two backends (SQL and in-memory) can drift |
| Query Object | An object representing a query, built from class and field names | Fowler: "An object that represents a database query" | Ad-hoc, user-built filters | Interpreter code; a mini ORM |
Evans and Fowler describe the idea as separating "how to match a candidate" from "the candidate object that it is matched against", and give three implementation strategies: Hard Coded, Parameterized and Composite Specification. A Composite Specification "uses an interpreter ... to cut a very agreeable middle path."
Finder-method explosion vs one specification
1 ordersRepo.Overdue(customer) ordersRepo.Matching(Overdue().And(ForCustomer(c)))
2 ordersRepo.OverdueNewestFirst(customer) ordersRepo.Matching(spec, Page(3, 20), Newest())
3 ordersRepo.OverdueByRegion(customer, region) -- one method, composable predicates
4 ordersRepo.OverdueByRegionUnpaid(...) -- 4 methods and growingReal scenario: an admin filter UI with twelve optional filters; a "can this customer buy this?" rule used both to validate and to list eligible customers; a nightly job selecting "orders stale for 30 days".
// A small specification for the SQL adapter: it renders a WHERE fragment and arguments.
type Spec interface{ SQL(argN int) (frag string, args []any) }
type ForCustomer string
func (s ForCustomer) SQL(n int) (string, []any) {
return fmt.Sprintf("customer_id = $%d", n), []any{string(s)}
}
type And []Spec
func (a And) SQL(n int) (string, []any) {
var parts []string
var args []any
for _, s := range a {
f, ar := s.SQL(n + len(args))
parts, args = append(parts, f), append(args, ar...)
}
return "(" + strings.Join(parts, " AND ") + ")", args
}// Laravel: a specification as a scope-like object applied to the persistence model's builder.
interface OrderSpecification
{
public function apply(\Illuminate\Database\Eloquent\Builder $query): void;
}
final class OverdueFor implements OrderSpecification
{
public function __construct(private string $customerId) {}
public function apply(\Illuminate\Database\Eloquent\Builder $query): void
{
$query->where('customer_id', $this->customerId)
->where('status', 'placed')
->where('due_at', '<', now());
}
}Fix / how to use it: start with named finder methods; move to specifications when you see the same predicates combined in several places; never make the specification API a thin re-spelling of the query builder (that is the leaky repository, see Solving the classic problems). Keep in-memory and SQL evaluation tested by the same contract tests (see Testing).
"Repository over Eloquent": the debate Important
In plain words: Eloquent already looks like a repository (Order::where(...)->get()), so should you hide it behind another one?
Common misunderstanding: "Always wrap it" and "Never wrap it" are both slogans. The question is whether the wrapper changes what the rest of the code depends on.
Definition: the debate has a stable core.
| Position | Argument | Strongest when |
|---|---|---|
| Do not wrap | Eloquent is already a data-access layer; a one-to-one wrapper adds code and no value; you lose relations, scopes and with() | CRUD, admin, content, small teams |
| Wrap per aggregate | Domain rules stay testable and persistence-ignorant; one place for locking, mapping and transactions | Rich rules, long-lived product, several bounded contexts |
| Wrap only the awkward parts | Query objects or action classes for the 10 complex queries; models elsewhere | Most real Laravel apps |
When the wrapper pays for itself
1 Rule changes: "orders over 1000 need approval" -> edit Order::place(), no SQL touched
2 Storage changes: split lines into a second database -> edit EloquentOrderRepository only
3 Test: 400 rule tests in 0.2 s with the fake -> no RefreshDatabase
4 Counter-case: a settings table with 3 columns -> the wrapper is pure ceremonyReal scenario (value): pricing, billing, booking, ledgers, anything where a rule bug costs money. Real scenario (ceremony): UserRepository::find, ::all, ::create, ::update, ::delete forwarding to Eloquent, plus an interface and a binding, for a CRUD screen.
| Question to ask | If yes | If no |
|---|---|---|
| Do domain rules exist that deserve fast tests? | Repository + plain domain | Eloquent directly |
| Will the storage shape differ from the object shape? | Mapper in a repository | Eloquent model is the object |
| Is there more than one way to load this thing? | Repository with named methods | Plain scopes |
| Will other modules use this data? | Facade or repository as the public contract | Internal model |
Fix / how to use it: the lab implements both, from the same tests, so you can feel the cost. See also Anemic vs Rich Models.
Unit of Work and transactions as a design boundary Must-know
In plain words: one business action, one transaction: either everything it changed is saved or nothing is. The Unit of Work is the thing that knows what changed and commits it together.
Common misunderstanding: "save() is atomic, so I am safe." Each save() is one statement; a use case that saves two things needs one transaction around both. Fowler's catalog adds that without it you get "lots of very small database calls".
Definition: Fowler: "Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." Two shapes exist:
| Shape | How | Examples |
|---|---|---|
| Tracked Unit of Work | The ORM watches objects, computes changes, flushes at the end | Doctrine EntityManager::flush(); GORM is not tracking (explicit calls) |
| Scoped transaction | You open a transaction, run the use case, commit | DB::transaction(fn), Go BeginTx + closure |
Scoped Unit of Work in the use case
1 uow.Do(ctx, func(ctx, orders) error { -- BEGIN
2 o := orders.Get(ctx, id) -- SELECT (inside the tx)
3 o.Place() -- in memory
4 orders.Save(ctx, o) -- UPDATE ... WHERE version = $n
5 }) -- COMMIT, or ROLLBACK if the closure returned an error
6 -- publish events AFTER commit, or write them to an outbox row in the same transactionReal scenario: place an order and reserve stock; transfer money (two accounts, one transaction, lock order matters); create a user and send a welcome email (the email is not in the transaction: put it after commit or in an outbox).
| Design question | Recommended answer |
|---|---|
| Who opens the transaction? | The use case (application layer), not the repository, not the controller |
| How long does it stay open? | One request's worth; never across user think time or a remote call |
| What goes inside? | Reads and writes of one database; no HTTP calls, no emails |
| How do repositories join it? | They receive the transaction handle (Go: Queries.WithTx; Laravel: ambient DB::transaction) |
| What about two aggregates? | Usually two transactions plus an event; see Saga |
// Go: the use case owns the boundary; the adapter binds repositories to the transaction.
func (u UoW) Do(ctx context.Context, fn func(context.Context, domain.Repository) error) error {
tx, err := u.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
if err := fn(ctx, New(u.Q.WithTx(tx))); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}// Laravel: the use case wraps the work. The repository's own DB::transaction nests inside.
DB::transaction(function () use ($orderId): void {
$order = $this->orders->get($orderId);
$order->place();
$this->orders->save($order);
});The sqlc docs describe the Go mechanism: "In the code generated by sqlc, the WithTx method allows a Queries instance to be associated with a transaction." Isolation, locking and deadlock details are in ACID & Transactions and Isolation Levels. Laravel's DB::transaction also accepts an attempts argument to retry on deadlock.
Identity Map and caching Important
In plain words: if you load row 7 twice in the same operation, you should get the same object, not two copies that can diverge.
Common misunderstanding: "An identity map is a cache." It is a per-business-transaction map for correctness first; any speed-up is a side effect. A cache outlives the transaction and has an invalidation problem; an identity map is thrown away with it.
Definition: Fowler: "Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them." Doctrine's docs describe it: "Doctrine keeps a map of each entity and ids that have been retrieved per PHP request and keeps returning you the same instances." Eloquent and GORM do not do this; each query returns fresh objects.
Without and with an identity map
1 a := repo.Get(7); b := repo.Get(7) -- two objects, same row
2 a.Rename("X"); b.Rename("Y") -- both dirty
3 save(a); save(b) -- last write wins, "X" lost, no error
--- with an identity map ---
4 a := uow.Get(7); b := uow.Get(7) -- a == b (same instance)
5 a.Rename("X"); b.Rename("Y") -- one object, final state "Y", saved onceReal scenario: code paths that load the same order in a controller and again in a listener; a batch job that touches the same customer from several rows.
| Layer | Scope | Invalidation | Where |
|---|---|---|---|
| Identity Map | One unit of work | Dies with it | Doctrine; hand-written per request in Go |
| Request-level memo | One request | Dies with it | A map[OrderID]*Order inside the UoW |
| Application cache | Process or shared | Explicit, hard | Cache::remember, Redis |
| Database cache | Engine | Engine | Buffer pool |
Fix / how to use it: in Laravel, avoid reloading the same model in layers; pass the object down. In Go, keep a small map inside the unit of work if two repositories may load the same aggregate. For caches in front of repositories, cache read models (see DTOs and read models) and invalidate on events; never cache a writable aggregate across requests. Cache design: Storage & Data Scaling.
Lazy vs eager loading as a design decision Must-know
In plain words: when you load an order, do you also load its lines, the customer, the customer's other orders? Lazy loading says "only when someone looks"; eager loading says "now, in one go".
Common misunderstanding: "Lazy loading is a performance feature." Fowler's Lazy Load is to avoid loading "a huge number of related objects" when only a few are needed; the cost is a hidden query on first access, which turns into N+1 in a loop.
Definition: Lazy Load: "An object that doesn't contain all of the data you need but knows how to get it." Fowler lists four varieties: lazy initialization, virtual proxy, value holder and ghost. Eager loading fetches related rows up front.
| Strategy | When it loads | Queries for 50 orders + lines | Risk |
|---|---|---|---|
| Lazy | On first access of each relation | 1 + 50 | N+1, hidden I/O, access after the connection closed |
Eager (with, Preload, ent WithX) | With the parent | 2 | Over-fetching if unused |
| Join | In one statement | 1 | Row multiplication, big result |
| Read model | A purpose-built query | 1 | Another thing to maintain |
Aggregate design rule
1 Aggregate (Order + lines): always loaded whole -- eager by design, small, bounded
2 Reference to another aggregate (Customer): by id only -- never lazy-navigate across the boundary
3 Collections that can grow without bound (events, audit): -- not part of the aggregate; separate queryReal scenario: a list of 200 orders where the template prints $order->customer->name and count($order->lines): 401 queries lazily, 3 eagerly. The full diagnosis and fixes are in ORM Pitfalls.
What provides it: Eloquent loads relations lazily by default; Model::preventLazyLoading() turns accidental lazy loads into exceptions, and Laravel's docs show enabling it outside production (Model::preventLazyLoading(! $this->app->isProduction())). GORM requires Preload; ent uses eager-loading edges (WithPets()-style) and reads the result from Edges. Go with sqlc has no lazy loading: relations are separate queries you write.
Fix / how to use it: in the design, decide per association: inside the aggregate means load eagerly with the root; across aggregates means reference by id and use a read model for display.
DTOs and read models (CQRS-light) Must-know
In plain words: a screen wants "id, status, total, number of lines" for fifty orders. Do not load fifty aggregates; run one query that returns exactly those fields.
Common misunderstanding: "CQRS means two databases, events and eventual consistency." That is one heavy form. Fowler warns that "for most systems CQRS adds risky complexity". The light form is just a separate query path returning DTOs from the same database.
Definition: a Data Transfer Object is "an object that carries data between processes in order to reduce the number of method calls" (Fowler's catalog), usually built by an assembler. Here it also means any data-only shape returned to a screen or API. A read model is a query-side model: its shape is the screen's, not the aggregate's. CQRS: "you can use a different model to update information than the model you use to read information."
Command side vs query side
1 POST /orders/o-1/place -> use case -> repository.Get -> Order.Place -> repository.Save -- aggregate, rules, version
2 GET /customers/c-1/orders -> OrderSummaryQuery.forCustomer -> one GROUP BY query -- DTOs, no rules
3 Both read the same tables; the query side never constructs an OrderReal scenario: list screens, dashboards, exports, search results, API collection endpoints; anything the user reads more often than writes.
| Level | What you do | Consistency | Cost |
|---|---|---|---|
| Light | DTO query on the same tables | Immediate | Almost none |
| Medium | A SQL view or materialized view | As fresh as the refresh | Refresh jobs |
| Heavy | Separate store fed by events (see CQRS & event sourcing) | Eventual | Projectors, rebuilds, monitoring |
-- The read model query used by sqlc and the Laravel query builder.
SELECT o.id, o.status, o.currency,
COALESCE(SUM(l.qty * l.unit_cents), 0)::bigint AS total_cents,
COUNT(l.position)::int AS line_count
FROM orders o
LEFT JOIN order_lines l ON l.order_id = o.id
WHERE o.customer_id = $1 AND o.deleted_at IS NULL
GROUP BY o.id
ORDER BY o.created_at DESC
LIMIT $2;Fix / how to use it: readmodel.Reader in Go and OrderSummaryQuery in Laravel are the pattern: separate port, plain data, no behaviour. Pagination of such lists: Pagination.
Mapping value objects, enums and JSON columns Important
In plain words: Money, Address and Status are small, meaningful types. The database stores numbers, strings and JSON. You need a rule for crossing over, and the type should refuse bad values on both sides.
Common misunderstanding: "Store money as a float and format later", or "a JSON column is a free pass to skip modelling". Money is an integer amount plus a currency; a JSON column is a deliberate choice for data you do not query field by field.
Definition: the mapping strategies (Fowler's names: Embedded Value, Serialized LOB):
| Value | Column strategy | Go | Laravel |
|---|---|---|---|
Money | Two columns (total_cents, currency) | Fields on the adapter struct; domain Money built in the mapper | CastsAttributes over two columns (MoneyCast) |
Address | One JSONB column, or several columns | Type implementing driver.Valuer and sql.Scanner | AsArrayObject/custom cast, or an Address cast |
Status enum | text + CHECK, or a native enum type | Type with Scan that rejects unknown values | Backed enum cast (OrderStatus::class) |
| Tags / settings | jsonb | []byte or json.RawMessage, or a typed Valuer | AsArrayObject, AsCollection, array cast |
| Id | text/uuid/bigint | Named type OrderID | Typed id in domain, string in the model |
Crossing the boundary
1 write: domain.Address{...} --Value()--> []byte JSON --driver--> jsonb column
2 read: jsonb column --driver--> []byte or string --Scan()--> domain.Address
3 bad data: status = 'shipped' in the table --Scan()--> error "unknown value", not a silent defaultReal scenario: a currency mismatch caught at the type; a status column edited by hand to a value the code does not know; a JSON blob whose shape changed between releases.
// Go: Valuer writes, Scanner reads. Unknown enum values fail loudly on read.
func (a Address) Value() (driver.Value, error) { return json.Marshal(a) }
func (a *Address) Scan(src any) error {
switch v := src.(type) {
case []byte:
return json.Unmarshal(v, a)
case string:
return json.Unmarshal([]byte(v), a)
case nil:
*a = Address{}
return nil
default:
return fmt.Errorf("address: cannot scan %T", src)
}
}// Laravel: casts() declares the mapping; CastsAttributes handles multi-column values.
protected function casts(): array
{
return [
'status' => OrderStatus::class, // backed enum
'options' => AsArrayObject::class, // JSON column as an object
'total' => MoneyCast::class, // two columns -> Money
];
}The Valuer and Scanner interfaces are documented in database/sql/driver and database/sql; Laravel's casts in Eloquent: Mutators & Casting. sqlc can also override Go types for columns (its overrides how-to). GORM documents the same Scanner/Valuer pair for custom types. JSON column design: Schema Design.
Optimistic locking as a design concern Must-know
In plain words: two people open the same order; both click save. Without a check the second silently erases the first. A version number makes the second save fail instead.
Common misunderstanding: "My ORM does this for me." Doctrine and many ORMs offer a version field; Eloquent has no built-in optimistic locking and GORM core has none either, so you write the WHERE version = ? yourself.
Definition: Rice's Optimistic Offline Lock "prevents conflicts between concurrent business transactions by detecting a conflict and rolling back the transaction." A business transaction often spans several requests, so the database's transaction alone cannot protect it. The design decision is who owns the version: the aggregate root. See Optimistic vs Pessimistic Locking for the database mechanics.
Two editors, one aggregate (version column)
1 A: Get(o-1) -> version 3 B: Get(o-1) -> version 3
2 A: Place(); Save: UPDATE ... SET version = 4 WHERE id = 'o-1' AND version = 3 -> 1 row
3 B: Place(); Save: UPDATE ... WHERE version = 3 -> 0 rows
4 B: ErrConflict -> reload and retry, or tell the userReal scenario: two admins editing a product; a double-clicked "pay" button; a worker and a user both updating a booking. Not for hot counters: use an atomic UPDATE x = x + 1 instead.
| Technique | Detects | Cost | Use when |
|---|---|---|---|
Version column + WHERE version = ? | Any concurrent write to the aggregate | A retry path | Edits spanning requests, low conflict |
updated_at compare | Concurrent write (coarse, clock-resolution) | Fragile | Quick CRUD forms |
SELECT ... FOR UPDATE | Prevents it by waiting | Held locks, deadlocks | Short, high-conflict transactions |
Atomic update (balance = balance - ?) | Nothing needed | None | Counters, stock |
UPDATE orders
SET status = $2, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL;
-- rows affected = 0 => someone else changed it (or it is gone): return a conflict, never "ok"n, err := q.UpdateOrderVersioned(ctx, db.UpdateOrderVersionedParams{ID: id, Status: s, Version: v})
if err == nil && n == 0 {
err = domain.ErrConflict // the repository translates "0 rows" into a domain error
}$affected = OrderRecord::query()
->where('id', $order->id)
->where('version', $order->version())
->update(['status' => $order->status()->value, 'version' => $order->version() + 1]);
if ($affected === 0) {
throw ConcurrencyConflict::forOrder($order->id);
}Fix / how to use it: the repository contract test in the lab includes "second writer gets a conflict". Decide the user-facing behaviour (reload and merge, or ask again) in the use case, not the repository.
Soft deletes and auditing as cross-cutting concerns Important
In plain words: "delete" often means "hide, but keep for the books"; and someone will ask who changed what and when.
Common misunderstanding: "Soft delete is just a boolean on every table and the problem is solved." Every query, every unique index, every foreign key and every report now has to know about it, and the data never leaves (privacy rules may require real deletion).
Definition: both are cross-cutting: they apply to many aggregates and should not be repeated in each use case.
| Concern | Typical mechanism | Pitfalls |
|---|---|---|
| Soft delete | deleted_at timestamp | Unique constraints (email reused), joins that forget the filter, cascades |
| Auditing: who/when | created_by, updated_by, timestamps | Background jobs have no user |
| Auditing: what changed | Append-only history table, event log, or database trigger | Volume, PII retention |
| Event log as truth | Event sourcing | A different architecture; see event sourcing |
Soft delete in practice
1 DELETE /orders/o-1 -> UPDATE orders SET deleted_at = now() WHERE id = 'o-1'
2 list orders -> WHERE deleted_at IS NULL (global scope in Eloquent, GORM adds it for gorm.DeletedAt)
3 create order with same key -> unique index must be partial: UNIQUE (code) WHERE deleted_at IS NULL
4 GDPR erasure -> real DELETE or anonymise; soft delete is not erasureReal scenario: an order cancelled but kept for accounting; a user "deleted" but their invoices must remain; an admin asks "who changed this price on Friday?".
What provides it: Laravel's SoftDeletes trait with trashed(), withTrashed(), restore() and forceDelete(); GORM: "If your model includes a gorm.DeletedAt field ... When calling Delete, the record WON'T be removed from the database"; sqlc and database/sql give you nothing: write deleted_at IS NULL in every query (as the snippet queries do). Auditing in Eloquent can use model events and observers (ShouldHandleEventsAfterCommit exists for after-commit handling), but it misses bulk update() calls that bypass models.
CREATE UNIQUE INDEX orders_code_live ON orders (code) WHERE deleted_at IS NULL; -- PostgreSQL partial unique index
CREATE TABLE order_audit (
id bigserial PRIMARY KEY,
order_id text NOT NULL,
actor text NOT NULL,
action text NOT NULL,
changed_at timestamptz NOT NULL DEFAULT now(),
diff jsonb NOT NULL
);Fix / how to use it: make soft delete a property of the repository (every read method filters it), write audit rows inside the same transaction as the change, and decide retention up front. Security angle: Security by Design and Database Security.
Testing persistence: fakes, real databases, transactional tests Must-know
In plain words: test the rules with plain objects, test the adapter against the real database, and prove the fake behaves like the real thing with the same tests.
Common misunderstanding: "Use an in-memory SQLite database in tests instead of the real one." It is a different engine: different types, locking, JSON, constraints and SQL dialect. It tests your assumptions about SQLite.
Definition: a pyramid for persistence.
| Test | Subject | Speed | Catches |
|---|---|---|---|
| Domain unit test | Order rules, no I/O | microseconds | Rule bugs |
| Use case test with an in-memory fake | PlaceOrder with memrepo | microseconds | Orchestration bugs, rollback behaviour |
| Repository contract test | Fake and real adapter run the same suite | milliseconds | Fake drift, mapping bugs, version check |
| Adapter test on the real engine | SQL, constraints, indexes, JSON | milliseconds each, seconds per suite | Wrong SQL, wrong types |
| End-to-end through HTTP | Whole slice | slower | Wiring |
The contract suite
1 contract.Run(t, newRepo) -- one list of behaviours
2 memrepo.New() passes -> the fake mirrors the contract
3 sqlcrepo.New(db.New(tx)) passes -> the SQL adapter satisfies it (inside a rolled-back transaction)
4 gormrepo.New(gormDB) passes -> same port, different tool
5 Change a rule in the contract, all three fail togetherReal scenario: a fake that silently accepted two writers while production returned a conflict; a migration that added a NOT NULL column and broke only the real-database tests; a suite that took eleven minutes because every test truncated tables.
| Isolation technique | How | Notes |
|---|---|---|
| Transaction per test, rollback at the end | Begin before, Rollback in cleanup | Fast; cannot test commit behaviour; the Go test in the snippets does this |
| Truncate / refresh between tests | Laravel RefreshDatabase ("take care of this for you") | Simple; slower |
| Fresh schema per package | Container per suite | Slowest, most isolated |
// Go: run the same contract against the fake and, if DATABASE_URL is set, PostgreSQL.
func TestContract(t *testing.T) {
contract.Run(t, func(*testing.T) domain.Repository { return memrepo.New() })
}// Laravel: one trait of checks, two test classes (fake: plain PHPUnit; real: RefreshDatabase).
final class InMemoryOrderRepositoryTest extends TestCase { use OrderRepositoryContract; }
final class EloquentOrderRepositoryTest extends TestCase { use OrderRepositoryContract, RefreshDatabase; }Fix / how to use it: keep fakes dumb (copy state in and out, same error values), keep the contract in one place, run the real-engine suite in CI with the same engine and version as production. Messaging side: Testing Messaging.
Per-language and per-framework view
Classification column is ours (from Fowler's definitions); each tool's own docs describe features, not pattern names.
| Tool | Closest pattern | Unit of Work | Identity Map | Lazy loading | Optimistic lock | Soft delete | Source |
|---|---|---|---|---|---|---|---|
| Eloquent (Laravel 13) | Active Record | No tracking; save() per model, you wrap DB::transaction | No | Default for relations; preventLazyLoading() | Not built in; write where('version', $n) | SoftDeletes trait | Laravel docs |
| Doctrine ORM (PHP) | Data Mapper | Yes, EntityManager, flush() | Yes, "per PHP request" | Not covered in the pages we read | Not covered in the pages we read | Not covered in the pages we read | Doctrine docs |
| GORM (Go) | Active Record-ish (models carry tags; you choose whether to wrap) | db.Transaction(func(tx *gorm.DB) error); writes run in an implicit transaction | No | No; Preload for eager loading | Not in core; Where("version = ?") | gorm.DeletedAt | GORM docs |
| sqlc (Go) | Table Data Gateway over generated SQL | Queries.WithTx(tx) | No | None: you write each query | Hand-written WHERE version with :execrows | Hand-written deleted_at IS NULL | sqlc docs |
| ent (Go) | Generated entity graph with a client | Has a transactions page (not read in detail) | No | Eager WithX() edges | Not in the part we read | Not in the part we read | ent docs |
database/sql + pgx (Go) | Raw gateway | BeginTx, *sql.Tx | No | None | By hand | By hand | database/sql docs |
Query builder (DB::table) | Table Data Gateway, rows as stdClass | DB::transaction | No | None | By hand | By hand | Laravel docs |
| PostgreSQL, MySQL/InnoDB, SQL Server, Oracle | Storage engines under all of the above | Transactions, locks, MVCC | n/a | n/a | Row version via your column | n/a | See Databases |
| SQLite, MongoDB, Redis, CockroachDB | Other stores a repository adapter may target | Varies (MongoDB multi-document transactions, CockroachDB serializable) | n/a | n/a | MongoDB: version field by hand | n/a | See Databases |
GORM's docs state that write operations "run inside a transaction to ensure data consistency, you can disable it during initialization". Its Save writes all fields, which is the usual source of lost updates when two writers load the same record. ent's docs describe eager loading: "ent supports querying entities with their associations (through their edges)".
Mechanics
Dirty checking and what SQL gets emitted Must-know
How a tool decides what to write defines how it fails.
| Tool | How it knows what changed | SQL emitted on save | Failure mode |
|---|---|---|---|
| Eloquent | Compares attributes with originals (isDirty()) | UPDATE ... SET changed columns | Two writers on different columns both succeed; same column: last wins |
| Doctrine | Unit of Work snapshots entities at load, diffs at flush() | One batch in one transaction | Large unit of work is slow and memory-hungry |
GORM Save | No tracking; writes all fields | UPDATE ... SET every column | Overwrites a concurrent change to any column |
GORM Updates with a map or struct | Only the given fields (non-zero for structs) | UPDATE ... SET given | Zero values silently skipped when using structs |
| sqlc | You choose the statement | Exactly your SQL | Forgetting a column in a hand-written UPDATE |
| Repository with versioning | Whole aggregate, one version | UPDATE ... WHERE version + rewrite children | Children rewritten (delete + insert) even if unchanged |
Same two edits, three tools (two admins, order o-1, status vs notes)
1 A: load o-1 (status=draft, notes='') B: load o-1 (status=draft, notes='')
2 A: status = placed; save B: notes = 'gift'; save
3 Eloquent save(): A writes status, B writes notes -> both survive (different columns), no version
4 GORM Save(&o): A writes all, B writes all -> B overwrites status back to draft
5 Version column: A ok (v1->v2), B conflict -> B reloads and retriesTransaction mechanics in the object layer Important
| Concern | Go (database/sql) | Laravel |
|---|---|---|
| Pool | sql.DB is "a database handle representing a pool of zero or more underlying connections", safe for concurrent use | Connection per request/worker; see Connection Pooling |
| Begin | db.BeginTx(ctx, &sql.TxOptions{Isolation:..., ReadOnly:...}) | DB::transaction(fn, attempts) or beginTransaction() |
| Commit/rollback | tx.Commit() / tx.Rollback(); sql.ErrTxDone after either | Automatic on closure return or exception |
| Context | ctx cancels the query and rolls back an open transaction | Request timeouts, not context |
| Retry | You write it (40001, 40P01) | attempts: argument, documented under "Handling Deadlocks" |
| Nested | Pass the same *sql.Tx; there is no nesting | DB::transaction inside DB::transaction is tracked by Laravel as a nested level (nesting is not described in the pages we read; test it on your driver) |
| After commit | You call the publisher after Commit() | ShouldHandleEventsAfterCommit on observers; outbox row for messages |
Errors you map in the repository Important
| Source | Raw error | Domain meaning | Retry? |
|---|---|---|---|
database/sql | sql.ErrNoRows | ErrNotFound | No |
| Eloquent | ModelNotFoundException from findOrFail | OrderNotFound | No |
| PostgreSQL | SQLSTATE 23505 unique_violation | AlreadyExists / business duplicate | No |
| PostgreSQL | SQLSTATE 23503 foreign_key_violation | Reference to a missing aggregate | No |
| PostgreSQL | SQLSTATE 40001 serialization_failure | Retry the whole unit of work | Yes |
| PostgreSQL | SQLSTATE 40P01 deadlock_detected | Retry the whole unit of work | Yes |
| MySQL/InnoDB | 1062 duplicate key, 1213 deadlock, 1205 lock wait timeout | As above | 1213, 1205: yes |
| Version check | 0 rows affected | ErrConflict / ConcurrencyConflict | After reload |
The repository's job is to turn engine errors into domain errors, so that use cases never import pgconn or Illuminate\Database\QueryException. Retry rules are on Error & Exception Handling and Fault Tolerance and Deadlocks.
Knobs that change persistence behaviour Good to know
| Knob | Tool | Effect |
|---|---|---|
Model::preventLazyLoading(! $this->app->isProduction()) | Eloquent | Exception on lazy load outside production |
Model::preventSilentlyDiscardingAttributes() | Eloquent | Exception when a non-fillable attribute is dropped (listed in the docs index) |
DB::transaction($cb, attempts: 3) | Laravel | Retry on deadlock |
SkipDefaultTransaction: true | GORM gorm.Config | Disable the implicit per-write transaction ("30%+ performance improvement" per GORM docs) |
db.SetMaxOpenConns, SetMaxIdleConns | database/sql | Pool size; see Connection Pooling |
emit_interface, sql_package | sqlc sqlc.yaml | Generate a Querier interface, choose database/sql or pgx |
| Overrides | sqlc | Map a column type to your Go type |
Go
Before
An Active Record written by hand: Order knows its columns, its SQL and its placing rule. It compiles and works. The costs: the rule cannot run without *sql.DB, the caller cannot choose the transaction, and the type is shaped like the table.
// Package before is Active Record written by hand in Go: the Order type
// knows its table, its SQL and its business rules, all in one place.
package before
import (
"context"
"database/sql"
"errors"
)
// Order mirrors the orders table column by column.
type Order struct {
ID string
CustomerID string
Status string
TotalCents int64
Lines []Line
}
// Line mirrors the order_lines table.
type Line struct {
SKU string
Qty int
UnitCents int64
}
// Find loads one order and its lines.
func Find(ctx context.Context, db *sql.DB, id string) (*Order, error) {
o := &Order{ID: id}
err := db.QueryRowContext(ctx,
`SELECT customer_id, status, total_cents FROM orders WHERE id = $1`, id).
Scan(&o.CustomerID, &o.Status, &o.TotalCents)
if err != nil {
return nil, err
}
rows, err := db.QueryContext(ctx,
`SELECT sku, qty, unit_cents FROM order_lines WHERE order_id = $1 ORDER BY position`, id)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var l Line
if err := rows.Scan(&l.SKU, &l.Qty, &l.UnitCents); err != nil {
return nil, err
}
o.Lines = append(o.Lines, l)
}
return o, rows.Err()
}
// Place applies a business rule and writes to the database in the same
// method. The rule cannot be tested without a database, the SQL cannot be
// reused without the rule, and nothing says which transaction this runs in.
func (o *Order) Place(ctx context.Context, db *sql.DB) error {
if len(o.Lines) == 0 {
return errors.New("an order needs at least one line")
}
o.TotalCents = 0
for _, l := range o.Lines {
o.TotalCents += int64(l.Qty) * l.UnitCents
}
o.Status = "placed"
_, err := db.ExecContext(ctx,
`UPDATE orders SET status = $2, total_cents = $3 WHERE id = $1`,
o.ID, o.Status, o.TotalCents)
return err
}After
The same behaviour as an aggregate behind a port. First the domain: no imports beyond context, errors and fmt.
// Package domain holds the Order aggregate. It imports no database,
// no framework and no JSON package: this is persistence ignorance.
package domain
import (
"context"
"errors"
"fmt"
)
// OrderID is the identity of an order, assigned by the application.
type OrderID string
// Status is the order lifecycle.
type Status string
// The allowed statuses.
const (
Draft Status = "draft"
Placed Status = "placed"
Cancelled Status = "cancelled"
)
// Money is a value object: an amount in minor units plus a currency.
type Money struct {
Cents int64
Currency string
}
// Add returns the sum of two amounts in the same currency.
func (m Money) Add(o Money) (Money, error) {
if m.Currency != o.Currency {
return Money{}, fmt.Errorf("currency mismatch: %s vs %s", m.Currency, o.Currency)
}
return Money{Cents: m.Cents + o.Cents, Currency: m.Currency}, nil
}
// Line is one entry of an order. It has no identity outside its order.
type Line struct {
SKU string
Qty int
UnitCents int64
}
// Order is the aggregate root. Lines are reachable only through it.
type Order struct {
id OrderID
customerID string
currency string
status Status
lines []Line
version int64
}
// NewOrder starts a draft order. Version 0 means "never stored".
func NewOrder(id OrderID, customerID, currency string) (*Order, error) {
if id == "" || customerID == "" {
return nil, errors.New("id and customer are required")
}
return &Order{id: id, customerID: customerID, currency: currency, status: Draft}, nil
}
// Rehydrate rebuilds an order from stored state. Only repositories call it.
// It skips the business rules on purpose: stored data was valid when written.
func Rehydrate(id OrderID, customerID, currency string, status Status, lines []Line, version int64) *Order {
return &Order{id: id, customerID: customerID, currency: currency, status: status,
lines: append([]Line(nil), lines...), version: version}
}
// ID returns the identity.
func (o *Order) ID() OrderID { return o.id }
// CustomerID returns the owning customer.
func (o *Order) CustomerID() string { return o.customerID }
// Currency returns the order currency.
func (o *Order) Currency() string { return o.currency }
// Status returns the lifecycle state.
func (o *Order) Status() Status { return o.status }
// Version returns the version this object was loaded or last saved at.
func (o *Order) Version() int64 { return o.version }
// Lines returns a copy so callers cannot bypass the root.
func (o *Order) Lines() []Line { return append([]Line(nil), o.lines...) }
// AcceptVersion is called by a repository after a successful write.
func (o *Order) AcceptVersion(v int64) { o.version = v }
// AddLine adds a line while the order is a draft.
func (o *Order) AddLine(sku string, qty int, unitCents int64) error {
if o.status != Draft {
return fmt.Errorf("cannot change a %s order", o.status)
}
if qty <= 0 || unitCents < 0 {
return errors.New("quantity must be positive and price non-negative")
}
o.lines = append(o.lines, Line{SKU: sku, Qty: qty, UnitCents: unitCents})
return nil
}
// Place moves a draft order to placed. An order needs at least one line.
func (o *Order) Place() error {
if o.status != Draft {
return fmt.Errorf("cannot place a %s order", o.status)
}
if len(o.lines) == 0 {
return errors.New("an order needs at least one line")
}
o.status = Placed
return nil
}
// Total sums the lines.
func (o *Order) Total() Money {
var cents int64
for _, l := range o.lines {
cents += int64(l.Qty) * l.UnitCents
}
return Money{Cents: cents, Currency: o.currency}
}
// Errors every repository implementation must return.
var (
ErrNotFound = errors.New("order not found")
ErrConflict = errors.New("order was changed by someone else")
)
// Repository is the collection-like port of the Order aggregate. It is
// defined next to the domain; adapters implement it elsewhere.
type Repository interface {
// Add stores a new order (version 0). It sets the version to 1.
Add(ctx context.Context, o *Order) error
// Get loads the whole aggregate or returns ErrNotFound.
Get(ctx context.Context, id OrderID) (*Order, error)
// Save writes changes if the stored version still equals o.Version();
// otherwise it returns ErrConflict.
Save(ctx context.Context, o *Order) error
}The use case owns the transaction boundary (UnitOfWork) and speaks only to the port.
// Package app holds use cases. It owns the transaction boundary.
package app
import (
"context"
"academy/data-persistence-design/after/domain"
)
// UnitOfWork runs fn in one transaction. Everything fn does through the
// repository it receives commits together or not at all.
type UnitOfWork interface {
Do(ctx context.Context, fn func(ctx context.Context, orders domain.Repository) error) error
}
// PlaceOrder is one use case: load, call the domain, save, in one unit of work.
type PlaceOrder struct {
UoW UnitOfWork
}
// Handle places the order with the given id.
func (p PlaceOrder) Handle(ctx context.Context, id domain.OrderID) error {
return p.UoW.Do(ctx, func(ctx context.Context, orders domain.Repository) error {
o, err := orders.Get(ctx, id)
if err != nil {
return err
}
if err := o.Place(); err != nil {
return err
}
return orders.Save(ctx, o)
})
}The SQL adapter. The queries live in query.sql, typed code is in the shape sqlc generates (we did not run sqlc here; the file header says so), and the repository maps rows to the aggregate.
-- PostgreSQL. The aggregate is two tables: the root row and its lines.
CREATE TABLE IF NOT EXISTS orders (
id text PRIMARY KEY,
customer_id text NOT NULL,
currency char(3) NOT NULL,
status text NOT NULL CHECK (status IN ('draft', 'placed', 'cancelled')),
version bigint NOT NULL DEFAULT 1,
deleted_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS order_lines (
order_id text NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
position int NOT NULL,
sku text NOT NULL,
qty int NOT NULL CHECK (qty > 0),
unit_cents bigint NOT NULL CHECK (unit_cents >= 0),
PRIMARY KEY (order_id, position)
);
CREATE INDEX IF NOT EXISTS orders_customer_idx ON orders (customer_id) WHERE deleted_at IS NULL;-- name: GetOrder :one
SELECT id, customer_id, currency, status, version
FROM orders
WHERE id = $1 AND deleted_at IS NULL;
-- name: ListLines :many
SELECT order_id, position, sku, qty, unit_cents
FROM order_lines
WHERE order_id = $1
ORDER BY position;
-- name: InsertOrder :exec
INSERT INTO orders (id, customer_id, currency, status)
VALUES ($1, $2, $3, $4);
-- name: InsertLine :exec
INSERT INTO order_lines (order_id, position, sku, qty, unit_cents)
VALUES ($1, $2, $3, $4, $5);
-- name: DeleteLines :exec
DELETE FROM order_lines WHERE order_id = $1;
-- Optimistic lock: the WHERE clause carries the version the caller read.
-- :execrows returns the affected row count; 0 means someone else won.
-- name: UpdateOrderVersioned :execrows
UPDATE orders
SET status = $2, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL;
-- Read model: no aggregate, no lines, one row per order.
-- name: ListOrderSummaries :many
SELECT o.id, o.status, o.currency,
COALESCE(SUM(l.qty * l.unit_cents), 0)::bigint AS total_cents,
COUNT(l.position)::int AS line_count
FROM orders o
LEFT JOIN order_lines l ON l.order_id = o.id
WHERE o.customer_id = $1 AND o.deleted_at IS NULL
GROUP BY o.id
ORDER BY o.created_at DESC
LIMIT $2;version: "2"
sql:
- engine: "postgresql"
schema: "schema.sql"
queries: "query.sql"
gen:
go:
package: "db"
out: "db"
sql_package: "database/sql"// Code in the shape that `sqlc generate` produces (sqlc was not run for this
// page; regenerate with the sqlc.yaml next to it and compare).
package db
import (
"context"
"database/sql"
)
// DBTX is satisfied by both *sql.DB and *sql.Tx.
type DBTX interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
PrepareContext(context.Context, string) (*sql.Stmt, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
}
// New wraps a connection or a transaction.
func New(db DBTX) *Queries { return &Queries{db: db} }
// Queries holds one method per named query.
type Queries struct {
db DBTX
}
// WithTx returns Queries bound to a transaction.
func (q *Queries) WithTx(tx *sql.Tx) *Queries { return &Queries{db: tx} }package db
import "context"
const getOrder = `SELECT id, customer_id, currency, status, version
FROM orders
WHERE id = $1 AND deleted_at IS NULL`
// GetOrder returns the root row.
func (q *Queries) GetOrder(ctx context.Context, id string) (Order, error) {
row := q.db.QueryRowContext(ctx, getOrder, id)
var i Order
err := row.Scan(&i.ID, &i.CustomerID, &i.Currency, &i.Status, &i.Version)
return i, err
}
const listLines = `SELECT order_id, position, sku, qty, unit_cents
FROM order_lines
WHERE order_id = $1
ORDER BY position`
// ListLines returns the lines of one order.
func (q *Queries) ListLines(ctx context.Context, orderID string) ([]OrderLine, error) {
rows, err := q.db.QueryContext(ctx, listLines, orderID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []OrderLine
for rows.Next() {
var i OrderLine
if err := rows.Scan(&i.OrderID, &i.Position, &i.Sku, &i.Qty, &i.UnitCents); err != nil {
return nil, err
}
items = append(items, i)
}
return items, rows.Err()
}
const insertOrder = `INSERT INTO orders (id, customer_id, currency, status)
VALUES ($1, $2, $3, $4)`
// InsertOrderParams are the arguments of InsertOrder.
type InsertOrderParams struct {
ID string
CustomerID string
Currency string
Status string
}
// InsertOrder inserts the root row.
func (q *Queries) InsertOrder(ctx context.Context, arg InsertOrderParams) error {
_, err := q.db.ExecContext(ctx, insertOrder, arg.ID, arg.CustomerID, arg.Currency, arg.Status)
return err
}
const insertLine = `INSERT INTO order_lines (order_id, position, sku, qty, unit_cents)
VALUES ($1, $2, $3, $4, $5)`
// InsertLineParams are the arguments of InsertLine.
type InsertLineParams struct {
OrderID string
Position int32
Sku string
Qty int32
UnitCents int64
}
// InsertLine inserts one line.
func (q *Queries) InsertLine(ctx context.Context, arg InsertLineParams) error {
_, err := q.db.ExecContext(ctx, insertLine, arg.OrderID, arg.Position, arg.Sku, arg.Qty, arg.UnitCents)
return err
}
const deleteLines = `DELETE FROM order_lines WHERE order_id = $1`
// DeleteLines removes every line of one order.
func (q *Queries) DeleteLines(ctx context.Context, orderID string) error {
_, err := q.db.ExecContext(ctx, deleteLines, orderID)
return err
}
const updateOrderVersioned = `UPDATE orders
SET status = $2, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $3 AND deleted_at IS NULL`
// UpdateOrderVersionedParams are the arguments of UpdateOrderVersioned.
type UpdateOrderVersionedParams struct {
ID string
Status string
Version int64
}
// UpdateOrderVersioned returns the number of rows changed (0 or 1).
func (q *Queries) UpdateOrderVersioned(ctx context.Context, arg UpdateOrderVersionedParams) (int64, error) {
result, err := q.db.ExecContext(ctx, updateOrderVersioned, arg.ID, arg.Status, arg.Version)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
const listOrderSummaries = `SELECT o.id, o.status, o.currency,
COALESCE(SUM(l.qty * l.unit_cents), 0)::bigint AS total_cents,
COUNT(l.position)::int AS line_count
FROM orders o
LEFT JOIN order_lines l ON l.order_id = o.id
WHERE o.customer_id = $1 AND o.deleted_at IS NULL
GROUP BY o.id
ORDER BY o.created_at DESC
LIMIT $2`
// ListOrderSummariesParams are the arguments of ListOrderSummaries.
type ListOrderSummariesParams struct {
CustomerID string
Limit int32
}
// ListOrderSummariesRow is one row of the read model.
type ListOrderSummariesRow struct {
ID string
Status string
Currency string
TotalCents int64
LineCount int32
}
// ListOrderSummaries returns one row per order, newest first.
func (q *Queries) ListOrderSummaries(ctx context.Context, arg ListOrderSummariesParams) ([]ListOrderSummariesRow, error) {
rows, err := q.db.QueryContext(ctx, listOrderSummaries, arg.CustomerID, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrderSummariesRow
for rows.Next() {
var i ListOrderSummariesRow
if err := rows.Scan(&i.ID, &i.Status, &i.Currency, &i.TotalCents, &i.LineCount); err != nil {
return nil, err
}
items = append(items, i)
}
return items, rows.Err()
}// Package sqlcrepo is the SQL adapter of domain.Repository: it maps the
// aggregate to two tables with queries written in SQL and typed by sqlc.
package sqlcrepo
import (
"context"
"database/sql"
"errors"
"academy/data-persistence-design/after/app"
"academy/data-persistence-design/after/domain"
"academy/data-persistence-design/after/readmodel"
"academy/data-persistence-design/after/sqlcrepo/db"
)
// Repo implements domain.Repository and readmodel.Reader.
type Repo struct{ q *db.Queries }
var (
_ domain.Repository = (*Repo)(nil)
_ readmodel.Reader = (*Repo)(nil)
)
// New builds a repository on a connection or on a transaction.
func New(q *db.Queries) *Repo { return &Repo{q: q} }
// Add inserts the root and its lines.
func (r *Repo) Add(ctx context.Context, o *domain.Order) error {
err := r.q.InsertOrder(ctx, db.InsertOrderParams{
ID: string(o.ID()), CustomerID: o.CustomerID(), Currency: o.Currency(), Status: string(o.Status()),
})
if err != nil {
return err
}
if err := r.writeLines(ctx, o); err != nil {
return err
}
o.AcceptVersion(1)
return nil
}
// Get loads the root and its lines, then rebuilds the aggregate.
func (r *Repo) Get(ctx context.Context, id domain.OrderID) (*domain.Order, error) {
row, err := r.q.GetOrder(ctx, string(id))
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, err
}
rows, err := r.q.ListLines(ctx, row.ID)
if err != nil {
return nil, err
}
lines := make([]domain.Line, 0, len(rows))
for _, l := range rows {
lines = append(lines, domain.Line{SKU: l.Sku, Qty: int(l.Qty), UnitCents: l.UnitCents})
}
return domain.Rehydrate(domain.OrderID(row.ID), row.CustomerID, row.Currency,
domain.Status(row.Status), lines, row.Version), nil
}
// Save is an optimistic write: zero affected rows means a newer version exists.
func (r *Repo) Save(ctx context.Context, o *domain.Order) error {
n, err := r.q.UpdateOrderVersioned(ctx, db.UpdateOrderVersionedParams{
ID: string(o.ID()), Status: string(o.Status()), Version: o.Version(),
})
if err != nil {
return err
}
if n == 0 {
return domain.ErrConflict
}
if err := r.q.DeleteLines(ctx, string(o.ID())); err != nil {
return err
}
if err := r.writeLines(ctx, o); err != nil {
return err
}
o.AcceptVersion(o.Version() + 1)
return nil
}
func (r *Repo) writeLines(ctx context.Context, o *domain.Order) error {
for i, l := range o.Lines() {
err := r.q.InsertLine(ctx, db.InsertLineParams{
OrderID: string(o.ID()), Position: int32(i), Sku: l.SKU, Qty: int32(l.Qty), UnitCents: l.UnitCents,
})
if err != nil {
return err
}
}
return nil
}
// ForCustomer is the read side: it never builds an aggregate.
func (r *Repo) ForCustomer(ctx context.Context, customerID string, limit int) ([]readmodel.OrderSummary, error) {
rows, err := r.q.ListOrderSummaries(ctx, db.ListOrderSummariesParams{CustomerID: customerID, Limit: int32(limit)})
if err != nil {
return nil, err
}
out := make([]readmodel.OrderSummary, 0, len(rows))
for _, s := range rows {
out = append(out, readmodel.OrderSummary{
ID: s.ID, Status: s.Status, Currency: s.Currency, TotalCents: s.TotalCents, LineCount: int(s.LineCount),
})
}
return out, nil
}
// UoW opens a database transaction per unit of work and hands the use case a
// repository bound to it.
type UoW struct {
DB *sql.DB
Q *db.Queries
}
var _ app.UnitOfWork = UoW{}
// Do implements app.UnitOfWork.
func (u UoW) Do(ctx context.Context, fn func(context.Context, domain.Repository) error) error {
tx, err := u.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
if err := fn(ctx, New(u.Q.WithTx(tx))); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}The same port with GORM. Compare how the version check, eager loading and soft delete look when the tool is an ORM.
// Package gormrepo is the same adapter written with GORM. Compare it with
// package sqlcrepo: the port (domain.Repository) is identical.
package gormrepo
import (
"context"
"errors"
"gorm.io/gorm"
"academy/data-persistence-design/after/domain"
)
// orderRow and lineRow are persistence models. They carry GORM tags, the
// domain type does not.
type orderRow struct {
ID string `gorm:"primaryKey"`
CustomerID string
Currency string
Status string
Version int64
DeletedAt gorm.DeletedAt // soft delete: Delete sets it, queries skip it
Lines []lineRow `gorm:"foreignKey:OrderID;references:ID"`
}
func (orderRow) TableName() string { return "orders" }
type lineRow struct {
OrderID string `gorm:"primaryKey"`
Position int `gorm:"primaryKey;autoIncrement:false"`
SKU string
Qty int
UnitCents int64
}
func (lineRow) TableName() string { return "order_lines" }
// Repo implements domain.Repository on top of *gorm.DB.
type Repo struct{ db *gorm.DB }
var _ domain.Repository = (*Repo)(nil)
// New builds a repository. Pass a transaction handle to join a transaction.
func New(db *gorm.DB) *Repo { return &Repo{db: db} }
// Add inserts the root and its lines in one call (GORM saves associations).
func (r *Repo) Add(ctx context.Context, o *domain.Order) error {
row := toRow(o)
row.Version = 1
if err := r.db.WithContext(ctx).Create(&row).Error; err != nil {
return err
}
o.AcceptVersion(1)
return nil
}
// Get uses Preload, an explicit eager load of the aggregate's lines.
func (r *Repo) Get(ctx context.Context, id domain.OrderID) (*domain.Order, error) {
var row orderRow
err := r.db.WithContext(ctx).Preload("Lines", func(tx *gorm.DB) *gorm.DB {
return tx.Order("position")
}).First(&row, "id = ?", string(id)).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, err
}
lines := make([]domain.Line, 0, len(row.Lines))
for _, l := range row.Lines {
lines = append(lines, domain.Line{SKU: l.SKU, Qty: l.Qty, UnitCents: l.UnitCents})
}
return domain.Rehydrate(domain.OrderID(row.ID), row.CustomerID, row.Currency,
domain.Status(row.Status), lines, row.Version), nil
}
// Save does the optimistic check by hand: GORM has no version column feature
// in core, so the WHERE clause and RowsAffected are ours.
func (r *Repo) Save(ctx context.Context, o *domain.Order) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
res := tx.Model(&orderRow{}).
Where("id = ? AND version = ?", string(o.ID()), o.Version()).
Updates(map[string]any{"status": string(o.Status()), "version": o.Version() + 1})
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return domain.ErrConflict
}
if err := tx.Where("order_id = ?", string(o.ID())).Delete(&lineRow{}).Error; err != nil {
return err
}
if lines := toRow(o).Lines; len(lines) > 0 {
if err := tx.Create(&lines).Error; err != nil {
return err
}
}
o.AcceptVersion(o.Version() + 1)
return nil
})
}
func toRow(o *domain.Order) orderRow {
row := orderRow{ID: string(o.ID()), CustomerID: o.CustomerID(), Currency: o.Currency(),
Status: string(o.Status()), Version: o.Version()}
for i, l := range o.Lines() {
row.Lines = append(row.Lines, lineRow{OrderID: row.ID, Position: i, SKU: l.SKU, Qty: l.Qty, UnitCents: l.UnitCents})
}
return row
}The read side returns DTOs and never builds an aggregate.
// Package readmodel holds query-side shapes. They are plain data: no
// behaviour, no invariants, no link to the aggregate.
package readmodel
import "context"
// OrderSummary is the DTO a list screen or an API response needs.
type OrderSummary struct {
ID string `json:"id"`
Status string `json:"status"`
Currency string `json:"currency"`
TotalCents int64 `json:"total_cents"`
LineCount int `json:"line_count"`
}
// Reader is the query port. It is separate from domain.Repository on purpose.
type Reader interface {
ForCustomer(ctx context.Context, customerID string, limit int) ([]OrderSummary, error)
}Value mapping across database/sql.
// Package valuer shows how a value object, an enum and a JSON column cross
// the database/sql boundary: driver.Valuer writes, sql.Scanner reads.
package valuer
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
// Address is a value object stored in one jsonb column.
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Postal string `json:"postal"`
}
// Value implements driver.Valuer.
func (a Address) Value() (driver.Value, error) { return json.Marshal(a) }
// Scan implements sql.Scanner.
func (a *Address) Scan(src any) error {
switch v := src.(type) {
case []byte:
return json.Unmarshal(v, a)
case string:
return json.Unmarshal([]byte(v), a)
case nil:
*a = Address{}
return nil
default:
return fmt.Errorf("address: cannot scan %T", src)
}
}
// Status is a closed enum that refuses unknown database values.
type Status string
// The allowed statuses.
const (
Draft Status = "draft"
Placed Status = "placed"
)
// Value implements driver.Valuer and rejects invalid values before the write.
func (s Status) Value() (driver.Value, error) {
if s != Draft && s != Placed {
return nil, fmt.Errorf("status: invalid value %q", string(s))
}
return string(s), nil
}
// Scan implements sql.Scanner and rejects invalid values after the read.
func (s *Status) Scan(src any) error {
var raw string
switch v := src.(type) {
case string:
raw = v
case []byte:
raw = string(v)
default:
return fmt.Errorf("status: cannot scan %T", src)
}
if st := Status(raw); st == Draft || st == Placed {
*s = st
return nil
}
return fmt.Errorf("status: unknown value %q in database", raw)
}The in-memory fake, with the same version check and a snapshot-based rollback.
// Package memrepo is the in-memory fake of domain.Repository, used by fast tests.
package memrepo
import (
"context"
"sync"
"academy/data-persistence-design/after/app"
"academy/data-persistence-design/after/domain"
)
type stored struct {
customerID, currency string
status domain.Status
lines []domain.Line
version int64
}
// Repo keeps copies, never the caller's pointer, like a real database would.
type Repo struct {
mu sync.Mutex
rows map[domain.OrderID]stored
}
// New returns an empty fake.
func New() *Repo { return &Repo{rows: map[domain.OrderID]stored{}} }
// Add implements domain.Repository.
func (r *Repo) Add(_ context.Context, o *domain.Order) error {
r.mu.Lock()
defer r.mu.Unlock()
r.rows[o.ID()] = stored{o.CustomerID(), o.Currency(), o.Status(), o.Lines(), 1}
o.AcceptVersion(1)
return nil
}
// Get implements domain.Repository.
func (r *Repo) Get(_ context.Context, id domain.OrderID) (*domain.Order, error) {
r.mu.Lock()
defer r.mu.Unlock()
s, ok := r.rows[id]
if !ok {
return nil, domain.ErrNotFound
}
return domain.Rehydrate(id, s.customerID, s.currency, s.status, s.lines, s.version), nil
}
// Save implements domain.Repository with the same version check as SQL.
func (r *Repo) Save(_ context.Context, o *domain.Order) error {
r.mu.Lock()
defer r.mu.Unlock()
s, ok := r.rows[o.ID()]
if !ok {
return domain.ErrNotFound
}
if s.version != o.Version() {
return domain.ErrConflict
}
s.status, s.lines, s.version = o.Status(), o.Lines(), s.version+1
r.rows[o.ID()] = s
o.AcceptVersion(s.version)
return nil
}
// UoW is a fake unit of work: it snapshots the rows and restores them on error.
type UoW struct{ Repo *Repo }
var _ app.UnitOfWork = UoW{}
// Do implements app.UnitOfWork.
func (u UoW) Do(ctx context.Context, fn func(context.Context, domain.Repository) error) error {
u.Repo.mu.Lock()
snapshot := make(map[domain.OrderID]stored, len(u.Repo.rows))
for k, v := range u.Repo.rows {
snapshot[k] = v
}
u.Repo.mu.Unlock()
if err := fn(ctx, u.Repo); err != nil {
u.Repo.mu.Lock()
u.Repo.rows = snapshot
u.Repo.mu.Unlock()
return err
}
return nil
}The contract every implementation must pass, and how it is wired to the fake and to PostgreSQL.
// Package contract is a test suite every domain.Repository must pass. The
// in-memory fake and the SQL adapters run the same checks, so the fake
// cannot drift from the real thing.
package contract
import (
"context"
"errors"
"testing"
"academy/data-persistence-design/after/domain"
)
// Run executes the contract against repositories made by newRepo.
func Run(t *testing.T, newRepo func(t *testing.T) domain.Repository) {
ctx := context.Background()
t.Run("round trip keeps the whole aggregate", func(t *testing.T) {
repo := newRepo(t)
o, _ := domain.NewOrder("o-1", "c-1", "USD")
_ = o.AddLine("sku-1", 2, 500)
_ = o.AddLine("sku-2", 1, 250)
if err := repo.Add(ctx, o); err != nil {
t.Fatal(err)
}
got, err := repo.Get(ctx, "o-1")
if err != nil {
t.Fatal(err)
}
if got.Total().Cents != 1250 || len(got.Lines()) != 2 || got.Version() != 1 {
t.Fatalf("unexpected aggregate: total=%d lines=%d version=%d",
got.Total().Cents, len(got.Lines()), got.Version())
}
})
t.Run("missing order is ErrNotFound", func(t *testing.T) {
if _, err := newRepo(t).Get(ctx, "nope"); !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
})
t.Run("second writer gets ErrConflict", func(t *testing.T) {
repo := newRepo(t)
o, _ := domain.NewOrder("o-2", "c-1", "USD")
_ = o.AddLine("sku-1", 1, 100)
_ = repo.Add(ctx, o)
a, _ := repo.Get(ctx, "o-2")
b, _ := repo.Get(ctx, "o-2")
_ = a.Place()
_ = b.Place()
if err := repo.Save(ctx, a); err != nil {
t.Fatal(err)
}
if err := repo.Save(ctx, b); !errors.Is(err, domain.ErrConflict) {
t.Fatalf("err = %v, want ErrConflict", err)
}
})
}package sqlcrepo_test
import (
"database/sql"
"os"
"testing"
_ "github.com/jackc/pgx/v5/stdlib"
"academy/data-persistence-design/after/contract"
"academy/data-persistence-design/after/domain"
"academy/data-persistence-design/after/sqlcrepo"
"academy/data-persistence-design/after/sqlcrepo/db"
_ "embed"
)
//go:embed schema.sql
var schema string
// TestContract runs the shared contract against PostgreSQL. Every subtest runs
// inside one transaction that is rolled back, so nothing is left behind.
// Run: DATABASE_URL=postgres://... go test ./after/sqlcrepo
func TestContract(t *testing.T) {
url := os.Getenv("DATABASE_URL")
if url == "" {
t.Skip("DATABASE_URL not set")
}
conn, err := sql.Open("pgx", url)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
contract.Run(t, func(t *testing.T) domain.Repository {
tx, err := conn.Begin()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = tx.Rollback() })
if _, err := tx.Exec(schema); err != nil {
t.Fatal(err)
}
return sqlcrepo.New(db.New(tx))
})
}The Go angle
The pool is the connection. sql.DB is a pool and is safe for concurrent use, so repositories hold a *sql.DB or a DBTX, never a single connection. Transactions pin one connection, which is why the transaction handle has to be passed down (sqlc's WithTx, GORM's tx *gorm.DB) instead of read from a global.
DBTX is the seam. sqlc's generated DBTX interface is satisfied by both *sql.DB and *sql.Tx. That one interface is why a repository can run standalone or inside a unit of work with the same code.
sqlc, GORM, ent: three answers to the same question.
| Question | sqlc | GORM | ent |
|---|---|---|---|
| Where does SQL live? | In .sql files you write | Generated by the library from method chains | Generated by the library from a schema graph |
| What is the model type? | A struct per query/table, generated | Your struct with tags | Generated entities |
| Compile-time checks | Queries checked against the schema at generate time | Few; errors at runtime | Strong: typed predicates |
| Eager loading | Write the join or a second query | Preload | WithX edges |
| Value types | Overrides in sqlc.yaml | Scanner/Valuer | Field types and custom Go types |
| Best for | Query-heavy services that want visible SQL | Fast CRUD, many small models | Graph-shaped domains |
| Domain isolation | You map rows to the domain | You map models to the domain, or use models as the domain | You map entities to the domain, or use them |
sqlc's own description: "You write SQL queries, you run sqlc to generate Go code that presents type-safe interfaces to those queries, you write application code that calls the methods sqlc generated." Go's culture of small interfaces means the repository port is two or three methods, defined where it is consumed (Dependency Inversion), and the adapter is a struct in its own package.
Laravel
Before
Active Record the Laravel way: the model casts its enum, owns the relation, runs its rule and saves itself, and the controller walks relations lazily.
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\OrderStatus;
use App\Casts\MoneyCast;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
/**
* Active Record: one object = one row of `orders`. The model knows its table,
* its casts, its relations, its business rules AND how to save itself.
* For a CRUD-ish aggregate this is the shortest path; the cost shows up when
* rules grow and tests need the database.
*/
class Order extends Model
{
use SoftDeletes;
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
protected function casts(): array
{
return [
'status' => OrderStatus::class, // enum <-> string column
'total' => MoneyCast::class, // value object <-> two columns
'version' => 'integer',
];
}
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class)->orderBy('position');
}
/** Business rule and persistence in one method. */
public function place(): void
{
if ($this->lines()->count() === 0) {
throw new \DomainException('An order needs at least one line.');
}
DB::transaction(function (): void {
$this->status = OrderStatus::Placed;
$this->save(); // UPDATE orders SET ... (whole dirty set)
});
}
}<?php
declare(strict_types=1);
namespace App\Casts;
use App\Domain\Money;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
/**
* Maps two columns (total_cents, currency) to one value object.
*
* @implements CastsAttributes<Money, Money>
*/
class MoneyCast implements CastsAttributes
{
public function get(Model $model, string $key, mixed $value, array $attributes): Money
{
return new Money((int) $attributes['total_cents'], (string) $attributes['currency']);
}
public function set(Model $model, string $key, mixed $value, array $attributes): array
{
if (! $value instanceof Money) {
throw new InvalidArgumentException('The given value is not a Money instance.');
}
return ['total_cents' => $value->cents, 'currency' => $value->currency];
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
class OrderController
{
/**
* The classic Active Record trap: the view model IS the table row, and
* `$order->lines` inside the loop lazy-loads one query per order (N+1).
*/
public function index(string $customerId): JsonResponse
{
$orders = Order::query()->where('customer_id', $customerId)->latest()->limit(50)->get();
return response()->json($orders->map(fn (Order $o) => [
'id' => $o->id,
'status' => $o->status->value,
'lines' => $o->lines->count(), // lazy load per row
]));
}
public function place(string $id): JsonResponse
{
Order::query()->findOrFail($id)->place();
return response()->json(['ok' => true]);
}
}After
The aggregate is a plain PHP class. Eloquent is demoted to a persistence model that only the repository touches. The migration carries the version column and soft deletes.
<?php
declare(strict_types=1);
namespace App\Domain;
/**
* The Order aggregate root. Plain PHP: no Eloquent, no facade, no framework
* import. That is persistence ignorance, and it is why this class can be
* tested with `new Order(...)` and nothing else.
*/
final class Order
{
/** @var list<array{sku: string, qty: int, unitCents: int}> */
private array $lines = [];
private int $version = 0;
public function __construct(
public readonly string $id,
public readonly string $customerId,
public readonly string $currency,
private OrderStatus $status = OrderStatus::Draft,
) {
}
/**
* Rebuild from stored state. Only repositories call this.
*
* @param list<array{sku: string, qty: int, unitCents: int}> $lines
*/
public static function rehydrate(
string $id,
string $customerId,
string $currency,
OrderStatus $status,
array $lines,
int $version,
): self {
$order = new self($id, $customerId, $currency, $status);
$order->lines = $lines;
$order->version = $version;
return $order;
}
public function status(): OrderStatus
{
return $this->status;
}
public function version(): int
{
return $this->version;
}
/** @return list<array{sku: string, qty: int, unitCents: int}> */
public function lines(): array
{
return $this->lines;
}
public function acceptVersion(int $version): void
{
$this->version = $version;
}
public function addLine(string $sku, int $qty, int $unitCents): void
{
if ($this->status !== OrderStatus::Draft) {
throw new \DomainException("Cannot change a {$this->status->value} order.");
}
if ($qty <= 0 || $unitCents < 0) {
throw new \DomainException('Quantity must be positive and price non-negative.');
}
$this->lines[] = ['sku' => $sku, 'qty' => $qty, 'unitCents' => $unitCents];
}
public function place(): void
{
if ($this->status !== OrderStatus::Draft) {
throw new \DomainException("Cannot place a {$this->status->value} order.");
}
if ($this->lines === []) {
throw new \DomainException('An order needs at least one line.');
}
$this->status = OrderStatus::Placed;
}
public function total(): Money
{
$cents = 0;
foreach ($this->lines as $line) {
$cents += $line['qty'] * $line['unitCents'];
}
return new Money($cents, $this->currency);
}
}<?php
declare(strict_types=1);
namespace App\Domain;
/** Value object: immutable, compared by value, no identity. */
final readonly class Money
{
public function __construct(public int $cents, public string $currency)
{
}
public function add(self $other): self
{
if ($other->currency !== $this->currency) {
throw new \DomainException("Currency mismatch: {$this->currency} vs {$other->currency}");
}
return new self($this->cents + $other->cents, $this->currency);
}
}<?php
declare(strict_types=1);
namespace App\Domain;
enum OrderStatus: string
{
case Draft = 'draft';
case Placed = 'placed';
case Cancelled = 'cancelled';
}<?php
declare(strict_types=1);
namespace App\Domain;
/** Collection-like port of the Order aggregate. Lives with the domain. */
interface OrderRepository
{
/** Store a new order (version 0); sets version 1. */
public function add(Order $order): void;
/** @throws OrderNotFound */
public function get(string $id): Order;
/**
* Write changes if the stored version still equals $order->version().
*
* @throws ConcurrencyConflict
*/
public function save(Order $order): void;
}<?php
declare(strict_types=1);
namespace App\Domain;
final class OrderNotFound extends \RuntimeException
{
public static function withId(string $id): self
{
return new self("Order {$id} not found.");
}
}<?php
declare(strict_types=1);
namespace App\Domain;
final class ConcurrencyConflict extends \RuntimeException
{
public static function forOrder(string $id): self
{
return new self("Order {$id} was changed by someone else.");
}
}<?php
declare(strict_types=1);
namespace App\Infrastructure;
use App\Domain\OrderStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Persistence model: an Eloquent class used ONLY inside the repository.
* Nothing outside Infrastructure imports it.
*/
class OrderRecord extends Model
{
use SoftDeletes;
protected $table = 'orders';
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
protected function casts(): array
{
return ['status' => OrderStatus::class, 'version' => 'integer'];
}
public function lines(): HasMany
{
return $this->hasMany(OrderLineRecord::class, 'order_id')->orderBy('position');
}
}<?php
declare(strict_types=1);
namespace App\Infrastructure;
use Illuminate\Database\Eloquent\Model;
class OrderLineRecord extends Model
{
protected $table = 'order_lines';
public $incrementing = false;
public $timestamps = false;
protected $guarded = [];
}<?php
declare(strict_types=1);
namespace App\Infrastructure;
use App\Domain\ConcurrencyConflict;
use App\Domain\Order;
use App\Domain\OrderNotFound;
use App\Domain\OrderRepository;
use Illuminate\Support\Facades\DB;
final class EloquentOrderRepository implements OrderRepository
{
public function add(Order $order): void
{
DB::transaction(function () use ($order): void {
OrderRecord::query()->create([
'id' => $order->id,
'customer_id' => $order->customerId,
'currency' => $order->currency,
'status' => $order->status(),
'version' => 1,
]);
$this->writeLines($order);
});
$order->acceptVersion(1);
}
public function get(string $id): Order
{
// with('lines') is an explicit eager load: two queries, never N+1.
$record = OrderRecord::query()->with('lines')->find($id);
if ($record === null) {
throw OrderNotFound::withId($id);
}
return Order::rehydrate(
$record->id,
$record->customer_id,
$record->currency,
$record->status,
$record->lines->map(fn (OrderLineRecord $l) => [
'sku' => $l->sku, 'qty' => (int) $l->qty, 'unitCents' => (int) $l->unit_cents,
])->all(),
$record->version,
);
}
/**
* Optimistic write. Eloquent has no built-in version column, so the check
* is ours: the UPDATE only matches when the version is still the one we read.
*/
public function save(Order $order): void
{
DB::transaction(function () use ($order): void {
$affected = OrderRecord::query()
->where('id', $order->id)
->where('version', $order->version())
->update(['status' => $order->status()->value, 'version' => $order->version() + 1]);
if ($affected === 0) {
throw ConcurrencyConflict::forOrder($order->id);
}
OrderLineRecord::query()->where('order_id', $order->id)->delete();
$this->writeLines($order);
});
$order->acceptVersion($order->version() + 1);
}
private function writeLines(Order $order): void
{
$rows = [];
foreach ($order->lines() as $position => $line) {
$rows[] = [
'order_id' => $order->id,
'position' => $position,
'sku' => $line['sku'],
'qty' => $line['qty'],
'unit_cents' => $line['unitCents'],
];
}
if ($rows !== []) {
OrderLineRecord::query()->insert($rows); // one multi-row INSERT
}
}
}<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('orders', function (Blueprint $table): void {
$table->string('id')->primary();
$table->string('customer_id')->index();
$table->char('currency', 3);
$table->string('status');
$table->unsignedBigInteger('version')->default(1); // optimistic lock
$table->softDeletes();
$table->timestamps();
});
Schema::create('order_lines', function (Blueprint $table): void {
$table->string('order_id');
$table->unsignedInteger('position');
$table->string('sku');
$table->unsignedInteger('qty');
$table->unsignedBigInteger('unit_cents');
$table->primary(['order_id', 'position']);
$table->foreign('order_id')->references('id')->on('orders')->cascadeOnDelete();
});
}
public function down(): void
{
Schema::dropIfExists('order_lines');
Schema::dropIfExists('orders');
}
};The use case owns the transaction, the DTO query serves the list screen, and the provider is the only place that names the adapter.
<?php
declare(strict_types=1);
namespace App\Application;
use App\Domain\OrderRepository;
use Illuminate\Support\Facades\DB;
/** One use case = one transaction. The transaction boundary is chosen here. */
final class PlaceOrder
{
public function __construct(private readonly OrderRepository $orders)
{
}
public function handle(string $orderId): void
{
DB::transaction(function () use ($orderId): void {
$order = $this->orders->get($orderId);
$order->place();
$this->orders->save($order);
}, attempts: 1); // a ConcurrencyConflict is a business retry, not a deadlock retry
}
}<?php
declare(strict_types=1);
namespace App\Application;
/** Read model / DTO: data only, shaped for one screen or one API response. */
final readonly class OrderSummary
{
public function __construct(
public string $id,
public string $status,
public string $currency,
public int $totalCents,
public int $lineCount,
) {
}
}<?php
declare(strict_types=1);
namespace App\Application;
use Illuminate\Support\Facades\DB;
/** Query side: no aggregate, no Eloquent models, one grouped SQL statement. */
final class OrderSummaryQuery
{
/** @return list<OrderSummary> */
public function forCustomer(string $customerId, int $limit = 50): array
{
return DB::table('orders as o')
->leftJoin('order_lines as l', 'l.order_id', '=', 'o.id')
->where('o.customer_id', $customerId)
->whereNull('o.deleted_at')
->groupBy('o.id', 'o.status', 'o.currency', 'o.created_at')
->orderByDesc('o.created_at')
->limit($limit)
->selectRaw('o.id, o.status, o.currency, COALESCE(SUM(l.qty * l.unit_cents), 0) AS total_cents, COUNT(l.position) AS line_count')
->get()
->map(fn (object $r) => new OrderSummary(
$r->id, $r->status, $r->currency, (int) $r->total_cents, (int) $r->line_count,
))
->all();
}
}<?php
declare(strict_types=1);
namespace App\Providers;
use App\Domain\OrderRepository;
use App\Infrastructure\EloquentOrderRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;
final class PersistenceServiceProvider extends ServiceProvider
{
public array $bindings = [
// The composition root: the only place that names the adapter.
OrderRepository::class => EloquentOrderRepository::class,
];
public function boot(): void
{
// Fail loudly in development when a relation is lazy loaded (N+1).
Model::preventLazyLoading(! $this->app->isProduction());
}
}Tests: the pure aggregate, the fake, and one contract run against both the fake and the real database.
<?php
declare(strict_types=1);
namespace Tests\Unit;
use App\Domain\Order;
use App\Domain\OrderStatus;
use PHPUnit\Framework\TestCase;
/** The aggregate needs nothing but `new`. */
final class OrderTest extends TestCase
{
public function test_an_empty_order_cannot_be_placed(): void
{
$this->expectException(\DomainException::class);
(new Order('o-1', 'c-1', 'USD'))->place();
}
public function test_a_placed_order_is_frozen(): void
{
$order = new Order('o-1', 'c-1', 'USD');
$order->addLine('sku-1', 1, 100);
$order->place();
$this->assertSame(OrderStatus::Placed, $order->status());
$this->expectException(\DomainException::class);
$order->addLine('sku-2', 1, 100);
}
}<?php
declare(strict_types=1);
namespace Tests\Fakes;
use App\Domain\ConcurrencyConflict;
use App\Domain\Order;
use App\Domain\OrderNotFound;
use App\Domain\OrderRepository;
/** Fake for fast unit tests. It copies state in and out like a database. */
final class InMemoryOrderRepository implements OrderRepository
{
/** @var array<string, array{customerId: string, currency: string, status: \App\Domain\OrderStatus, lines: array, version: int}> */
private array $rows = [];
public function add(Order $order): void
{
$this->rows[$order->id] = $this->snapshot($order, 1);
$order->acceptVersion(1);
}
public function get(string $id): Order
{
$r = $this->rows[$id] ?? throw OrderNotFound::withId($id);
return Order::rehydrate($id, $r['customerId'], $r['currency'], $r['status'], $r['lines'], $r['version']);
}
public function save(Order $order): void
{
$stored = $this->rows[$order->id] ?? throw OrderNotFound::withId($order->id);
if ($stored['version'] !== $order->version()) {
throw ConcurrencyConflict::forOrder($order->id);
}
$this->rows[$order->id] = $this->snapshot($order, $stored['version'] + 1);
$order->acceptVersion($stored['version'] + 1);
}
private function snapshot(Order $o, int $version): array
{
return ['customerId' => $o->customerId, 'currency' => $o->currency,
'status' => $o->status(), 'lines' => $o->lines(), 'version' => $version];
}
}<?php
declare(strict_types=1);
namespace Tests\Contracts;
use App\Domain\ConcurrencyConflict;
use App\Domain\Order;
use App\Domain\OrderNotFound;
use App\Domain\OrderRepository;
/** Shared checks: the fake and the Eloquent adapter must both pass them. */
trait OrderRepositoryContract
{
abstract protected function repository(): OrderRepository;
public function test_round_trip_keeps_the_whole_aggregate(): void
{
$repo = $this->repository();
$order = new Order('o-1', 'c-1', 'USD');
$order->addLine('sku-1', 2, 500);
$order->addLine('sku-2', 1, 250);
$repo->add($order);
$loaded = $repo->get('o-1');
$this->assertSame(1250, $loaded->total()->cents);
$this->assertCount(2, $loaded->lines());
$this->assertSame(1, $loaded->version());
}
public function test_missing_order_throws(): void
{
$this->expectException(OrderNotFound::class);
$this->repository()->get('nope');
}
public function test_second_writer_gets_a_conflict(): void
{
$repo = $this->repository();
$order = new Order('o-2', 'c-1', 'USD');
$order->addLine('sku-1', 1, 100);
$repo->add($order);
$a = $repo->get('o-2');
$b = $repo->get('o-2');
$a->place();
$b->place();
$repo->save($a);
$this->expectException(ConcurrencyConflict::class);
$repo->save($b);
}
}<?php
declare(strict_types=1);
namespace Tests\Unit;
use App\Domain\OrderRepository;
use PHPUnit\Framework\TestCase;
use Tests\Contracts\OrderRepositoryContract;
use Tests\Fakes\InMemoryOrderRepository;
/** Plain PHPUnit: no framework boot, no database, milliseconds. */
final class InMemoryOrderRepositoryTest extends TestCase
{
use OrderRepositoryContract;
protected function repository(): OrderRepository
{
return new InMemoryOrderRepository();
}
}<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Domain\OrderRepository;
use App\Infrastructure\EloquentOrderRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Contracts\OrderRepositoryContract;
use Tests\TestCase;
/** Real database: the same contract, run against Eloquent and the migration. */
final class EloquentOrderRepositoryTest extends TestCase
{
use OrderRepositoryContract;
use RefreshDatabase;
protected function repository(): OrderRepository
{
return new EloquentOrderRepository();
}
}PHP is not installed on the authoring machine, so these files were reviewed, not run. Treat the first php artisan test as part of the lab.
The Laravel angle
Eloquent is an Active Record by design. Laravel's description: "each database table has a corresponding 'Model' that is used to interact with that table." The model is the table's row object, relations are methods that return builders, and save() writes the dirty attributes.
Casts are the mapping layer you already have. The casts() method maps columns to PHP types; backed enums are first-class cast targets; CastsAttributes classes map several columns to one value object (get and set receive $attributes, which is how MoneyCast reads two columns); AsArrayObject and related casts map JSON columns.
Lazy loading is on by default, and you can forbid it. Laravel's documented guard: call Model::preventLazyLoading(! $this->app->isProduction()) in a service provider's boot so development and CI throw when a relation is lazy loaded and production continues to work.
Events and observers are hidden persistence logic. Model events fire from save() and delete(); Laravel's docs say that on a mass update via Eloquent the saving, saved, updating and updated events "will not be fired", so audit code in observers can miss bulk writes; ShouldHandleEventsAfterCommit on an observer defers it until the transaction commits.
Transactions. DB::transaction(fn) commits on return and rolls back on exception; the optional second argument is the number of attempts when a deadlock occurs. Pessimistic locks (sharedLock(), lockForUpdate()) are documented on the query builder and "it is recommended to wrap pessimistic locks within a transaction".
Testing. RefreshDatabase ("will take care of this for you") resets the database between tests. For fast tests of the domain, do not boot Laravel at all: extend PHPUnit\Framework\TestCase.
What Laravel does not give you: optimistic locking, an identity map, a unit of work that tracks aggregates, or a repository. Each is a decision, not a missing feature.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| God model (Active Record with 40 methods) | Extract domain class or Action | Move rules out, keep the model as persistence | Rules testable | Mapping or two classes |
| N+1 from lazy loading | Eager load or read model | with(), Preload, a join query | 1 to 2 queries | Over-fetching if misused |
| Leaky repository | Return aggregates and domain errors only | No query builders in signatures | Storage can change | Repository code grows |
| Repository per table | One per aggregate root | Group tables by invariant | Fewer, meaningful ports | Needs aggregate design |
save() overwrites a concurrent change | Version column | WHERE version = ?, 0 rows = conflict | Detects lost updates | Retry path |
| Transaction opened in five places | Unit of Work in the use case | One closure, one handle | Atomicity is visible | Passing the handle |
| Slow tests that need a database for rules | Persistence-ignorant domain + fake | new Order(), memrepo | Milliseconds | Contract tests to keep the fake honest |
| List screens loading aggregates | DTO read model | One grouped query | Fast, small | A second shape to maintain |
| Two services share a table | Data ownership | API or events, own schema | Independent deploys | Eventual consistency |
| Soft-deleted rows leak | Filter in the repository | deleted_at IS NULL everywhere, partial unique index | One rule | Discipline |
God model
The model has relations, scopes, rules, accessors, notifications and an HTTP-shaped toArray. Split by reason to change (SRP): keep the persistence model, move rules to the aggregate or Action classes, move presentation to API resources, move side effects to listeners fired after commit.
Leaky repository
Signs: a method returns Builder, *gorm.DB or *sql.Rows; callers add ->where(); a findBy(array $criteria) takes column names.
// Leaky: the caller now depends on Eloquent and on column names.
public function query(): \Illuminate\Database\Eloquent\Builder;
// Honest: the question is in domain language, the answer is an aggregate.
/** @return list<Order> */
public function overdueFor(string $customerId, \DateTimeImmutable $now): array;N+1 and its relatives
Detect: Model::preventLazyLoading() in development, query counts in tests, pg_stat_statements in production (Database Observability). Fix by design: aggregates load whole, cross-aggregate display uses a read model. Mechanics and bulk operations: ORM Pitfalls.
Saving the whole aggregate on every change
A repository that deletes and re-inserts all lines on every save is correct but wasteful. If aggregates are large, diff in the repository (insert new, update changed, delete removed) or reconsider the aggregate size. The snippet favours clarity: lines are small and bounded.
-- Diff-style write for large aggregates: only what changed.
INSERT INTO order_lines (order_id, position, sku, qty, unit_cents)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (order_id, position) DO UPDATE
SET sku = EXCLUDED.sku, qty = EXCLUDED.qty, unit_cents = EXCLUDED.unit_cents;
DELETE FROM order_lines WHERE order_id = $1 AND position >= $2; -- trim removed tailChoosing: which persistence design
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| CRUD admin, content, settings | Eloquent Active Record directly | preventLazyLoading, Form Requests | Cheapest correct choice |
| Rich rules, money, bookings, ledgers | Aggregate + repository | Version column, contract tests | Rules testable, concurrency explicit |
| Query-heavy Go service | sqlc + thin repository | Read-model queries, WithTx | Visible SQL, typed |
| Fast CRUD in Go with many small tables | GORM models | Preload, version by hand | Least boilerplate |
| Reporting, exports, dashboards | Read model / SQL view | DTOs, pagination | No aggregates, no rules |
| Legacy schema you cannot change | Data Mapper with anti-corruption | Mapping tests | Domain stays clean |
| Many teams on one codebase | Repository or facade per module | Schema per module, one writer per table | Ownership |
| Microservices | Database per service | Outbox, events, own read models | Independent change |
| Bulk import/export | Table Data Gateway / set-based SQL | COPY, batches | Row-by-row objects too slow |
| Prototype | Whatever is fastest, throw away | None | Do not design for the unknown |
Decision walk
1 Are there domain rules worth fast tests? no -> Active Record, stop
2 yes -> Is the storage shape close to the object? yes -> Active Record + Action classes, revisit later
3 no -> Aggregate + repository (Data Mapper)
4 Do screens read data the aggregates do not shape? yes -> add DTO read models
5 Will another team or service use this data? yes -> public contract (API/events), private tablesIn architecture: from a single process to a distributed system
The same question repeats at every size: who owns this data, and who is allowed to change it?
Monolith: one process, one database
How it shows up: models and queries inside one app; any code can reach any table. The failure is spread: controllers, jobs, and views all call Order::where(...).
Simplest correct usage: Active Record for CRUD parts; for the one or two aggregates with real rules, a repository and a plain domain class; one DB::transaction per use case; read models for list screens.
Everyday example (simple): a blog or an admin app. Post::with('author')->paginate(), StorePostRequest, PublishPost action. No repository; adding one would be ceremony.
Production example (complex): a shop's checkout. PlaceOrder loads the Order aggregate, applies pricing rules, saves with a version check, and writes an OrderPlaced row to an outbox table in the same transaction (Outbox); a relay publishes after commit. The order list page uses OrderSummaryQuery.
Modular monolith and multiple databases
How it shows up: each module owns its tables (a schema per module) and exposes a facade; other modules call the facade, never the tables. Persistence design becomes module design (Modular Monolith).
-- PostgreSQL: one schema and one role per module; others get read-only access to a view at most.
CREATE SCHEMA orders; CREATE SCHEMA billing;
CREATE ROLE orders_app LOGIN; CREATE ROLE billing_app LOGIN;
GRANT USAGE, CREATE ON SCHEMA orders TO orders_app;
GRANT USAGE, CREATE ON SCHEMA billing TO billing_app;
-- billing_app has no privileges on schema orders: it must call the Orders facade. Cross-module read, modular monolith
1 Billing needs the order total
2 billing -> OrdersFacade.totalFor(orderId) -- public interface, returns a DTO
3 OrdersFacade -> OrderSummaryQuery -- reads orders.* tables, inside the Orders module
4 billing never joins orders.order_lines directlyEveryday example: Catalog, Orders, Billing modules in one Laravel app, each with a service provider and CODEOWNERS. Production example: the same split, with a second database connection for the Billing module (separate credentials, DB::connection('billing')), so the split is real before any service exists.
Microservices: persistence with a network boundary
What survives: repositories and aggregates, unchanged. What breaks: joins across services, cross-service transactions, and "just read their table". Richardson's rule: "Keep each microservice's persistent data private to that service and accessible only via its API", with three levels of isolation (private tables, schema per service, database server per service). Fowler's Integration Database page explains why the alternative hurts: a shared schema "has to unify what should be separate BoundedContexts".
Place an order across three services
1 Client -> Orders: POST /orders -- Orders: aggregate saved, version 1, outbox row OrderPlaced (one transaction)
2 Relay -> broker: OrderPlaced -- after commit, at-least-once
3 Billing consumes OrderPlaced (inbox: dedupe by event id) -- creates its invoice in its own DB
4 Billing -> broker: InvoiceCreated
5 Orders consumes InvoiceCreated -- updates Order.status in its own aggregate
6 Reporting consumes all three -- its own denormalised read model, rebuildableData sync and read models. A service that needs another's data keeps a copy it owns, fed by events or change data capture, and treats it as a read model that may be stale. Idempotent handling: Idempotent Consumer & Inbox; coordination: Saga.
Strangler migration of the persistence design. Fowler's Strangler Fig: replace a legacy system gradually, so "investment and returns occur gradually and visibly". Applied to data:
| Step | Action | Data rule |
|---|---|---|
| 1 | Put a facade in front of the module inside the monolith | Others stop reading its tables |
| 2 | Move the module's tables to their own schema, then database | One writer per table |
| 3 | Route new traffic to the new service; old code calls the facade | Dual read, single write |
| 4 | Sync data both ways during the transition (events, CDC, or dual writes behind a flag) | Pick one source of truth per field |
| 5 | Retire the old tables | Backfill, verify, drop |
Anti-corruption layer. When the new service must read a legacy model, translate at the border. Evans: "As a downstream client, create an isolating layer to provide your system with functionality of the upstream system in terms of your own domain model." In persistence terms, the legacy schema gets its own mapper, and the new domain never imports its types.
Everyday example: Orders publishes OrderPlaced; Notifications keeps its own order_contacts copy. Production example: splitting Billing out of a monolith: facade first, schema second, dual-write behind a flag, compare invoices for a month, then switch reads and drop the old tables.
Distributed data: replicas, caches and CQRS
Where it breaks. Read replicas lag, so a repository that reads from a replica right after a write returns stale data (Replication); caches in front of aggregates go stale and hide version conflicts; a repository that spans two databases has no transaction.
| Situation | Rule |
|---|---|
| Read right after write | Read the primary (or pass a consistency token) for the next request |
| Repository on a replica | Only for read models; aggregates load from the primary, because the version check must see the truth |
| Cache in front of reads | Cache read models, invalidate on events, TTL as a safety net |
| Two databases in one use case | Two transactions plus an outbox/saga; never a hidden two-phase commit (distributed SQL) |
| Sharded store | The aggregate id must contain or imply the shard key |
| Multi-region | One writer region per aggregate; conflicts resolved by version or CRDT |
Replica lag and the repository
1 T0 Orders: Save(o-1) on primary, version 5
2 T1 user reloads the page; the query goes to a replica
3 T2 replica still at version 4 -> the page shows the old status
4 T3 user clicks Place again; Get(o-1) from the REPLICA returns version 4; Save with WHERE version = 4 -> 0 rows on the primary
5 Lesson: aggregates load from the primary, read models may use replicasScaling path: 1×, 10×, 100×
| Scale | Persistence design | Practice |
|---|---|---|
| 1× (one team, one app) | Eloquent/GORM models directly; repository only for the rule-heavy aggregate | preventLazyLoading, one transaction per use case |
| 10× (several teams, one repo) | Modular monolith; schema per module; repositories and facades | Contract tests, CODEOWNERS on tables, read models for lists |
| 100× (many teams, many services) | Database per service; events, outbox, inbox; read models as owned copies | Idempotency, versioned events, replay and rebuild tooling |
| Beyond | Sharding, per-tenant stores, polyglot persistence | Aggregate id carries the shard; see Multi-Tenancy and Billion-Row Tables |
Lab: the same Order three ways
You run the Go tests, then compare the Active Record and Repository versions on change cost, test cost and concurrency. Everything in Go runs offline except the optional PostgreSQL run; PHP steps are expected outputs, not executed here (no PHP on the authoring machine).
Setup.
cd docs/snippets/design/data-persistence-design/go
gofmt -l . # no output
go vet ./... # no output
go test ./...Step 1: run the pure and fake tests.
go test -v ./after/domain ./after/memrepo ./after/app ./after/valuer
# --- PASS: TestPlaceNeedsLines
# --- PASS: TestPlacedOrderIsFrozen
# --- PASS: TestMoneyAddRejectsMixedCurrencies
# --- PASS: TestContract/round_trip_keeps_the_whole_aggregate
# --- PASS: TestContract/missing_order_is_ErrNotFound
# --- PASS: TestContract/second_writer_gets_ErrConflict
# --- PASS: TestPlaceOrderCommitsOnSuccess
# --- PASS: TestPlaceOrderRollsBackOnError
# --- PASS: TestAddressRoundTrip
# --- PASS: TestStatusRejectsUnknownStep 2: measure what the domain imports.
go list -f '{{join .Imports " "}}' ./after/domain
# context errors fmt
go list -f '{{join .Imports " "}}' ./before
# context database/sql errorsThe aggregate imports no database package; the Active Record cannot be built without one.
Step 3: break the version check. In memrepo/repo.go, delete the if s.version != o.Version() block. Expected: TestContract/second_writer_gets_ErrConflict fails with err = <nil>, want ErrConflict. This is the lost update in object form. Restore the block.
Step 4: add a field and count the files. Add Notes string to the order. Expected files to touch with the repository design: domain/order.go, schema.sql, query.sql, db/query.sql.go, repo.go. With the Active Record: the struct, the SELECT and the UPDATE in before/order.go. Which design is cheaper depends on how many rules and how many tables you have; the repository wins when the domain changes often and storage rarely, Active Record wins when both change together.
| Metric | Active Record (before) | Repository (after) |
|---|---|---|
Packages needed to test Place() | database/sql and a database | none (plain go test) |
| Where the transaction is chosen | Inside the model's method | In the use case (UnitOfWork) |
| Concurrency control | None | Version check, tested by the contract |
| Files to add a column | 1 | 5 |
| Files to change the storage engine | all callers | 1 adapter |
| Read model for a list screen | Load models | ForCustomer DTO query |
Step 5: swap the adapter. gormrepo.New(gormDB) implements the same domain.Repository. Wire it in a test with the contract (needs a GORM dialector for your database; the module compiles it without one):
// contract.Run(t, func(t *testing.T) domain.Repository { return gormrepo.New(openGorm(t)) })Step 6: run against PostgreSQL (optional).
createdb academy_dpd
DATABASE_URL="postgres://localhost/academy_dpd?sslmode=disable" go test -v ./after/sqlcrepo
# --- PASS: TestContract/round_trip_keeps_the_whole_aggregate
# --- PASS: TestContract/missing_order_is_ErrNotFound
# --- PASS: TestContract/second_writer_gets_ErrConflictEach subtest creates the schema and runs inside a transaction that is rolled back, so the database stays empty. We could not run this step on the authoring machine (no PostgreSQL available); without DATABASE_URL the test prints SKIP.
Step 7 (Laravel). Copy the after/ files into a Laravel 13 app (namespaces as written), run the migration, bind the provider and run the tests.
php artisan migrate
php artisan test --filter=OrderTest # pure: no database
php artisan test --filter=InMemoryOrderRepositoryTest # fake: no database
php artisan test --filter=EloquentOrderRepositoryTest # real DB, RefreshDatabase
# expected: all green; the three contract tests run twice (fake and Eloquent)Step 8 (Laravel): feel the N+1. Call the before/OrderController::index action for a customer with 50 orders with Model::preventLazyLoading() enabled. Expected: an exception naming the lines relation on the first loop iteration. Change $o->lines->count() to $o->loadCount('lines') before the loop, or use OrderSummaryQuery. Expected: 1 query.
Common misconceptions
| Belief | Reality |
|---|---|
| "A repository is a wrapper over the ORM." | It is a domain-language collection of aggregates; a one-to-one wrapper adds nothing |
| "Active Record is an anti-pattern." | It is the cheapest correct pattern for CRUD-shaped features |
| "Using a repository lets me switch databases easily." | Transactions, locking and SQL features leak; the win is testability and one place to change |
| "One repository per table." | One per aggregate root that needs direct access |
| "Lazy loading is a performance feature." | It defers cost and hides N+1; in design, decide per association |
"save() is safe because it is atomic." | One statement is atomic; a use case needs one transaction around all its writes |
| "In-memory SQLite tests are equivalent to production." | Different engine, types, locking and JSON; use the real engine for adapters |
| "An identity map is a cache." | Per-transaction correctness tool, discarded with the unit of work |
| "CQRS means separate databases and events." | The light form is a DTO query on the same tables |
| "Soft delete means privacy is handled." | Soft-deleted data still exists; erasure needs real deletion or anonymisation |
| "Eloquent has optimistic locking." | It does not; add a version column and WHERE version = ? |
| "Services can share a database if they use different tables." | Shared access couples deploys and schema; each service owns its tables and exposes an API or events |
Cheat sheet
| Topic | Remember |
|---|---|
| Persistence ignorance | Domain imports nothing about storage; test rules with new |
| Mismatch | Identity, inheritance, associations, granularity, navigation |
| Active Record | Row object that saves itself; great for CRUD |
| Data Mapper | Separate mapper; domain object has no storage code |
| Gateways | Table: SQL for a table; Row: typed handle per row; neither holds rules |
| Repository | Collection of aggregates in domain language; one per root |
| Aggregate | Load and save whole; reference others by id; one transaction |
| Querying | Finder methods first; Specification for reusable predicates |
| Unit of Work | One use case, one transaction, opened in the application layer |
| Identity Map | One row, one object per unit of work; not a cache |
| Loading | Inside aggregate eager; across aggregates by id or read model |
| Read model | DTO query on the side; never build aggregates for lists |
| Value mapping | Scanner/Valuer in Go; casts in Laravel; reject unknown values |
| Optimistic lock | WHERE version = ?; 0 rows is a conflict |
| Soft delete | Filter in the repository; partial unique indexes; not erasure |
| Testing | Domain pure, fake for use cases, contract on the real engine |
| Services | Database per service; no shared tables; events and read models |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A colleague says "Eloquent already is a repository, so we should not add one." When is that right, and when is it wrong? Must-know
Answer
Answer: Right for CRUD-shaped features with few rules. Wrong when rules deserve fast tests, when the storage shape differs from the object, or when other modules need a stable contract. See Repository over Eloquent.
2 — Name the five mismatches between objects and tables and one tool feature for each. Important
Answer
Answer: Identity (Identity Map, key equality), inheritance (Single/Class/Concrete Table Inheritance), associations (foreign key and association table mapping, relations), granularity (casts, Scanner/Valuer, embedded value, JSON), navigation (eager loading, read models). See Impedance mismatch.
3 — Why should the repository interface live in the domain package instead of next to the ORM? Important
Answer
Answer: Dependency Inversion: the domain defines what it needs; the adapter depends on it. Otherwise the domain imports infrastructure and loses persistence ignorance. See Dependency Inversion.
4 — Two users edit the same order. Using UPDATE ... WHERE version = ?, describe what each user sees. Must-know
Answer
Answer: The first save changes one row and bumps the version. The second matches zero rows, the repository returns a conflict, and the use case reloads or asks the user again. See Optimistic locking.
5 — Where should the transaction start for "place order", and why not in the repository? Must-know
Answer
Answer: In the use case, because only it knows which repository calls belong to one business action. A repository-level transaction would commit each call separately. See Unit of Work.
6 — A list endpoint takes 2 seconds and runs 401 queries. What is the design fix, beyond adding with()? Must-know
Answer
Answer: Use a read model (DTO query) so the list does not construct aggregates; eager loading is the patch, a purpose-built query is the design. See DTOs and read models and ORM Pitfalls.
7 — What belongs inside an aggregate and what is referenced by id? Must-know
Answer
Answer: Objects that must be consistent together in one transaction (an order and its lines) are inside; other aggregates (the customer) are referenced by id and reached through their own repositories. See Aggregate boundary.
8 — Why is an in-memory SQLite database a poor stand-in for PostgreSQL in repository tests? Important
Answer
Answer: Different types, constraints, JSON handling, locking and SQL dialect; the tests check SQLite's behaviour. Use the real engine for adapters and a fake for use cases, with one contract suite for both. See Testing persistence.
9 — Service A needs data owned by service B. List two acceptable ways and one forbidden way. Must-know
Answer
Answer: Acceptable: call B's API; keep an owned copy fed by B's events or CDC. Forbidden: reading B's tables directly (shared database). See Microservices.
10 — What does Model::preventLazyLoading(! $this->app->isProduction()) do, and why is the condition there? Important
Answer
Answer: It throws when a relation is lazy loaded, so N+1 is found in development and CI; in production the app keeps working. See Lazy vs eager.
11 — Why must aggregates be loaded from the primary and not a replica? Important
Answer
Answer: A replica may lag, so the version read there is stale and the version-checked write fails or, worse, decisions are made on old state. Read models may use replicas. See Distributed data.
Glossary
| Term | Meaning |
|---|---|
| Persistence ignorance | Domain objects carry no storage code or storage imports |
| Impedance mismatch | The structural gap between object models and relational schemas |
| Identity | What makes two things the same: key (table) or reference/value (object) |
| Granularity | How finely the object model splits data compared with columns |
| Navigation | Following object references one hop at a time vs joining sets |
| Active Record | An object that wraps a row, holds data access and adds domain logic |
| Data Mapper | A layer that moves data between objects and tables, keeping both independent |
| Table Data Gateway | One object holding all the SQL for a table |
| Row Data Gateway | One object per row, a typed handle without rules |
| Repository | A collection-like interface over the stored aggregates of one type |
| Aggregate | A cluster of objects treated as one unit for consistency and storage |
| Aggregate root | The only member outside objects may reference |
| Specification | An object stating whether a candidate matches a criterion |
| Query Object | An object that represents a database query |
| Unit of Work | Tracks what changed in a business action and commits it together |
| Identity Map | A per-transaction map that ensures one object per row |
| Lazy Load | An object that knows how to fetch its missing data on first use |
| Eager loading | Fetching related data up front with the parent |
| N+1 | One query for the parent plus one per child |
| DTO | Data Transfer Object: a data-only shape carried across a boundary |
| Read model | A query-side shape built for one screen or response |
| CQRS | Using a different model to write than to read |
| Value object | An immutable object compared by value, without identity |
| Embedded Value | Storing a value object in columns of the owner's table |
| Serialized LOB | Storing an object graph as one serialised column (JSON) |
| Single Table Inheritance | A hierarchy in one table with a discriminator |
| Class Table Inheritance | One table per class in the hierarchy |
sql.Scanner | Go interface to read a database value into a type |
driver.Valuer | Go interface to turn a type into a database value |
| Cast | Eloquent's declared conversion between column and PHP type |
| Optimistic locking | Detecting concurrent edits with a version, failing the later write |
| Soft delete | Marking a row deleted instead of removing it |
| Audit trail | A record of who changed what and when |
| Persistence model | A storage-shaped class (Eloquent model, GORM struct) used inside the adapter |
| Contract test | A test suite every implementation of a port must pass |
| Transactional test | A test that runs in a transaction rolled back at the end |
| Database per service | Each service owns its data store, accessed only via its API |
| Integration database | One schema shared by several applications |
| Strangler Fig | Gradually replacing a legacy system around its edges |
| Anti-corruption layer | A translation layer protecting a domain from a foreign model |
| Outbox | A table written in the same transaction as the state change, relayed to a broker |
| Change data capture (CDC) | Streaming committed row changes from the database log |
| Dirty checking | Detecting which fields of a loaded object changed |
References
- Martin Fowler et al., Patterns of Enterprise Application Architecture catalog: Repository (Edward Hieatt, Rob Mee), Data Mapper, Active Record, Table Data Gateway, Row Data Gateway, Unit of Work, Identity Map, Lazy Load, Query Object, Data Transfer Object, Single Table Inheritance, Class Table Inheritance, Embedded Value, Serialized LOB, Foreign Key Mapping, Optimistic Offline Lock (David Rice). Catalog summaries only; the book chapters were not read.
- Martin Fowler, OrmHate, 8 May 2012; DDD Aggregate, 23 April 2013; CQRS; Integration Database, 25 May 2004; Strangler Fig, 22 August 2024.
- Eric Evans, Domain-Driven Design Reference (2015): Aggregates, Repositories, Anticorruption Layer.
- Eric Evans and Martin Fowler, Specifications.
- Scott Ambler, Mapping Objects to Relational Databases; Wikipedia, Object-relational impedance mismatch (secondary source).
- Chris Richardson, Database per service, CQRS, Aggregate.
- Laravel 13: Eloquent, Mutators & Casting, Relationships, Database, Query Builder, Database Testing.
- Doctrine ORM: Working with objects, Architecture.
- Go: database/sql, database/sql/driver, Executing transactions.
- sqlc: docs, Using transactions, Query annotations, Overrides.
- GORM: Guides, Models, Preload, Transactions, Delete (soft delete), Update, Data types.
- ent: Getting started, Eager loading, Transactions.
- Related chapters: ORM Pitfalls, Optimistic vs Pessimistic Locking, Repositories, Aggregates & Factories, Data Ownership in Microservices, Outbox.