@ddd-ts-kit/drizzle 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.fr.md +940 -0
- package/README.md +400 -52
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
**English** · [Français](README.fr.md)
|
|
2
|
+
|
|
1
3
|
# @ddd-ts-kit/drizzle
|
|
2
4
|
|
|
3
5
|
Drizzle adapters of the kernel and events ports on PostgreSQL: a unit of work that
|
|
@@ -13,13 +15,28 @@ npm i @ddd-ts-kit/drizzle drizzle-orm
|
|
|
13
15
|
Works with every drizzle PostgreSQL driver (node-postgres, postgres-js, PGlite, Neon): the
|
|
14
16
|
functions are generic over the database type, so `executor()` is typed exactly like your `db`.
|
|
15
17
|
|
|
18
|
+
## Where it sits in an application
|
|
19
|
+
|
|
20
|
+
Nothing here is imported from `domain/` or `application/`. A handler depends on the repository
|
|
21
|
+
port of its domain; the adapter of that port, in `infrastructure/`, runs its statements on the
|
|
22
|
+
`Database` of the project; the platform builds the unit of work once and binds it.
|
|
23
|
+
|
|
24
|
+

|
|
25
|
+
|
|
26
|
+
The one idea to keep: **every statement goes through `executor()`**. Inside a unit of work it
|
|
27
|
+
is the transaction of that unit of work, so the row of the aggregate, the outbox record of the
|
|
28
|
+
event it published and the processed-event mark of a consumer commit or roll back together.
|
|
29
|
+
Outside one (a query, a script) it is the database itself.
|
|
30
|
+
|
|
16
31
|
## Schema
|
|
17
32
|
|
|
18
33
|
The tables are plain drizzle definitions: export them from the schema files drizzle-kit reads
|
|
19
34
|
and they are created by your own migrations.
|
|
20
35
|
|
|
36
|
+
<!-- checked sample -->
|
|
21
37
|
```ts
|
|
22
38
|
// platform/database/schema.ts
|
|
39
|
+
import { integer, text } from 'drizzle-orm/pg-core';
|
|
23
40
|
import { contextSchema, outboxTable, processedEventsTable } from '@ddd-ts-kit/drizzle/postgres';
|
|
24
41
|
|
|
25
42
|
export const outbox = outboxTable('messaging'); // messaging.outbox; no argument: public.outbox
|
|
@@ -43,6 +60,7 @@ export const orders = orderManagement.table('orders', {
|
|
|
43
60
|
over the drizzle database, so the project names its own database with a class, which is then
|
|
44
61
|
the injection token:
|
|
45
62
|
|
|
63
|
+
<!-- checked sample -->
|
|
46
64
|
```ts
|
|
47
65
|
// platform/database/database.ts
|
|
48
66
|
import type { PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
@@ -132,7 +150,8 @@ run after the commit. Handlers declared `after-commit` run once the transaction
|
|
|
132
150
|
A nested `run` joins the unit of work in progress: one dispatch, at the end of the outermost.
|
|
133
151
|
A `run` called directly (a consumer, a script) has the same timing as a command.
|
|
134
152
|
`unitOfWorkContract` of `@ddd-ts-kit/testing/contracts` proves it on PGlite, with a deferred
|
|
135
|
-
constraint for the commit that fails.
|
|
153
|
+
constraint for the commit that fails. The README of `@ddd-ts-kit/kernel` draws this timeline
|
|
154
|
+
([Domain events and the unit of work](../kernel/README.md#domain-events-and-the-unit-of-work)).
|
|
136
155
|
|
|
137
156
|
## Repository
|
|
138
157
|
|
|
@@ -141,33 +160,127 @@ database, never a transaction: `executor()` is the transaction of the unit of wo
|
|
|
141
160
|
is one and `db` otherwise.
|
|
142
161
|
|
|
143
162
|
```ts
|
|
144
|
-
//
|
|
145
|
-
|
|
163
|
+
// Instead of: a transaction handed down by the caller, which every port and every handler would then carry
|
|
164
|
+
save(order: Order, transaction: PgTransaction<PgQueryResultHKT>): Promise<void>;
|
|
165
|
+
|
|
166
|
+
// Write: the database, whose executor() is the transaction of the unit of work in progress
|
|
167
|
+
constructor(private readonly database: Database) {}
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
The domain side, an aggregate that knows nothing of rows, and its port:
|
|
146
171
|
|
|
172
|
+
<!-- checked sample -->
|
|
173
|
+
```ts
|
|
174
|
+
// contexts/order-management/domain/order.aggregate.ts
|
|
175
|
+
import { AggregateRoot, ConceptError, Repository } from '@ddd-ts-kit/kernel';
|
|
176
|
+
|
|
177
|
+
export type OrderStatus = 'open' | 'placed';
|
|
178
|
+
|
|
179
|
+
export class OrderError extends ConceptError {
|
|
180
|
+
static alreadyPlaced(orderId: string) {
|
|
181
|
+
return OrderError.refusal('ORDER_ALREADY_PLACED', `Order ${orderId} is already placed.`, { orderId });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export class Order extends AggregateRoot {
|
|
186
|
+
private constructor(
|
|
187
|
+
id: string,
|
|
188
|
+
private status: OrderStatus,
|
|
189
|
+
) {
|
|
190
|
+
super(id);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
static open(id: string): Order {
|
|
194
|
+
return new Order(id, 'open');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Rebuilds a stored order: used by the mapper only. */
|
|
198
|
+
static rehydrate(id: string, status: OrderStatus): Order {
|
|
199
|
+
return new Order(id, status);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
get currentStatus(): OrderStatus {
|
|
203
|
+
return this.status;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
place(): void {
|
|
207
|
+
if (this.status === 'placed') {
|
|
208
|
+
throw OrderError.alreadyPlaced(this.id);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
this.status = 'placed';
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// contexts/order-management/domain/repositories/order.repository.ts: findById and save come from Repository
|
|
147
216
|
export abstract class OrderRepository extends Repository<Order> {}
|
|
148
217
|
```
|
|
149
218
|
|
|
219
|
+
The infrastructure side, the table, the mapper and the adapter:
|
|
220
|
+
|
|
221
|
+
<!-- checked sample -->
|
|
150
222
|
```ts
|
|
151
223
|
// contexts/order-management/infrastructure/persistence/drizzle-order.repository.ts
|
|
152
224
|
import { and, eq } from 'drizzle-orm';
|
|
225
|
+
import { integer, text, type PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
226
|
+
import { AggregateRoot } from '@ddd-ts-kit/kernel';
|
|
153
227
|
import { Repository } from '@ddd-ts-kit/kernel/declarations';
|
|
154
|
-
import { optimisticUpdate } from '@ddd-ts-kit/drizzle/postgres';
|
|
228
|
+
import { contextSchema, DrizzleContext, optimisticUpdate } from '@ddd-ts-kit/drizzle/postgres';
|
|
229
|
+
|
|
230
|
+
// The aggregate and its port of the previous sample, reduced to their shape.
|
|
231
|
+
type OrderStatus = 'open' | 'placed';
|
|
232
|
+
declare class Order extends AggregateRoot {
|
|
233
|
+
static rehydrate(id: string, status: OrderStatus): Order;
|
|
234
|
+
get currentStatus(): OrderStatus;
|
|
235
|
+
}
|
|
236
|
+
abstract class OrderRepository {
|
|
237
|
+
abstract findById(id: string): Promise<Order | undefined>;
|
|
238
|
+
abstract save(order: Order): Promise<void>;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// platform/database/database.ts: the injection token of the database
|
|
242
|
+
abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
|
|
243
|
+
|
|
244
|
+
// order-management.schema.ts: the table of the schema sample, with a typed status
|
|
245
|
+
const orders = contextSchema('order-management').table('orders', {
|
|
246
|
+
id: text('id').primaryKey(),
|
|
247
|
+
status: text('status').$type<OrderStatus>().notNull(),
|
|
248
|
+
version: integer('version').notNull(),
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
type OrderRow = typeof orders.$inferSelect;
|
|
252
|
+
|
|
253
|
+
// order.mapper.ts: the row never leaves infrastructure
|
|
254
|
+
const OrderMapper = {
|
|
255
|
+
toDomain(row: OrderRow): Order {
|
|
256
|
+
const order = Order.rehydrate(row.id, row.status);
|
|
257
|
+
|
|
258
|
+
order.version = row.version; // the version optimisticUpdate will expect
|
|
259
|
+
|
|
260
|
+
return order;
|
|
261
|
+
},
|
|
262
|
+
|
|
263
|
+
toRow(order: Order, version: number): OrderRow {
|
|
264
|
+
return { id: order.id, status: order.currentStatus, version };
|
|
265
|
+
},
|
|
266
|
+
};
|
|
155
267
|
|
|
156
268
|
@Repository(OrderRepository)
|
|
157
269
|
export class DrizzleOrderRepository implements OrderRepository {
|
|
158
270
|
constructor(private readonly database: Database) {}
|
|
159
271
|
|
|
160
272
|
async findById(id: string): Promise<Order | undefined> {
|
|
273
|
+
// executor(): the transaction of the unit of work in progress, or the database outside one
|
|
161
274
|
const [row] = await this.database.executor().select().from(orders).where(eq(orders.id, id));
|
|
162
275
|
|
|
163
|
-
return row === undefined ? undefined : OrderMapper.toDomain(row);
|
|
276
|
+
return row === undefined ? undefined : OrderMapper.toDomain(row);
|
|
164
277
|
}
|
|
165
278
|
|
|
166
279
|
async save(order: Order): Promise<void> {
|
|
167
280
|
const db = this.database.executor();
|
|
168
281
|
|
|
169
282
|
await optimisticUpdate(order, async ({ expected, next }) => {
|
|
170
|
-
const row =
|
|
283
|
+
const row = OrderMapper.toRow(order, next);
|
|
171
284
|
const written =
|
|
172
285
|
expected === 0
|
|
173
286
|
? await db.insert(orders).values(row).onConflictDoNothing().returning({ id: orders.id })
|
|
@@ -177,7 +290,7 @@ export class DrizzleOrderRepository implements OrderRepository {
|
|
|
177
290
|
.where(and(eq(orders.id, order.id), eq(orders.version, expected)))
|
|
178
291
|
.returning({ id: orders.id });
|
|
179
292
|
|
|
180
|
-
return written.length;
|
|
293
|
+
return written.length; // 0 rows: optimisticUpdate throws ConcurrencyError
|
|
181
294
|
});
|
|
182
295
|
}
|
|
183
296
|
}
|
|
@@ -193,34 +306,73 @@ statement wrote no row, and moves `order.version` on otherwise. If your database
|
|
|
193
306
|
with a relational schema (`drizzle(url, { schema })`), declare `Database` as
|
|
194
307
|
`DrizzleContext<PgQueryResultHKT, typeof schema>` to keep `executor().query`.
|
|
195
308
|
|
|
309
|
+
| `expected` | Statement | No row written means |
|
|
310
|
+
|---|---|---|
|
|
311
|
+
| `0`: never saved | `INSERT ... ON CONFLICT DO NOTHING` | the id is taken |
|
|
312
|
+
| `n` | `UPDATE ... SET version = n + 1 WHERE id = ... AND version = n` | another transaction saved it since it was read |
|
|
313
|
+
|
|
196
314
|
## Audit columns, tenant scoping and pages
|
|
197
315
|
|
|
198
316
|
The standard persistence shapes of the kernel, on drizzle. `auditColumns()` and `tenantColumn()`
|
|
199
317
|
are column helpers to spread into a table: their keys are those of the kernel `AuditStamp` and
|
|
200
|
-
`TenantScoped`, so a stamp spreads into an insert as it is, and the
|
|
318
|
+
`TenantScoped`, so a stamp spreads into an insert as it is, and the columns have the same
|
|
201
319
|
names in every project (`created_at`, `created_by`, `updated_at`, `updated_by`, `tenant_id`),
|
|
202
320
|
which is what lets a dashboard, an export or the audit package be written once.
|
|
203
321
|
|
|
322
|
+
The table, then the repository. It reads through `tenantCondition` and writes through
|
|
323
|
+
`ownTenantCondition`, the two conditions of [Tenant isolation](#tenant-isolation):
|
|
324
|
+
|
|
325
|
+
<!-- checked sample -->
|
|
204
326
|
```ts
|
|
205
|
-
import {
|
|
327
|
+
import { and, eq } from 'drizzle-orm';
|
|
328
|
+
import { index, integer, text, type PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
329
|
+
import { AggregateRoot, Clock, ExecutionScope, stampCreation, stampUpdate, tenantScopeOf } from '@ddd-ts-kit/kernel';
|
|
330
|
+
import { Repository } from '@ddd-ts-kit/kernel/declarations';
|
|
331
|
+
import {
|
|
332
|
+
auditColumns,
|
|
333
|
+
contextSchema,
|
|
334
|
+
DrizzleContext,
|
|
335
|
+
optimisticUpdate,
|
|
336
|
+
ownTenantCondition,
|
|
337
|
+
tenantColumn,
|
|
338
|
+
tenantCondition,
|
|
339
|
+
} from '@ddd-ts-kit/drizzle/postgres';
|
|
340
|
+
|
|
341
|
+
// The aggregate, its port and the database, reduced to their shape.
|
|
342
|
+
type InvoiceStatus = 'draft' | 'issued';
|
|
343
|
+
declare class Invoice extends AggregateRoot {
|
|
344
|
+
static rehydrate(id: string, amount: number, status: InvoiceStatus): Invoice;
|
|
345
|
+
get amount(): number;
|
|
346
|
+
get status(): InvoiceStatus;
|
|
347
|
+
}
|
|
348
|
+
abstract class InvoiceRepository {
|
|
349
|
+
abstract findById(id: string): Promise<Invoice | undefined>;
|
|
350
|
+
abstract save(invoice: Invoice): Promise<void>;
|
|
351
|
+
}
|
|
352
|
+
abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
|
|
206
353
|
|
|
354
|
+
// contexts/billing-core/infrastructure/persistence/invoices.ts
|
|
207
355
|
export const invoices = contextSchema('billing-core').table(
|
|
208
356
|
'invoices',
|
|
209
357
|
{
|
|
210
358
|
id: text('id').primaryKey(),
|
|
211
359
|
amount: integer('amount').notNull(),
|
|
212
|
-
status: text('status').$type<
|
|
360
|
+
status: text('status').$type<InvoiceStatus>().notNull(),
|
|
213
361
|
version: integer('version').notNull(),
|
|
214
362
|
...tenantColumn(),
|
|
215
363
|
...auditColumns(),
|
|
216
364
|
},
|
|
365
|
+
// the order of the list queries, tie-breaker included, so a page is read from the index
|
|
217
366
|
(table) => [index('invoices_tenant_amount_idx').on(table.tenantId, table.amount, table.id)],
|
|
218
367
|
);
|
|
219
|
-
```
|
|
220
368
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
369
|
+
/** What the aggregate says of itself, plus the version to store: the rest of the row is the adapter's. */
|
|
370
|
+
interface VersionedInvoice {
|
|
371
|
+
readonly id: string;
|
|
372
|
+
readonly amount: number;
|
|
373
|
+
readonly status: InvoiceStatus;
|
|
374
|
+
readonly version: number;
|
|
375
|
+
}
|
|
224
376
|
|
|
225
377
|
@Repository(InvoiceRepository)
|
|
226
378
|
export class DrizzleInvoiceRepository implements InvoiceRepository {
|
|
@@ -235,14 +387,22 @@ export class DrizzleInvoiceRepository implements InvoiceRepository {
|
|
|
235
387
|
.executor()
|
|
236
388
|
.select()
|
|
237
389
|
.from(invoices)
|
|
238
|
-
.where(and(eq(invoices.id, id),
|
|
390
|
+
.where(and(eq(invoices.id, id), tenantCondition(invoices.tenantId, this.scope)));
|
|
391
|
+
|
|
392
|
+
if (row === undefined) {
|
|
393
|
+
return undefined;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const invoice = Invoice.rehydrate(row.id, row.amount, row.status);
|
|
239
397
|
|
|
240
|
-
|
|
398
|
+
invoice.version = row.version;
|
|
399
|
+
|
|
400
|
+
return invoice;
|
|
241
401
|
}
|
|
242
402
|
|
|
243
403
|
async save(invoice: Invoice): Promise<void> {
|
|
244
404
|
await optimisticUpdate(invoice, async ({ expected, next }) => {
|
|
245
|
-
const state = {
|
|
405
|
+
const state = { id: invoice.id, amount: invoice.amount, status: invoice.status, version: next };
|
|
246
406
|
const written = expected === 0 ? await this.insert(state) : await this.update(state, expected);
|
|
247
407
|
|
|
248
408
|
return written.length;
|
|
@@ -250,6 +410,7 @@ export class DrizzleInvoiceRepository implements InvoiceRepository {
|
|
|
250
410
|
}
|
|
251
411
|
|
|
252
412
|
private insert(state: VersionedInvoice) {
|
|
413
|
+
// tenant_id from the work in progress, created_* and updated_* from its actor and the Clock
|
|
253
414
|
const row = { ...state, ...tenantScopeOf(this.scope), ...stampCreation(this.scope, this.clock) };
|
|
254
415
|
|
|
255
416
|
return this.database.executor().insert(invoices).values(row).onConflictDoNothing().returning({ id: invoices.id });
|
|
@@ -259,13 +420,17 @@ export class DrizzleInvoiceRepository implements InvoiceRepository {
|
|
|
259
420
|
return this.database
|
|
260
421
|
.executor()
|
|
261
422
|
.update(invoices)
|
|
262
|
-
.set({ ...state, ...stampUpdate(this.scope, this.clock) })
|
|
263
|
-
.where(
|
|
423
|
+
.set({ ...state, ...stampUpdate(this.scope, this.clock) }) // leaves created_at and created_by alone
|
|
424
|
+
.where(
|
|
425
|
+
and(
|
|
426
|
+
eq(invoices.id, state.id),
|
|
427
|
+
eq(invoices.version, expected),
|
|
428
|
+
ownTenantCondition(invoices.tenantId, this.scope),
|
|
429
|
+
),
|
|
430
|
+
)
|
|
264
431
|
.returning({ id: invoices.id });
|
|
265
432
|
}
|
|
266
433
|
}
|
|
267
|
-
|
|
268
|
-
const ownTenant = (scope: ExecutionScope) => eq(invoices.tenantId, tenantScopeOf(scope).tenantId);
|
|
269
434
|
```
|
|
270
435
|
|
|
271
436
|
A search query takes the kernel `PageRequest` and answers a `Page`, in both variants:
|
|
@@ -277,10 +442,40 @@ export abstract class InvoiceQueries {
|
|
|
277
442
|
}
|
|
278
443
|
```
|
|
279
444
|
|
|
445
|
+
<!-- checked sample -->
|
|
280
446
|
```ts
|
|
281
447
|
// contexts/billing-core/infrastructure/persistence/drizzle-invoice-queries.reader.ts
|
|
282
|
-
import {
|
|
448
|
+
import { and, asc, desc, eq, gt, lt, or, type SQL } from 'drizzle-orm';
|
|
449
|
+
import { index, integer, text, type PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
450
|
+
import {
|
|
451
|
+
ExecutionScope,
|
|
452
|
+
InvalidPageRequestError,
|
|
453
|
+
decodeCursor,
|
|
454
|
+
encodeCursor,
|
|
455
|
+
pageOf,
|
|
456
|
+
type CursorPageRequest,
|
|
457
|
+
type OffsetPageRequest,
|
|
458
|
+
type Page,
|
|
459
|
+
type PageRequest,
|
|
460
|
+
type SortDirection,
|
|
461
|
+
} from '@ddd-ts-kit/kernel';
|
|
283
462
|
import { Repository } from '@ddd-ts-kit/kernel/declarations';
|
|
463
|
+
import { contextSchema, DrizzleContext, tenantColumn, tenantCondition } from '@ddd-ts-kit/drizzle/postgres';
|
|
464
|
+
|
|
465
|
+
// The port of the application, the database and the table of the previous samples, reduced to their shape.
|
|
466
|
+
interface InvoiceSummary {
|
|
467
|
+
readonly id: string;
|
|
468
|
+
readonly amount: number;
|
|
469
|
+
}
|
|
470
|
+
abstract class InvoiceQueries {
|
|
471
|
+
abstract search(request: PageRequest<'amount'>): Promise<Page<InvoiceSummary>>;
|
|
472
|
+
}
|
|
473
|
+
abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
|
|
474
|
+
const invoices = contextSchema('billing-core').table(
|
|
475
|
+
'invoices',
|
|
476
|
+
{ id: text('id').primaryKey(), amount: integer('amount').notNull(), ...tenantColumn() },
|
|
477
|
+
(table) => [index('invoices_tenant_amount_idx').on(table.tenantId, table.amount, table.id)],
|
|
478
|
+
);
|
|
284
479
|
|
|
285
480
|
@Repository(InvoiceQueries)
|
|
286
481
|
export class DrizzleInvoiceQueries implements InvoiceQueries {
|
|
@@ -295,15 +490,16 @@ export class DrizzleInvoiceQueries implements InvoiceQueries {
|
|
|
295
490
|
|
|
296
491
|
private async byOffset(request: OffsetPageRequest<'amount'>): Promise<Page<InvoiceSummary>> {
|
|
297
492
|
const db = this.database.executor();
|
|
493
|
+
const own = tenantCondition(invoices.tenantId, this.scope);
|
|
298
494
|
const rows = await db
|
|
299
495
|
.select()
|
|
300
496
|
.from(invoices)
|
|
301
|
-
.where(
|
|
497
|
+
.where(own)
|
|
302
498
|
.orderBy(...totalOrder(directionOf(request)))
|
|
303
499
|
.limit(request.limit)
|
|
304
500
|
.offset(request.offset);
|
|
305
501
|
|
|
306
|
-
return pageOf(rows.map(toSummary), { total: await db.$count(invoices,
|
|
502
|
+
return pageOf(rows.map(toSummary), { total: await db.$count(invoices, own) });
|
|
307
503
|
}
|
|
308
504
|
|
|
309
505
|
private async byCursor(request: CursorPageRequest<'amount'>): Promise<Page<InvoiceSummary>> {
|
|
@@ -313,9 +509,9 @@ export class DrizzleInvoiceQueries implements InvoiceQueries {
|
|
|
313
509
|
.executor()
|
|
314
510
|
.select()
|
|
315
511
|
.from(invoices)
|
|
316
|
-
.where(and(
|
|
512
|
+
.where(and(tenantCondition(invoices.tenantId, this.scope), after))
|
|
317
513
|
.orderBy(...totalOrder(direction))
|
|
318
|
-
.limit(request.limit + 1);
|
|
514
|
+
.limit(request.limit + 1); // one row more than asked: it says whether a page follows
|
|
319
515
|
const items = rows.slice(0, request.limit);
|
|
320
516
|
const last = items.at(-1);
|
|
321
517
|
const more = rows.length > request.limit && last !== undefined;
|
|
@@ -324,7 +520,9 @@ export class DrizzleInvoiceQueries implements InvoiceQueries {
|
|
|
324
520
|
}
|
|
325
521
|
}
|
|
326
522
|
|
|
327
|
-
const directionOf = (request: PageRequest<'amount'>) => request.sort[0]?.direction ?? 'asc';
|
|
523
|
+
const directionOf = (request: PageRequest<'amount'>): SortDirection => request.sort[0]?.direction ?? 'asc';
|
|
524
|
+
|
|
525
|
+
const toSummary = (row: typeof invoices.$inferSelect): InvoiceSummary => ({ id: row.id, amount: row.amount });
|
|
328
526
|
|
|
329
527
|
// The primary key follows the sort field, in the same direction: the order is total.
|
|
330
528
|
function totalOrder(direction: SortDirection): SQL[] {
|
|
@@ -334,12 +532,13 @@ function totalOrder(direction: SortDirection): SQL[] {
|
|
|
334
532
|
}
|
|
335
533
|
|
|
336
534
|
// The rows after a position, as a tuple comparison: the tie-breaker decides among equals.
|
|
337
|
-
function beyond({ amount, id }: { amount: number; id: string }, direction: SortDirection) {
|
|
535
|
+
function beyond({ amount, id }: { amount: number; id: string }, direction: SortDirection): SQL | undefined {
|
|
338
536
|
const past = direction === 'asc' ? gt : lt;
|
|
339
537
|
|
|
340
538
|
return or(past(invoices.amount, amount), and(eq(invoices.amount, amount), past(invoices.id, id)));
|
|
341
539
|
}
|
|
342
540
|
|
|
541
|
+
// A cursor comes back from a client: what it decodes to is checked before it reaches a statement.
|
|
343
542
|
function positionOf(cursor: string): { amount: number; id: string } {
|
|
344
543
|
const { amount, id } = decodeCursor(cursor);
|
|
345
544
|
|
|
@@ -356,6 +555,10 @@ generates: its kind is `repository`. Declared with `@Adapter` it would be `exter
|
|
|
356
555
|
generated platform puts a retry and a time limit around every `external` and `gateway`
|
|
357
556
|
adapter, which a statement of the unit of work must not get.
|
|
358
557
|
|
|
558
|
+
What the two kinds of page do when a row is inserted between two reads:
|
|
559
|
+
|
|
560
|
+

|
|
561
|
+
|
|
359
562
|
The rules these examples hold, and that the tests of this package check on a real database:
|
|
360
563
|
|
|
361
564
|
- **Audit columns** are filled by the adapter, never by the aggregate: `stampCreation(scope,
|
|
@@ -384,13 +587,18 @@ Two strategies on drizzle, both proven by `tenantIsolationContract` of
|
|
|
384
587
|
`@ddd-ts-kit/testing/contracts`; schema per tenant and database per tenant are shipped for knex
|
|
385
588
|
only ([Multitenancy](../../docs/concepts/multitenancy.md) has the table).
|
|
386
589
|
|
|
590
|
+

|
|
591
|
+
|
|
387
592
|
**Shared tables.** A `tenant_id` column (`tenantColumn()`) and the condition of the kit in every
|
|
388
593
|
statement instead of one written by hand:
|
|
389
594
|
|
|
390
595
|
```ts
|
|
391
|
-
//
|
|
596
|
+
// Instead of: a condition written by hand, which an elevation of platform staff cannot widen
|
|
597
|
+
.where(and(eq(invoices.id, id), eq(invoices.tenantId, tenantScopeOf(this.scope).tenantId)))
|
|
598
|
+
|
|
599
|
+
// Write, for reads: the tenant of the work, or the tenants of an elevation
|
|
392
600
|
.where(and(eq(invoices.id, id), tenantCondition(invoices.tenantId, this.scope)))
|
|
393
|
-
// updates and deletes: the one tenant of the work, which an elevation never widens
|
|
601
|
+
// and for updates and deletes: the one tenant of the work, which an elevation never widens
|
|
394
602
|
.where(and(eq(invoices.id, state.id), eq(invoices.version, expected), ownTenantCondition(invoices.tenantId, this.scope)))
|
|
395
603
|
```
|
|
396
604
|
|
|
@@ -401,12 +609,44 @@ column: table.tenantId }` to `DrizzleReadModelTable` and `DrizzleReadModelStore`
|
|
|
401
609
|
the work, an insert, an update and a delete only its one tenant) are declared with the table, so
|
|
402
610
|
drizzle-kit generates them, and the unit of work sets the tenant of each transaction.
|
|
403
611
|
|
|
612
|
+
<!-- checked sample -->
|
|
404
613
|
```ts
|
|
405
|
-
|
|
406
|
-
|
|
614
|
+
// contexts/billing-core/infrastructure/persistence/invoices.ts
|
|
615
|
+
import { integer, text } from 'drizzle-orm/pg-core';
|
|
616
|
+
import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
617
|
+
import type { ExecutionScope } from '@ddd-ts-kit/kernel';
|
|
618
|
+
import {
|
|
619
|
+
contextSchema,
|
|
620
|
+
createDrizzleUnitOfWork,
|
|
621
|
+
forceRowLevelSecurity,
|
|
622
|
+
tenantColumn,
|
|
623
|
+
tenantPolicies,
|
|
624
|
+
tenantSession,
|
|
625
|
+
} from '@ddd-ts-kit/drizzle/postgres';
|
|
626
|
+
|
|
627
|
+
export const invoices = contextSchema('billing-core')
|
|
628
|
+
.table(
|
|
629
|
+
'invoices',
|
|
630
|
+
{
|
|
631
|
+
id: text('id').primaryKey(),
|
|
632
|
+
amount: integer('amount').notNull(),
|
|
633
|
+
version: integer('version').notNull(),
|
|
634
|
+
...tenantColumn(),
|
|
635
|
+
},
|
|
636
|
+
// tenant_isolation_select, _insert, _update and _delete: drizzle-kit writes them into the migration
|
|
637
|
+
(table) => [...tenantPolicies(table.tenantId)],
|
|
638
|
+
)
|
|
407
639
|
.enableRLS();
|
|
408
640
|
|
|
409
|
-
|
|
641
|
+
// platform/database/persistence-over.ts: each transaction starts by setting the tenant of the work
|
|
642
|
+
declare const db: PgDatabase<PgQueryResultHKT>;
|
|
643
|
+
declare const executionScope: ExecutionScope;
|
|
644
|
+
|
|
645
|
+
export const unitOfWork = createDrizzleUnitOfWork(db, undefined, { begin: tenantSession(executionScope) });
|
|
646
|
+
|
|
647
|
+
// The one statement drizzle-kit does not write, for a custom migration (drizzle-kit generate --custom):
|
|
648
|
+
// alter table "billing_core"."invoices" force row level security;
|
|
649
|
+
export const forced = forceRowLevelSecurity(invoices);
|
|
410
650
|
```
|
|
411
651
|
|
|
412
652
|
drizzle-kit does not force the policies on the owner of the table: `forceRowLevelSecurity(invoices)`
|
|
@@ -425,25 +665,79 @@ condition. `columns` maps each field of the read model to its column, and is the
|
|
|
425
665
|
of identifiers: every value is a parameter encoded by its column, a text search is
|
|
426
666
|
`like $1 escape $2` with `%`, `_` and `\` escaped.
|
|
427
667
|
|
|
668
|
+
A read port declares what a caller may ask with `defineCriteria`; a query of your own on the
|
|
669
|
+
table of a read model plans the criteria, then hands the plan to the translator:
|
|
670
|
+
|
|
671
|
+
<!-- checked sample -->
|
|
428
672
|
```ts
|
|
673
|
+
import { and, eq } from 'drizzle-orm';
|
|
674
|
+
import { text, timestamp, type PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
675
|
+
import { defineCriteria, pageOfPlan, planCriteria, type Page, type ScopedCriteria } from '@ddd-ts-kit/kernel';
|
|
676
|
+
import { contextSchema, criteriaToDrizzle, DrizzleContext, readModelColumns } from '@ddd-ts-kit/drizzle/postgres';
|
|
677
|
+
|
|
678
|
+
// application/ports/appointment-list.port.ts: the row, and what a caller may filter and sort by
|
|
679
|
+
export interface AppointmentRow {
|
|
680
|
+
readonly id: string;
|
|
681
|
+
readonly status: string;
|
|
682
|
+
readonly startsAt: Date;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
export const appointmentCriteria = defineCriteria<AppointmentRow>({
|
|
686
|
+
fields: {
|
|
687
|
+
id: { type: 'string' },
|
|
688
|
+
status: { type: 'string', filter: ['eq', 'in'], sortable: true },
|
|
689
|
+
startsAt: { type: 'instant', filter: ['gte', 'lt', 'between'], sortable: true },
|
|
690
|
+
},
|
|
691
|
+
defaultSort: [{ field: 'startsAt', direction: 'asc' }],
|
|
692
|
+
tieBreaker: 'id',
|
|
693
|
+
});
|
|
694
|
+
|
|
695
|
+
abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
|
|
696
|
+
|
|
697
|
+
// infrastructure/persistence/appointment-list.schema.ts
|
|
698
|
+
export const appointmentList = contextSchema('scheduling').table('appointment_list', {
|
|
699
|
+
id: text('id').primaryKey(),
|
|
700
|
+
status: text('status').notNull(),
|
|
701
|
+
startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }).notNull(),
|
|
702
|
+
...readModelColumns(), // last_event_id, last_event_at, last_event_version, deleted
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
// the only source of identifiers: a field the map does not name never reaches a statement
|
|
706
|
+
const COLUMNS = { id: appointmentList.id, status: appointmentList.status, startsAt: appointmentList.startsAt };
|
|
707
|
+
|
|
429
708
|
// infrastructure/persistence/drizzle-appointment-queries.reader.ts
|
|
430
|
-
async
|
|
431
|
-
|
|
709
|
+
export async function searchAppointments(
|
|
710
|
+
database: Database,
|
|
711
|
+
criteria: ScopedCriteria<AppointmentRow>,
|
|
712
|
+
): Promise<Page<AppointmentRow>> {
|
|
713
|
+
const plan = planCriteria(appointmentCriteria, criteria); // refuses what the definition does not open
|
|
432
714
|
|
|
433
715
|
if (plan.empty) {
|
|
434
|
-
return pageOfPlan(plan, []);
|
|
716
|
+
return pageOfPlan(plan, []); // the access scope reaches no row: no statement at all
|
|
435
717
|
}
|
|
436
718
|
|
|
437
|
-
const { where, orderBy, limit, offset } = criteriaToDrizzle(plan, COLUMNS);
|
|
438
|
-
const
|
|
439
|
-
|
|
440
|
-
|
|
719
|
+
const { where, counted, orderBy, limit, offset } = criteriaToDrizzle(plan, COLUMNS);
|
|
720
|
+
const live = eq(appointmentList.deleted, false); // a removed row stays in the table, flagged
|
|
721
|
+
const db = database.executor();
|
|
722
|
+
const rows = await db
|
|
723
|
+
.select(COLUMNS)
|
|
724
|
+
.from(appointmentList)
|
|
725
|
+
.where(and(where, live))
|
|
726
|
+
.orderBy(...orderBy)
|
|
727
|
+
.limit(limit)
|
|
728
|
+
.offset(offset);
|
|
729
|
+
|
|
730
|
+
// An offset page counts its total; a cursor page knows what follows from the extra row.
|
|
731
|
+
const total = plan.kind === 'offset' ? await db.$count(appointmentList, and(counted, live)) : undefined;
|
|
732
|
+
|
|
733
|
+
return pageOfPlan(plan, rows, total);
|
|
441
734
|
}
|
|
442
735
|
```
|
|
443
736
|
|
|
444
737
|
A cursor page is fetched one row longer than asked, which is how `pageOfPlan` knows whether
|
|
445
|
-
another follows; an offset page takes its total from `db.$count(table, counted)
|
|
446
|
-
declared `nullable` is ordered `nulls last`
|
|
738
|
+
another follows; an offset page takes its total from `db.$count(table, counted)`, passed as
|
|
739
|
+
the third argument of `pageOfPlan`. A field declared `nullable` is ordered `nulls last`
|
|
740
|
+
ascending and `nulls first` descending.
|
|
447
741
|
|
|
448
742
|
**Strings.** A text column is ordered and compared by range in the collation of the column;
|
|
449
743
|
criteria order strings by code point. Declare the text columns that are sorted or compared
|
|
@@ -454,7 +748,26 @@ An integer is `integer`: a `bigint` comes back as a string from the driver.
|
|
|
454
748
|
|
|
455
749
|
## Read models
|
|
456
750
|
|
|
751
|
+
The adapter of a read model port extends `DrizzleReadModelStore` and adds nothing: it gets
|
|
752
|
+
`get`, `upsertIfNewer`, `delete` and `search` from it.
|
|
753
|
+
|
|
754
|
+
<!-- checked sample -->
|
|
457
755
|
```ts
|
|
756
|
+
import { text, timestamp, type PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
757
|
+
import { ReadModelStore, type CriteriaDefinition } from '@ddd-ts-kit/kernel';
|
|
758
|
+
import { Repository } from '@ddd-ts-kit/kernel/declarations';
|
|
759
|
+
import { contextSchema, DrizzleContext, DrizzleReadModelStore, readModelColumns } from '@ddd-ts-kit/drizzle/postgres';
|
|
760
|
+
|
|
761
|
+
// The row, its criteria and the database of the previous samples, reduced to their shape.
|
|
762
|
+
interface AppointmentRow {
|
|
763
|
+
readonly id: string;
|
|
764
|
+
readonly status: string;
|
|
765
|
+
readonly startsAt: Date;
|
|
766
|
+
}
|
|
767
|
+
declare const appointmentCriteria: CriteriaDefinition<AppointmentRow>;
|
|
768
|
+
abstract class AppointmentList extends ReadModelStore<AppointmentRow> {}
|
|
769
|
+
abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
|
|
770
|
+
|
|
458
771
|
// infrastructure/persistence/appointment-list.schema.ts
|
|
459
772
|
export const appointmentList = contextSchema('scheduling').table('appointment_list', {
|
|
460
773
|
id: text('id').primaryKey(),
|
|
@@ -484,19 +797,22 @@ a query of your own on the table leaves those rows out, and so does a unique ind
|
|
|
484
797
|
(`WHERE NOT deleted`). `store.table` is what `ProjectionRebuild` takes; the rebuild is
|
|
485
798
|
PostgreSQL only (a copy `<table>__rebuild` made `LIKE ... INCLUDING ALL`, the keys written
|
|
486
799
|
meanwhile in `<table>__touched`, the swap by rename in one transaction) and its guarantees
|
|
487
|
-
and limits are in the README of `@ddd-ts-kit/kernel` (
|
|
488
|
-
`criteriaContract` and `readModelStoreContract` of
|
|
489
|
-
and on PostgreSQL 18.
|
|
800
|
+
and limits are in the README of `@ddd-ts-kit/kernel` ([Rebuild](../kernel/README.md#rebuild)).
|
|
801
|
+
The store passes `criteriaContract` and `readModelStoreContract` of
|
|
802
|
+
`@ddd-ts-kit/testing/contracts`, on PGlite and on PostgreSQL 18.
|
|
490
803
|
|
|
491
804
|
## Outbox and idempotency
|
|
492
805
|
|
|
493
806
|
- `DrizzleOutboxStore.claimBatch` selects the due rows `FOR UPDATE SKIP LOCKED` and leases
|
|
494
807
|
them in the same short transaction by pushing `next_attempt_at` forward (`leaseMs`, default
|
|
495
808
|
30 s), so several relays share the work without waiting for each other, and the records of a
|
|
496
|
-
relay that died come back when the lease expires. Delivery is at least once,
|
|
809
|
+
relay that died come back when the lease expires. Delivery is at least once and, by default,
|
|
810
|
+
unordered: `ordering: 'per-key'` of `OutboxRelay`, given a `keyOf` (typically the aggregate
|
|
811
|
+
id), keeps the records of one key in order, with a single relay ([Ordering per key](../events/README.md#ordering-per-key)).
|
|
497
812
|
- `DrizzleProcessedEventStore.markProcessed` is an `INSERT ... ON CONFLICT DO NOTHING`. Run
|
|
498
813
|
the consumer inside the unit of work: the mark then commits with the effects of the handler,
|
|
499
|
-
and disappears with them if it fails.
|
|
814
|
+
and disappears with them if it fails. `consume` of `@ddd-ts-kit/events` does exactly that
|
|
815
|
+
([Consume idempotently](../events/README.md#consume-idempotently)).
|
|
500
816
|
- A multi-tenant project declares `tenantOutboxTable('messaging')` instead of `outboxTable`: the
|
|
501
817
|
same table and a nullable `tenant_id`, which the store, given that table, fills from the tenant
|
|
502
818
|
of each event, so that its consumers run in that tenant. Switching an existing project is one
|
|
@@ -504,12 +820,19 @@ and on PostgreSQL 18.
|
|
|
504
820
|
|
|
505
821
|
## Event store
|
|
506
822
|
|
|
823
|
+
<!-- checked sample -->
|
|
507
824
|
```ts
|
|
825
|
+
import type { PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
826
|
+
import { createDrizzleEventSourcing, DrizzleContext, eventStoreTables } from '@ddd-ts-kit/drizzle/postgres';
|
|
827
|
+
|
|
508
828
|
// src/contexts/scheduling/infrastructure/persistence/scheduling.schema.ts, read by drizzle-kit
|
|
509
829
|
export const { events, head, snapshots, checkpoints, subjectKeys } = eventStoreTables('scheduling');
|
|
510
830
|
|
|
511
|
-
// the composition root
|
|
512
|
-
const
|
|
831
|
+
// the composition root: the database of the project, then one store per port
|
|
832
|
+
declare const database: DrizzleContext<PgQueryResultHKT>;
|
|
833
|
+
|
|
834
|
+
export const stores = createDrizzleEventSourcing(database, { schema: 'scheduling' });
|
|
835
|
+
// stores.events, stores.snapshots, stores.checkpoints, stores.subjectKeys
|
|
513
836
|
```
|
|
514
837
|
|
|
515
838
|
`eventStoreTables` declares the tables drizzle-kit creates in a migration of the project, with
|
|
@@ -521,7 +844,8 @@ unit of work, so the stream and the outbox records its events publish commit tog
|
|
|
521
844
|
transaction ends: positions are given in commit order, without gaps, and two appends never run
|
|
522
845
|
side by side, whatever their streams. PostgreSQL only. The stores are the ones of the kernel
|
|
523
846
|
(`PostgresEventStore` and its companions), held to `eventStoreContract` here; how an
|
|
524
|
-
event-sourced aggregate uses them: the README of `@ddd-ts-kit/kernel`, section
|
|
847
|
+
event-sourced aggregate uses them: the README of `@ddd-ts-kit/kernel`, section
|
|
848
|
+
[Event sourcing](../kernel/README.md#event-sourcing).
|
|
525
849
|
|
|
526
850
|
## Background jobs
|
|
527
851
|
|
|
@@ -530,10 +854,25 @@ context in `jobsTable('scheduling')`, which the schema files of drizzle-kit incl
|
|
|
530
854
|
migration creates it. `add` runs on the executor of the context, inside the transaction of the
|
|
531
855
|
command that enqueues; claims select the due rows `FOR UPDATE SKIP LOCKED` and lease them.
|
|
532
856
|
|
|
857
|
+
<!-- checked sample -->
|
|
533
858
|
```ts
|
|
859
|
+
import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
860
|
+
import { kernelModule } from '@ddd-ts-kit/di';
|
|
861
|
+
import { createDrizzleUnitOfWork, DrizzleJobStore, DrizzleProcessStore, jobsTable, processesTable } from '@ddd-ts-kit/drizzle/postgres';
|
|
862
|
+
|
|
863
|
+
// scheduling.schema.ts, read by drizzle-kit: scheduling.background_jobs and scheduling.process_instances
|
|
534
864
|
export const schedulingJobs = jobsTable('scheduling');
|
|
865
|
+
export const schedulingProcesses = processesTable('scheduling');
|
|
866
|
+
|
|
867
|
+
// the composition root
|
|
868
|
+
declare const db: PgDatabase<PgQueryResultHKT>;
|
|
869
|
+
const unitOfWork = createDrizzleUnitOfWork(db);
|
|
535
870
|
|
|
536
|
-
|
|
871
|
+
export const kernel = kernelModule({
|
|
872
|
+
unitOfWork,
|
|
873
|
+
jobStore: new DrizzleJobStore(unitOfWork, schedulingJobs),
|
|
874
|
+
processStore: new DrizzleProcessStore(unitOfWork, schedulingProcesses),
|
|
875
|
+
});
|
|
537
876
|
```
|
|
538
877
|
|
|
539
878
|
It passes `jobStoreContract`, its unit of work suite included, on PGlite and, in the integration
|
|
@@ -545,7 +884,8 @@ guarantee: [Background jobs](../../docs/concepts/background-jobs.md).
|
|
|
545
884
|
|
|
546
885
|
`DrizzleProcessStore` is the `ProcessStore` of the kernel, on `processesTable(schema)`: a first
|
|
547
886
|
save inserts, a next one updates at the previous version, and a save that changes no row throws
|
|
548
|
-
`ConcurrencyError`, in the transaction of the step. It passes `processStoreContract`.
|
|
887
|
+
`ConcurrencyError`, in the transaction of the step. It passes `processStoreContract`. The
|
|
888
|
+
sample of [Background jobs](#background-jobs) binds it with `kernelModule({ processStore })`.
|
|
549
889
|
|
|
550
890
|
## Testing an adapter
|
|
551
891
|
|
|
@@ -561,3 +901,11 @@ database of its own that it drops afterwards (last run: PostgreSQL 18):
|
|
|
561
901
|
```
|
|
562
902
|
DDD_TS_KIT_TEST_DATABASE_URL=postgresql://user:password@localhost:5432/postgres npx vitest run packages/drizzle
|
|
563
903
|
```
|
|
904
|
+
|
|
905
|
+
## See also
|
|
906
|
+
|
|
907
|
+
- [Persistence](../../docs/tools/persistence.md): choosing an ORM, and what each adapter package verified
|
|
908
|
+
- [Aggregates](../../docs/concepts/aggregates.md#optimistic-concurrency): optimistic concurrency, seen from the domain
|
|
909
|
+
- [The transactional outbox](../../docs/concepts/transactional-outbox.md): why the outbox record commits with the business write
|
|
910
|
+
- [Multitenancy](../../docs/concepts/multitenancy.md#isolation-four-strategies): the four isolation strategies
|
|
911
|
+
- [`@ddd-ts-kit/typeorm`](../typeorm/README.md): the same pieces on TypeORM
|