Skip to content

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 forGo to
The whole chapter in a few tablesEverything in one minute
Why persistence needs design at allWhy it exists
Fowler, Evans, the ORM debateWhere it comes from
Domain objects that know nothing about storagePersistence ignorance
Why objects and tables do not fitImpedance mismatch
Eloquent, Rails-style modelsActive Record
Doctrine, hand-written mappers, sqlc adaptersData Mapper, Gateways
A collection-like interface for aggregatesRepository, Aggregate boundary
Finder methods, Specification, Query ObjectQuerying through a repository
"Do I wrap Eloquent in a repository?"Repository over Eloquent
Who opens and closes the transactionUnit of Work
Same row, one object; cache in frontIdentity Map and caching
Load now or load laterLazy vs eager loading
Screens and reports without aggregatesDTOs and read models
Money, enums, addresses, JSON columnsMapping value objects
Lost updates in the object layerOptimistic locking
deleted_at, who-changed-whatSoft deletes and auditing
Fakes, real databases, rollback testsTesting persistence
How Eloquent, GORM, sqlc, ent, Doctrine comparePer-language and per-framework view
Dirty checking, emitted SQL, knobsMechanics
Code: Order in Go and LaravelGo, Laravel
Classic problems with fixesSolving the classic problems
Which pattern for which situationChoosing
Monolith to microservices, strangler, data syncIn architecture
Run the tests and break thingsLab
Wrong beliefs, cheat sheet, questions, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concepts section.

TermIn plain wordsTiny exampleWhat goes wrong without it
Persistence ignoranceDomain objects do not know how or where they are storedOrder::place() has no SQL and no save()Rules cannot be tested without a database
Impedance mismatchObjects and tables model data differentlyAn Order holds a list of lines; a table holds one flat row per lineMapping code grows and leaks into the domain
Active RecordOne object wraps one row and saves itself$order->save() in EloquentRules, SQL and framework in one class
Data MapperA separate layer moves data between objects and tablesDoctrine EntityManager, a hand-written mapperMore code up front, more classes
Table / Row Data GatewayOne object holds the SQL of a table, or of a rowOrderTable::find($id)Duplicated SQL everywhere
RepositoryA collection-like facade over storage for one aggregateorders.Get(ctx, id)Query code scattered across the app
AggregateA cluster of objects saved and locked as one unitOrder + its OrderLine rowsHalf-saved invariants, huge locks
Specification / Query ObjectA reusable statement of "which objects"OverdueOrdersFinder-method explosion
Unit of WorkTracks changes and commits them togetherOne DB::transaction per use casePartial writes, chatty commits
Identity MapOne row, one object, per business transactionTwo find(7) calls return the same instanceTwo copies edited, one silently lost
Lazy / eager loadingLoad related data on first use, or up front$order->lines vs with('lines')N+1 queries or giant joins
DTO / read modelA data-only shape for one screen or responseOrderSummaryAggregates loaded to show a list
Optimistic lockA version number detects concurrent editsUPDATE ... WHERE version = ?Lost updates, no error
Soft deleteMark a row deleted instead of removing itdeleted_atGhost rows leak into queries
Database per serviceEach service owns its tables, nobody else reads themorders DB vs billing DBA shared schema nobody can change

The four ways to put an object next to a table (Fowler's catalog, details in the concepts):

PatternWho knows SQLWhere business rules liveTypical toolsBest when
Active RecordThe domain object itselfSame class as the SQLEloquent, Rails Active RecordRules are simple, tables and objects look alike
Data MapperA separate mapperA pure domain classDoctrine, Hibernate, hand-written mappersRich domain, schema and model differ
Table Data GatewayOne gateway per tableElsewhere (transaction scripts)OrderTable classes, Queries struct from sqlcMostly queries, few rules
Row Data GatewayOne gateway object per rowElsewhereGenerated row classesRows exposed as typed objects without rules

Where each idea lives in your tools.

LevelGoLaravel
Row mappingrows.Scan, sqlc structs, GORM modelsEloquent models, query builder stdClass rows
RepositoryInterface in the domain package, adapter next to the driverInterface in the domain namespace, Eloquent adapter in Infrastructure
Unit of Workdb.BeginTx plus a closure; gorm.DB.TransactionDB::transaction(fn)
Identity MapNot built in; per-request map if you want oneNot built in (Doctrine has one; Eloquent does not)
Lazy loadingRare; you call Preload or a second queryDefault for relations; Model::preventLazyLoading()
Value mappingsql.Scanner and driver.ValuerAttribute casts, CastsAttributes, enum casts
Soft deleteGORM gorm.DeletedAt; hand-written deleted_at IS NULLSoftDeletes trait
Optimistic lockWHERE version = $n plus RowsAffectedwhere('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 codePersistence behind a boundary
Fewest classes, fastest first featureMore classes, more names, a mapping layer
Any layer can query any tableOnly repositories and read models touch tables
Rules testable only with a databaseRules testable with plain objects
Schema change touches controllers, jobs, viewsSchema change touches one adapter
Transactions open wherever someone rememberedOne use case, one transaction
Risk: god model, N+1, shared tablesRisk: ceremony, anemic repositories, premature layers
Use case / controllerOrder (Active Record model)fields = columnsbusiness rules: place(), total()persistence: save(), find(), delete()one class, three reasons to changeDatabase: orders, order_linesUse case / application serviceOrderpure rulesno SQL, no frameworkRepositoryadd / get / saveport owned by domainMapper / adapterrows <-> aggregateDatabase: orders, order_linescalls model directlymodel runs its own SQLDoctrine, Hibernate, hand-written mappers, sqlc repositoriesEloquent, Rails Active Record

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 ​

  1. "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).
  2. "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.
  3. "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.

text
     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, RefreshDatabase

Real 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.

WhereWhat persistence ignorance costsWhat it buys
GoA Rehydrate constructor and a repository interfaceDomain tests with go test, no driver
LaravelA plain PHP class next to the Eloquent model, plus mappingUnit tests with PHPUnit\Framework\TestCase, no app boot
BothMapping code, two representationsOne place where storage changes
go
// 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
php
// 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:

DifferenceObjectsTablesWhat goes wrongCommon mappingGo / Laravel handling
IdentityTwo references are the same object (==), or equal by valueIdentity is the primary key; two rows with equal values are two rowsTwo copies of one row, divergent editsIdentity Map, key equality, value objects without identityGo compares ids; Doctrine has an Identity Map; Eloquent returns new instances per query
InheritanceSubclasses, polymorphismNo inheritanceWhich table holds which classSingle Table Inheritance, Class Table Inheritance, Concrete Table InheritanceNeither Eloquent nor GORM maps class inheritance for you (Eloquent's polymorphic relations are about associations, not subclasses); prefer composition and a type column
AssociationsReference fields, collections, both directionsForeign keys, one direction, join tablesCycles, ownership unclearForeign Key Mapping, Association Table MappingEloquent hasMany/belongsToMany; GORM tags; sqlc leaves it to your joins
GranularityMany small classes (Money, Address)Few wide tablesOne object, several columns, or several objects, one columnEmbedded Value, Serialized LOB (JSON)Casts, Scanner/Valuer, JSON columns
NavigationFollow references one hop at a timeJoin sets of rows at onceN+1: one query per hopEager loading, explicit queries, read modelswith(), Preload, joins in sqlc
BehaviourMethodsData onlygetTotalTax() mapped to a columnKeep behaviour in the object, store inputsCompute in domain, store the facts
Types and nullRich types, enumsColumn types, NULLSilent coercionCustom typesValuer 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.

text
     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 total

Real 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:

sql
-- 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
// 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)
}
php
// 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.

text
     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 one

Real 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.

StrengthCost
Least code to a working featureThe class has three reasons to change (rules, SQL, framework)
Relations, casts, scopes, events includedRules testable only with a database, or with heavy mocking
Great tooling and a huge communityThe table shape leaks into the API shape
Obvious where to lookAnything 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.

text
     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 transaction

Real 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.

StrengthCost
Domain tests need no databaseTwo models to keep in sync (domain and persistence)
Schema can change without touching rulesMore files, more names
Loading rules for the aggregate are in one placeEasy 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."

text
     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 methods

Real 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).

PatternUnitHolds rules?Go exampleLaravel example
Table Data GatewayOne object per tableNosqlc QueriesA class around DB::table('orders')
Row Data GatewayOne object per rowNosqlc row structsstdClass rows from the query builder
Active RecordOne object per rowYesGORM model with methodsEloquent 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.

text
     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 handle

Real scenario: OrderRepository, AccountRepository, BookingRepository: each loads and stores one aggregate and knows its invariants and its locking strategy.

Repository design choiceGoodBad
Interface placementIn the domain package (DIP)In the infrastructure package next to the ORM
Return typeAggregate (*domain.Order)ORM model, query builder, *sql.Rows
Method namesByCustomerOverdue, NextToShipFindBy(field, value)
GranularityOne per aggregate rootOne per table
ErrorsDomain errors (ErrNotFound, ErrConflict)Raw driver errors
Collection feelAdd, Get, SaveInsert, 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
// 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
}
php
// 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."

Use caseone transactionOrder aggregate: one consistency boundaryOrder (root)status, place(), total()Moneyvalue object, no idOrderLine 1..nno repository of its ownAddressvalue object (JSON)invariant: total = sum(lines); lines frozen after place()Customer aggregateseparate boundary,referenced by customer_idonlyOrderRepository (one per aggregate root)add / get / save whole aggregate, version checkRead model / DTOlist screens, reportsTablesorders, order_lines
text
     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 cluster

Real 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.

QuestionInside the aggregateAcross aggregates
ConsistencyImmediate, one transactionEventual (events, outbox)
ReferencesObjectsIds
LockingOne version column on the rootOne per aggregate
RepositoryThe root'sSeparate
Typical bugAggregate too big: contention, slow loadsAggregate 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.

TechniqueWhat it isSourceGood forCost
Finder methodsOne named method per questionEvans: criteria meaningful to domain expertsA handful of stable queriesMethod explosion, boolean flag parameters
SpecificationAn object that states whether a candidate matches; can be combined with AND, OR, NOTEvans and Fowler, SpecificationsReusable business predicates; validation and selectionTwo backends (SQL and in-memory) can drift
Query ObjectAn object representing a query, built from class and field namesFowler: "An object that represents a database query"Ad-hoc, user-built filtersInterpreter 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."

text
     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 growing

Real 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".

go
// 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
}
php
// 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.

PositionArgumentStrongest when
Do not wrapEloquent 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 aggregateDomain rules stay testable and persistence-ignorant; one place for locking, mapping and transactionsRich rules, long-lived product, several bounded contexts
Wrap only the awkward partsQuery objects or action classes for the 10 complex queries; models elsewhereMost real Laravel apps
text
     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 ceremony

Real 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 askIf yesIf no
Do domain rules exist that deserve fast tests?Repository + plain domainEloquent directly
Will the storage shape differ from the object shape?Mapper in a repositoryEloquent model is the object
Is there more than one way to load this thing?Repository with named methodsPlain scopes
Will other modules use this data?Facade or repository as the public contractInternal 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:

ShapeHowExamples
Tracked Unit of WorkThe ORM watches objects, computes changes, flushes at the endDoctrine EntityManager::flush(); GORM is not tracking (explicit calls)
Scoped transactionYou open a transaction, run the use case, commitDB::transaction(fn), Go BeginTx + closure
text
     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 transaction

Real 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 questionRecommended 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
// 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()
}
php
// 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.

text
     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 once

Real 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.

LayerScopeInvalidationWhere
Identity MapOne unit of workDies with itDoctrine; hand-written per request in Go
Request-level memoOne requestDies with itA map[OrderID]*Order inside the UoW
Application cacheProcess or sharedExplicit, hardCache::remember, Redis
Database cacheEngineEngineBuffer 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.

StrategyWhen it loadsQueries for 50 orders + linesRisk
LazyOn first access of each relation1 + 50N+1, hidden I/O, access after the connection closed
Eager (with, Preload, ent WithX)With the parent2Over-fetching if unused
JoinIn one statement1Row multiplication, big result
Read modelA purpose-built query1Another thing to maintain
text
     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 query

Real 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."

text
     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 Order

Real scenario: list screens, dashboards, exports, search results, API collection endpoints; anything the user reads more often than writes.

LevelWhat you doConsistencyCost
LightDTO query on the same tablesImmediateAlmost none
MediumA SQL view or materialized viewAs fresh as the refreshRefresh jobs
HeavySeparate store fed by events (see CQRS & event sourcing)EventualProjectors, rebuilds, monitoring
sql
-- 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):

ValueColumn strategyGoLaravel
MoneyTwo columns (total_cents, currency)Fields on the adapter struct; domain Money built in the mapperCastsAttributes over two columns (MoneyCast)
AddressOne JSONB column, or several columnsType implementing driver.Valuer and sql.ScannerAsArrayObject/custom cast, or an Address cast
Status enumtext + CHECK, or a native enum typeType with Scan that rejects unknown valuesBacked enum cast (OrderStatus::class)
Tags / settingsjsonb[]byte or json.RawMessage, or a typed ValuerAsArrayObject, AsCollection, array cast
Idtext/uuid/bigintNamed type OrderIDTyped id in domain, string in the model
text
     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 default

Real 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
// 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)
	}
}
php
// 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.

text
     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 user

Real 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.

TechniqueDetectsCostUse when
Version column + WHERE version = ?Any concurrent write to the aggregateA retry pathEdits spanning requests, low conflict
updated_at compareConcurrent write (coarse, clock-resolution)FragileQuick CRUD forms
SELECT ... FOR UPDATEPrevents it by waitingHeld locks, deadlocksShort, high-conflict transactions
Atomic update (balance = balance - ?)Nothing neededNoneCounters, stock
sql
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"
go
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
}
php
$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.

ConcernTypical mechanismPitfalls
Soft deletedeleted_at timestampUnique constraints (email reused), joins that forget the filter, cascades
Auditing: who/whencreated_by, updated_by, timestampsBackground jobs have no user
Auditing: what changedAppend-only history table, event log, or database triggerVolume, PII retention
Event log as truthEvent sourcingA different architecture; see event sourcing
text
     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 erasure

Real 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.

sql
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.

TestSubjectSpeedCatches
Domain unit testOrder rules, no I/OmicrosecondsRule bugs
Use case test with an in-memory fakePlaceOrder with memrepomicrosecondsOrchestration bugs, rollback behaviour
Repository contract testFake and real adapter run the same suitemillisecondsFake drift, mapping bugs, version check
Adapter test on the real engineSQL, constraints, indexes, JSONmilliseconds each, seconds per suiteWrong SQL, wrong types
End-to-end through HTTPWhole sliceslowerWiring
text
     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 together

Real 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 techniqueHowNotes
Transaction per test, rollback at the endBegin before, Rollback in cleanupFast; cannot test commit behaviour; the Go test in the snippets does this
Truncate / refresh between testsLaravel RefreshDatabase ("take care of this for you")Simple; slower
Fresh schema per packageContainer per suiteSlowest, most isolated
go
// 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() })
}
php
// 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.

ToolClosest patternUnit of WorkIdentity MapLazy loadingOptimistic lockSoft deleteSource
Eloquent (Laravel 13)Active RecordNo tracking; save() per model, you wrap DB::transactionNoDefault for relations; preventLazyLoading()Not built in; write where('version', $n)SoftDeletes traitLaravel docs
Doctrine ORM (PHP)Data MapperYes, EntityManager, flush()Yes, "per PHP request"Not covered in the pages we readNot covered in the pages we readNot covered in the pages we readDoctrine 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 transactionNoNo; Preload for eager loadingNot in core; Where("version = ?")gorm.DeletedAtGORM docs
sqlc (Go)Table Data Gateway over generated SQLQueries.WithTx(tx)NoNone: you write each queryHand-written WHERE version with :execrowsHand-written deleted_at IS NULLsqlc docs
ent (Go)Generated entity graph with a clientHas a transactions page (not read in detail)NoEager WithX() edgesNot in the part we readNot in the part we readent docs
database/sql + pgx (Go)Raw gatewayBeginTx, *sql.TxNoNoneBy handBy handdatabase/sql docs
Query builder (DB::table)Table Data Gateway, rows as stdClassDB::transactionNoNoneBy handBy handLaravel docs
PostgreSQL, MySQL/InnoDB, SQL Server, OracleStorage engines under all of the aboveTransactions, locks, MVCCn/an/aRow version via your columnn/aSee Databases
SQLite, MongoDB, Redis, CockroachDBOther stores a repository adapter may targetVaries (MongoDB multi-document transactions, CockroachDB serializable)n/an/aMongoDB: version field by handn/aSee 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.

ToolHow it knows what changedSQL emitted on saveFailure mode
EloquentCompares attributes with originals (isDirty())UPDATE ... SET changed columnsTwo writers on different columns both succeed; same column: last wins
DoctrineUnit of Work snapshots entities at load, diffs at flush()One batch in one transactionLarge unit of work is slow and memory-hungry
GORM SaveNo tracking; writes all fieldsUPDATE ... SET every columnOverwrites a concurrent change to any column
GORM Updates with a map or structOnly the given fields (non-zero for structs)UPDATE ... SET givenZero values silently skipped when using structs
sqlcYou choose the statementExactly your SQLForgetting a column in a hand-written UPDATE
Repository with versioningWhole aggregate, one versionUPDATE ... WHERE version + rewrite childrenChildren rewritten (delete + insert) even if unchanged
text
     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 retries

Transaction mechanics in the object layer Important ​

ConcernGo (database/sql)Laravel
Poolsql.DB is "a database handle representing a pool of zero or more underlying connections", safe for concurrent useConnection per request/worker; see Connection Pooling
Begindb.BeginTx(ctx, &sql.TxOptions{Isolation:..., ReadOnly:...})DB::transaction(fn, attempts) or beginTransaction()
Commit/rollbacktx.Commit() / tx.Rollback(); sql.ErrTxDone after eitherAutomatic on closure return or exception
Contextctx cancels the query and rolls back an open transactionRequest timeouts, not context
RetryYou write it (40001, 40P01)attempts: argument, documented under "Handling Deadlocks"
NestedPass the same *sql.Tx; there is no nestingDB::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 commitYou call the publisher after Commit()ShouldHandleEventsAfterCommit on observers; outbox row for messages

Errors you map in the repository Important ​

SourceRaw errorDomain meaningRetry?
database/sqlsql.ErrNoRowsErrNotFoundNo
EloquentModelNotFoundException from findOrFailOrderNotFoundNo
PostgreSQLSQLSTATE 23505 unique_violationAlreadyExists / business duplicateNo
PostgreSQLSQLSTATE 23503 foreign_key_violationReference to a missing aggregateNo
PostgreSQLSQLSTATE 40001 serialization_failureRetry the whole unit of workYes
PostgreSQLSQLSTATE 40P01 deadlock_detectedRetry the whole unit of workYes
MySQL/InnoDB1062 duplicate key, 1213 deadlock, 1205 lock wait timeoutAs above1213, 1205: yes
Version check0 rows affectedErrConflict / ConcurrencyConflictAfter 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 ​

KnobToolEffect
Model::preventLazyLoading(! $this->app->isProduction())EloquentException on lazy load outside production
Model::preventSilentlyDiscardingAttributes()EloquentException when a non-fillable attribute is dropped (listed in the docs index)
DB::transaction($cb, attempts: 3)LaravelRetry on deadlock
SkipDefaultTransaction: trueGORM gorm.ConfigDisable the implicit per-write transaction ("30%+ performance improvement" per GORM docs)
db.SetMaxOpenConns, SetMaxIdleConnsdatabase/sqlPool size; see Connection Pooling
emit_interface, sql_packagesqlc sqlc.yamlGenerate a Querier interface, choose database/sql or pgx
OverridessqlcMap 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.

go
// 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.

go
// 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.

go
// 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.

sql
-- 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;
sql
-- 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;
yaml
version: "2"
sql:
  - engine: "postgresql"
    schema: "schema.sql"
    queries: "query.sql"
    gen:
      go:
        package: "db"
        out: "db"
        sql_package: "database/sql"
go
// 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} }
go
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()
}
go
// 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.

go
// 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.

go
// 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.

go
// 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.

go
// 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.

go
// 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)
		}
	})
}
go
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.

QuestionsqlcGORMent
Where does SQL live?In .sql files you writeGenerated by the library from method chainsGenerated by the library from a schema graph
What is the model type?A struct per query/table, generatedYour struct with tagsGenerated entities
Compile-time checksQueries checked against the schema at generate timeFew; errors at runtimeStrong: typed predicates
Eager loadingWrite the join or a second queryPreloadWithX edges
Value typesOverrides in sqlc.yamlScanner/ValuerField types and custom Go types
Best forQuery-heavy services that want visible SQLFast CRUD, many small modelsGraph-shaped domains
Domain isolationYou map rows to the domainYou map models to the domain, or use models as the domainYou 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
<?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
<?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
<?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
<?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
<?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
<?php

declare(strict_types=1);

namespace App\Domain;

enum OrderStatus: string
{
    case Draft = 'draft';
    case Placed = 'placed';
    case Cancelled = 'cancelled';
}
php
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 ​

ProblemSolutionHowAdvantageCost / limitation
God model (Active Record with 40 methods)Extract domain class or ActionMove rules out, keep the model as persistenceRules testableMapping or two classes
N+1 from lazy loadingEager load or read modelwith(), Preload, a join query1 to 2 queriesOver-fetching if misused
Leaky repositoryReturn aggregates and domain errors onlyNo query builders in signaturesStorage can changeRepository code grows
Repository per tableOne per aggregate rootGroup tables by invariantFewer, meaningful portsNeeds aggregate design
save() overwrites a concurrent changeVersion columnWHERE version = ?, 0 rows = conflictDetects lost updatesRetry path
Transaction opened in five placesUnit of Work in the use caseOne closure, one handleAtomicity is visiblePassing the handle
Slow tests that need a database for rulesPersistence-ignorant domain + fakenew Order(), memrepoMillisecondsContract tests to keep the fake honest
List screens loading aggregatesDTO read modelOne grouped queryFast, smallA second shape to maintain
Two services share a tableData ownershipAPI or events, own schemaIndependent deploysEventual consistency
Soft-deleted rows leakFilter in the repositorydeleted_at IS NULL everywhere, partial unique indexOne ruleDiscipline

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.

php
// 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.

sql
-- 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 tail

Choosing: which persistence design ​

SituationRecommendedExtra techniqueReason
CRUD admin, content, settingsEloquent Active Record directlypreventLazyLoading, Form RequestsCheapest correct choice
Rich rules, money, bookings, ledgersAggregate + repositoryVersion column, contract testsRules testable, concurrency explicit
Query-heavy Go servicesqlc + thin repositoryRead-model queries, WithTxVisible SQL, typed
Fast CRUD in Go with many small tablesGORM modelsPreload, version by handLeast boilerplate
Reporting, exports, dashboardsRead model / SQL viewDTOs, paginationNo aggregates, no rules
Legacy schema you cannot changeData Mapper with anti-corruptionMapping testsDomain stays clean
Many teams on one codebaseRepository or facade per moduleSchema per module, one writer per tableOwnership
MicroservicesDatabase per serviceOutbox, events, own read modelsIndependent change
Bulk import/exportTable Data Gateway / set-based SQLCOPY, batchesRow-by-row objects too slow
PrototypeWhatever is fastest, throw awayNoneDo not design for the unknown
text
     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 tables

In 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).

sql
-- 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.
text
     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 directly

Everyday 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".

Orders serviceowns the Order aggregateBilling serviceowns invoices, paymentsCatalog serviceowns products, pricesorders DBprivate schemabilling DBprivate schemacatalog DBprivate schemasync APIAPI / eventforbidden: reading anotherservice's tablesReporting serviceread model built from events(outbox + consumer, or CDC)reporting DBdenormalised, rebuildabledotted = events: OrderPlaced,PriceChanged, InvoicePaid
text
     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, rebuildable

Data 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:

StepActionData rule
1Put a facade in front of the module inside the monolithOthers stop reading its tables
2Move the module's tables to their own schema, then databaseOne writer per table
3Route new traffic to the new service; old code calls the facadeDual read, single write
4Sync data both ways during the transition (events, CDC, or dual writes behind a flag)Pick one source of truth per field
5Retire the old tablesBackfill, 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.

SituationRule
Read right after writeRead the primary (or pass a consistency token) for the next request
Repository on a replicaOnly for read models; aggregates load from the primary, because the version check must see the truth
Cache in front of readsCache read models, invalidate on events, TTL as a safety net
Two databases in one use caseTwo transactions plus an outbox/saga; never a hidden two-phase commit (distributed SQL)
Sharded storeThe aggregate id must contain or imply the shard key
Multi-regionOne writer region per aggregate; conflicts resolved by version or CRDT
text
     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 replicas

Scaling path: 1×, 10×, 100× ​

ScalePersistence designPractice
1× (one team, one app)Eloquent/GORM models directly; repository only for the rule-heavy aggregatepreventLazyLoading, one transaction per use case
10× (several teams, one repo)Modular monolith; schema per module; repositories and facadesContract tests, CODEOWNERS on tables, read models for lists
100× (many teams, many services)Database per service; events, outbox, inbox; read models as owned copiesIdempotency, versioned events, replay and rebuild tooling
BeyondSharding, per-tenant stores, polyglot persistenceAggregate 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.

bash
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.

bash
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: TestStatusRejectsUnknown

Step 2: measure what the domain imports.

bash
go list -f '{{join .Imports " "}}' ./after/domain
# context errors fmt
go list -f '{{join .Imports " "}}' ./before
# context database/sql errors

The 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.

MetricActive Record (before)Repository (after)
Packages needed to test Place()database/sql and a databasenone (plain go test)
Where the transaction is chosenInside the model's methodIn the use case (UnitOfWork)
Concurrency controlNoneVersion check, tested by the contract
Files to add a column15
Files to change the storage engineall callers1 adapter
Read model for a list screenLoad modelsForCustomer 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):

go
// contract.Run(t, func(t *testing.T) domain.Repository { return gormrepo.New(openGorm(t)) })

Step 6: run against PostgreSQL (optional).

bash
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_ErrConflict

Each 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.

bash
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 ​

BeliefReality
"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 ​

TopicRemember
Persistence ignoranceDomain imports nothing about storage; test rules with new
MismatchIdentity, inheritance, associations, granularity, navigation
Active RecordRow object that saves itself; great for CRUD
Data MapperSeparate mapper; domain object has no storage code
GatewaysTable: SQL for a table; Row: typed handle per row; neither holds rules
RepositoryCollection of aggregates in domain language; one per root
AggregateLoad and save whole; reference others by id; one transaction
QueryingFinder methods first; Specification for reusable predicates
Unit of WorkOne use case, one transaction, opened in the application layer
Identity MapOne row, one object per unit of work; not a cache
LoadingInside aggregate eager; across aggregates by id or read model
Read modelDTO query on the side; never build aggregates for lists
Value mappingScanner/Valuer in Go; casts in Laravel; reject unknown values
Optimistic lockWHERE version = ?; 0 rows is a conflict
Soft deleteFilter in the repository; partial unique indexes; not erasure
TestingDomain pure, fake for use cases, contract on the real engine
ServicesDatabase per service; no shared tables; events and read models

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Persistence ignoranceDomain objects carry no storage code or storage imports
Impedance mismatchThe structural gap between object models and relational schemas
IdentityWhat makes two things the same: key (table) or reference/value (object)
GranularityHow finely the object model splits data compared with columns
NavigationFollowing object references one hop at a time vs joining sets
Active RecordAn object that wraps a row, holds data access and adds domain logic
Data MapperA layer that moves data between objects and tables, keeping both independent
Table Data GatewayOne object holding all the SQL for a table
Row Data GatewayOne object per row, a typed handle without rules
RepositoryA collection-like interface over the stored aggregates of one type
AggregateA cluster of objects treated as one unit for consistency and storage
Aggregate rootThe only member outside objects may reference
SpecificationAn object stating whether a candidate matches a criterion
Query ObjectAn object that represents a database query
Unit of WorkTracks what changed in a business action and commits it together
Identity MapA per-transaction map that ensures one object per row
Lazy LoadAn object that knows how to fetch its missing data on first use
Eager loadingFetching related data up front with the parent
N+1One query for the parent plus one per child
DTOData Transfer Object: a data-only shape carried across a boundary
Read modelA query-side shape built for one screen or response
CQRSUsing a different model to write than to read
Value objectAn immutable object compared by value, without identity
Embedded ValueStoring a value object in columns of the owner's table
Serialized LOBStoring an object graph as one serialised column (JSON)
Single Table InheritanceA hierarchy in one table with a discriminator
Class Table InheritanceOne table per class in the hierarchy
sql.ScannerGo interface to read a database value into a type
driver.ValuerGo interface to turn a type into a database value
CastEloquent's declared conversion between column and PHP type
Optimistic lockingDetecting concurrent edits with a version, failing the later write
Soft deleteMarking a row deleted instead of removing it
Audit trailA record of who changed what and when
Persistence modelA storage-shaped class (Eloquent model, GORM struct) used inside the adapter
Contract testA test suite every implementation of a port must pass
Transactional testA test that runs in a transaction rolled back at the end
Database per serviceEach service owns its data store, accessed only via its API
Integration databaseOne schema shared by several applications
Strangler FigGradually replacing a legacy system around its edges
Anti-corruption layerA translation layer protecting a domain from a foreign model
OutboxA 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 checkingDetecting which fields of a loaded object changed

References ​

Built by Morteza Negahi