Lesson 5 of 9 · 27m
Fluent Queries, Relationships, and Transactions
Query with tenant boundaries, load relationships without N+1 surprises, enforce uniqueness at the database, and use transactions only around real invariants.
I once reviewed a project list that issued one query for projects, then two more per project for owner and counts. Ten rows felt instant. Five thousand rows became a self-inflicted denial-of-service. ORMs do not remove query cost; they make cost easier to hide.
Tenant scope belongs in the query
let project = try await Project.query(on: req.db)
.filter(\.$id == projectID)
.filter(\.$tenantID == user.tenantID)
.first()
guard let project else {
throw Abort(.notFound)
}Fetching by ID and comparing later is easier to misuse. Query-level scoping composes across reads, updates, deletes, joins, and counts.
Relationships need loading decisions
let projects = try await Project.query(on: req.db)
.filter(\.$tenantID == user.tenantID)
.with(\.$owner)
.range(..<100)
.all()Do not loop over models and casually touch unloaded relationships. Count queries in integration tests or inspect database logs. Eager loading everything is also waste; load what the response actually uses.
Filtering and sorting are trust boundaries
Whitelist sortable fields and cap pagination:
enum ProjectSort: String {
case createdAt = "created_at"
case name
}
let sort = ProjectSort(rawValue: query.sort ?? "") ?? .createdAtNever interpolate client-controlled sort strings into SQL. An enum at the boundary turns injection into a non-event.
Transactions protect invariants
try await req.db.transaction { db in
let project = Project(tenantID: user.tenantID, name: input.name)
try await project.save(on: db)
let membership = ProjectMembership(projectID: try project.requireID(), userID: user.id, role: .owner)
try await membership.save(on: db)
}If membership creation fails after project creation outside a transaction, the user owns an unadministrable object. Transactions do not roll back emails, card charges, or object-storage writes.
Constraint violations are domain outcomes
Uniqueness belongs in PostgreSQL because concurrent creates race. Catch the driver's unique-violation error and return a stable conflict response; verify the exact error type in integration tests because it varies by driver version.
Field notes
- Query count scales with rows and users, not with how elegant the Swift looks.
- Keep transactions short; open network calls inside them hold database resources hostage.
nilfromfirst()can mean absent, forbidden, or outside scope. Choose response semantics deliberately.- Test concurrent creation of the same unique object; sequential tests cannot prove correctness.
Was this lesson helpful?