@ddd-ts-kit/drizzle 0.110.1 → 0.112.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.
Files changed (43) hide show
  1. package/README.fr.md +96 -34
  2. package/README.md +90 -34
  3. package/dist/postgres/locks/advisory-lock.d.ts +16 -0
  4. package/dist/postgres/locks/advisory-lock.d.ts.map +1 -0
  5. package/dist/postgres/locks/advisory-lock.js +19 -0
  6. package/dist/postgres/locks/advisory-lock.js.map +1 -0
  7. package/dist/postgres/locks/drizzle-locking-context.d.ts +7 -0
  8. package/dist/postgres/locks/drizzle-locking-context.d.ts.map +1 -0
  9. package/dist/postgres/locks/drizzle-locking-context.js +2 -0
  10. package/dist/postgres/locks/drizzle-locking-context.js.map +1 -0
  11. package/dist/postgres/locks/try-advisory-lock.d.ts +10 -0
  12. package/dist/postgres/locks/try-advisory-lock.d.ts.map +1 -0
  13. package/dist/postgres/locks/try-advisory-lock.js +15 -0
  14. package/dist/postgres/locks/try-advisory-lock.js.map +1 -0
  15. package/dist/postgres/read-model/drizzle-read-model-table.d.ts +4 -1
  16. package/dist/postgres/read-model/drizzle-read-model-table.d.ts.map +1 -1
  17. package/dist/postgres/read-model/drizzle-read-model-table.js +36 -2
  18. package/dist/postgres/read-model/drizzle-read-model-table.js.map +1 -1
  19. package/dist/postgres/read-model/drizzle-stamped-rows.d.ts +5 -1
  20. package/dist/postgres/read-model/drizzle-stamped-rows.d.ts.map +1 -1
  21. package/dist/postgres/read-model/drizzle-stamped-rows.js +24 -17
  22. package/dist/postgres/read-model/drizzle-stamped-rows.js.map +1 -1
  23. package/dist/postgres/read-model/like-pattern.d.ts +2 -2
  24. package/dist/postgres/read-model/like-pattern.d.ts.map +1 -1
  25. package/dist/postgres/read-model/like-pattern.js +1 -1
  26. package/dist/postgres/read-model/like-pattern.js.map +1 -1
  27. package/dist/postgres/read-model/predicate-to-drizzle.d.ts +1 -1
  28. package/dist/postgres/read-model/predicate-to-drizzle.d.ts.map +1 -1
  29. package/dist/postgres/read-model/predicate-to-drizzle.js +11 -3
  30. package/dist/postgres/read-model/predicate-to-drizzle.js.map +1 -1
  31. package/dist/postgres/read-model/row.mapper.d.ts +2 -0
  32. package/dist/postgres/read-model/row.mapper.d.ts.map +1 -1
  33. package/dist/postgres/read-model/row.mapper.js +4 -0
  34. package/dist/postgres/read-model/row.mapper.js.map +1 -1
  35. package/dist/postgres/sql/insert-ignoring-conflict.d.ts +29 -0
  36. package/dist/postgres/sql/insert-ignoring-conflict.d.ts.map +1 -0
  37. package/dist/postgres/sql/insert-ignoring-conflict.js +26 -0
  38. package/dist/postgres/sql/insert-ignoring-conflict.js.map +1 -0
  39. package/dist/postgres.d.ts +4 -0
  40. package/dist/postgres.d.ts.map +1 -1
  41. package/dist/postgres.js +4 -0
  42. package/dist/postgres.js.map +1 -1
  43. package/package.json +5 -5
package/README.fr.md CHANGED
@@ -1,5 +1,5 @@
1
1
  [English](README.md) · **Français**
2
- <!-- translation-of: README.md sha256:4d6a7e774da55a64 -->
2
+ <!-- translation-of: README.md sha256:0d30d02803f33ba1 -->
3
3
 
4
4
  # @ddd-ts-kit/drizzle
5
5
 
@@ -241,7 +241,7 @@ import { and, eq } from 'drizzle-orm';
241
241
  import { integer, text, type PgQueryResultHKT } from 'drizzle-orm/pg-core';
242
242
  import { AggregateRoot } from '@ddd-ts-kit/kernel';
243
243
  import { Repository } from '@ddd-ts-kit/kernel/declarations';
244
- import { contextSchema, DrizzleContext, optimisticUpdate, primaryKeyOf } from '@ddd-ts-kit/drizzle/postgres';
244
+ import { contextSchema, DrizzleContext, insertIgnoringConflict, optimisticUpdate } from '@ddd-ts-kit/drizzle/postgres';
245
245
 
246
246
  // L'agrégat et son port de l'exemple précédent, réduits à leur forme.
247
247
  type OrderStatus = 'open' | 'placed';
@@ -297,14 +297,16 @@ export class DrizzleOrderRepository implements OrderRepository {
297
297
 
298
298
  await optimisticUpdate(order, async ({ expected, next }) => {
299
299
  const row = OrderMapper.toRow(order, next);
300
- const written =
301
- expected === 0
302
- ? await db.insert(orders).values(row).onConflictDoNothing({ target: primaryKeyOf(orders) }).returning({ id: orders.id })
303
- : await db
304
- .update(orders)
305
- .set(row)
306
- .where(and(eq(orders.id, order.id), eq(orders.version, expected)))
307
- .returning({ id: orders.id });
300
+
301
+ if (expected === 0) {
302
+ return (await insertIgnoringConflict(() => db.insert(orders).values(row), orders)) ? 1 : 0;
303
+ }
304
+
305
+ const written = await db
306
+ .update(orders)
307
+ .set(row)
308
+ .where(and(eq(orders.id, order.id), eq(orders.version, expected)))
309
+ .returning({ id: orders.id });
308
310
 
309
311
  return written.length; // 0 ligne : optimisticUpdate lève ConcurrencyError
310
312
  });
@@ -324,16 +326,66 @@ schéma relationnel (`drizzle(url, { schema })`), déclarez `Database` comme
324
326
 
325
327
  | `expected` | Instruction | Aucune ligne écrite signifie |
326
328
  |---|---|---|
327
- | `0` : jamais enregistré | `INSERT ... ON CONFLICT (id) DO NOTHING` | l'id est déjà pris |
329
+ | `0` : jamais enregistré | `insertIgnoringConflict` : `INSERT ... ON CONFLICT DO NOTHING`, puis `ON CONFLICT (id) DO NOTHING` quand elle n'a rien écrit | l'id est déjà pris |
328
330
  | `n` | `UPDATE ... SET version = n + 1 WHERE id = ... AND version = n` | une autre transaction l'a enregistré depuis sa lecture |
329
331
 
330
- La cible du conflit est la clé primaire seule, telle que la table la déclare
331
- (`onConflictDoNothing({ target: primaryKeyOf(orders) })`, l'id, ou chaque colonne d'une clé qui
332
- porte le tenant) : sans elle,
333
- PostgreSQL écarte aussi une ligne qui prend une valeur qu'une autre ligne détient sous une
334
- contrainte d'unicité (un e-mail), et l'enregistrement se lit comme une mise à jour perdue.
335
- Nommée, cette ligne est refusée par la base, et `optimisticUpdate` lève `UniqueViolationError`
336
- (code `CONFLICT`, 409), comme pour une mise à jour qui prend une telle valeur.
332
+ `insertIgnoringConflict(() => db.insert(orders).values(row), orders)` insère sauf si la clé
333
+ primaire existe, telle que la table la déclare (`primaryKeyOf(orders)`, l'id, ou chaque colonne
334
+ d'une clé qui porte le tenant), et dit si elle l'a fait. Elle prend deux instructions au plus,
335
+ c'est pourquoi l'insertion est donnée comme une fonction. Aucune des deux clauses de conflit ne
336
+ suffit seule. Sans cible, PostgreSQL écarte aussi une ligne qui prend une valeur qu'une autre ligne
337
+ détient sous une contrainte d'unicité (un e-mail), et l'enregistrement se lit comme une mise à
338
+ jour perdue. Avec la clé pour cible, deux premiers enregistrements d'un même agrégat faits en même
339
+ temps (une requête livrée deux fois) se rencontrent d'abord sur l'autre index unique, et celui qui
340
+ a perdu est refusé pour une valeur qu'aucune autre ligne ne détient, là où il a perdu une mise à
341
+ jour. La première instruction ne nomme donc aucune cible, et seulement quand elle n'a rien écrit
342
+ la seconde nomme la clé : une clé tenue n'écrit aucune ligne, ce que `optimisticUpdate` lève comme
343
+ une `ConcurrencyError`, et une valeur que détient une autre ligne est refusée par la base, ce
344
+ qu'elle lève comme une `UniqueViolationError` (code `CONFLICT`, 409), comme pour une mise à jour
345
+ qui prend une telle valeur.
346
+
347
+ ### Un verrou sur une clé métier
348
+
349
+ La concurrence optimiste protège une ligne qui existe. Une décision prise sur des lignes qui
350
+ n'existent pas encore (compter les réservations d'un créneau puis en insérer une, donner le
351
+ numéro suivant d'une séquence par *tenant*) n'a pas de version à comparer : deux unités de travail
352
+ lisent le même compte et écrivent toutes les deux. `advisoryLock(context, key, { tenant })` les
353
+ met en file : il attend qu'aucune autre transaction ne tienne le verrou sur `key`, puis le tient
354
+ jusqu'à ce que l'unité de travail valide ou annule (`pg_advisory_xact_lock`). Rien ne le relâche
355
+ à la main.
356
+
357
+ ```ts
358
+ // infrastructure/persistence/drizzle-invoice-numbers.repository.ts
359
+ import { advisoryLock } from '@ddd-ts-kit/drizzle/postgres';
360
+
361
+ async next(): Promise<number> {
362
+ // First in the unit of work, before the read it protects.
363
+ await advisoryLock(this.database, 'invoice-number', { tenant: this.scope });
364
+
365
+ return (await this.lastNumber()) + 1;
366
+ }
367
+ ```
368
+
369
+ - **La clé est un texte**, que PostgreSQL hache vers le nombre de 64 bits qu'il verrouille
370
+ (`hashtextextended(text, 0)`). Avec `tenant`, un `ExecutionScope`, le texte est
371
+ `tenant:<id>:<key>` (`tenantKey` du kernel) : deux *tenants* ne s'attendent jamais, et un
372
+ travail qui ne nomme aucun *tenant* est refusé. Deux textes de même hachage, environ une paire
373
+ sur 2^64, s'attendent comme le ferait une seule clé : une attente, jamais une réponse fausse.
374
+ - **Dans une unité de travail seulement.** Hors d'une unité de travail, le verrou serait relâché
375
+ à la fin de son instruction : `AdvisoryLockOutsideUnitOfWorkError`. Garder l'isolation par
376
+ défaut, `read committed` : la lecture qui suit le verrou voit alors ce que le détenteur
377
+ précédent a validé, là où `repeatable read` et `serializable` lisent à l'instant où le verrou
378
+ a été demandé.
379
+ - **`tryAdvisoryLock(context, key, { tenant })`** n'attend pas : `true` quand il a pris le
380
+ verrou, `false` quand une autre transaction le tient (`pg_try_advisory_xact_lock`).
381
+ - **Un cas d'usage n'importe aucun *package* d'ORM.** Le verrou se place dans la méthode du
382
+ *repository* qui en a besoin, ou derrière un port du contexte (`InvoiceNumbering.reserve()`)
383
+ dont l'adaptateur est ce seul appel et dont le *fake* ne fait rien.
384
+ - PostgreSQL seulement. Dans un projet multitenant, `tenancy/scoped-statement` accepte le
385
+ *helper* et signale un `pg_advisory_xact_lock` écrit à la main, comme tout SQL brut.
386
+ - Tenu au contrat `advisoryLockContract` de `@ddd-ts-kit/testing/contracts`. L'attente d'une
387
+ seconde unité de travail est prouvée sur un vrai serveur : PGlite est une seule session, où
388
+ la seconde attend la connexion elle-même.
337
389
 
338
390
  ## Colonnes d'audit, restriction au tenant et pages
339
391
 
@@ -357,9 +409,9 @@ import {
357
409
  auditColumns,
358
410
  contextSchema,
359
411
  DrizzleContext,
412
+ insertIgnoringConflict,
360
413
  optimisticUpdate,
361
414
  ownTenantCondition,
362
- primaryKeyOf,
363
415
  tenantColumn,
364
416
  tenantCondition,
365
417
  } from '@ddd-ts-kit/drizzle/postgres';
@@ -429,19 +481,17 @@ export class DrizzleInvoiceRepository implements InvoiceRepository {
429
481
  async save(invoice: Invoice): Promise<void> {
430
482
  await optimisticUpdate(invoice, async ({ expected, next }) => {
431
483
  const state = { id: invoice.id, amount: invoice.amount, status: invoice.status, version: next };
432
- const written = expected === 0 ? await this.insert(state) : await this.update(state, expected);
433
484
 
434
- return written.length;
485
+ return expected === 0 ? this.insert(state) : (await this.update(state, expected)).length;
435
486
  });
436
487
  }
437
488
 
438
- private insert(state: VersionedInvoice) {
489
+ private async insert(state: VersionedInvoice): Promise<number> {
439
490
  // tenant_id vient du travail en cours, created_* et updated_* de son acteur et de la Clock
440
491
  const row = { ...state, ...tenantScopeOf(this.scope), ...stampCreation(this.scope, this.clock) };
492
+ const insertion = () => this.database.executor().insert(invoices).values(row);
441
493
 
442
- const insertion = this.database.executor().insert(invoices).values(row);
443
-
444
- return insertion.onConflictDoNothing({ target: primaryKeyOf(invoices) }).returning({ id: invoices.id });
494
+ return (await insertIgnoringConflict(insertion, invoices)) ? 1 : 0;
445
495
  }
446
496
 
447
497
  private update(state: VersionedInvoice, expected: number) {
@@ -702,7 +752,7 @@ requête : `where` (les filtres, le périmètre de l'acteur et le *keyset* d'une
702
752
  par le champ qui départage), `limit` et `offset`. `predicateToDrizzle(predicate, columns)` donne
703
753
  une condition. `columns` associe chaque champ du modèle de lecture à sa colonne, et c'est la
704
754
  seule source d'identifiants : chaque valeur est un paramètre encodé par sa colonne, une
705
- recherche textuelle est `like $1 escape $2`, avec `%`, `_` et `\` échappés.
755
+ recherche textuelle est `like $1 escape $2`, avec `%`, `_` et `\` échappés. `containsIgnoringCase` et `startsWithIgnoringCase` sont la même recherche en `ILIKE`, que PostgreSQL replie avec la locale de la base (la règle et ses limites sont dans le README du kernel, « Ce que signifient des critères ») ; aucun index b-tree ne la sert, un index GIN de `pg_trgm` sur la colonne le fait.
706
756
 
707
757
  Un port de lecture déclare ce qu'un appelant peut demander avec `defineCriteria` ; une requête
708
758
  à vous sur la table d'un modèle de lecture planifie les critères, puis remet le plan au
@@ -737,8 +787,8 @@ abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
737
787
  // infrastructure/persistence/appointment-list.schema.ts
738
788
  export const appointmentList = contextSchema('scheduling').table('appointment_list', {
739
789
  id: text('id').primaryKey(),
740
- status: text('status').notNull(),
741
- startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }).notNull(),
790
+ status: text('status'), // NULL dans une ligne supprimée, comme chaque colonne de la ligne
791
+ startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }),
742
792
  ...readModelColumns(), // last_event_id, last_event_at, last_event_version, deleted
743
793
  });
744
794
 
@@ -759,7 +809,7 @@ export async function searchAppointments(
759
809
  const { where, counted, orderBy, limit, offset } = criteriaToDrizzle(plan, COLUMNS);
760
810
  const live = eq(appointmentList.deleted, false); // une ligne supprimée reste dans la table, marquée
761
811
  const db = database.executor();
762
- const rows = await db
812
+ const selected = await db
763
813
  .select(COLUMNS)
764
814
  .from(appointmentList)
765
815
  .where(and(where, live))
@@ -767,6 +817,11 @@ export async function searchAppointments(
767
817
  .limit(limit)
768
818
  .offset(offset);
769
819
 
820
+ // la contrainte de vérification tient ces colonnes pour une ligne vivante, ce que leurs types ne peuvent pas dire
821
+ const rows = selected.flatMap(({ id, status, startsAt }) =>
822
+ status === null || startsAt === null ? [] : [{ id, status, startsAt }],
823
+ );
824
+
770
825
  // Une page par offset compte son total ; une page par curseur sait ce qui suit grâce à la ligne en trop.
771
826
  const total = plan.kind === 'offset' ? await db.$count(appointmentList, and(counted, live)) : undefined;
772
827
 
@@ -790,7 +845,7 @@ entier est `integer` : un `bigint` revient du pilote sous forme de chaîne.
790
845
  ## Modèles de lecture
791
846
 
792
847
  L'adaptateur d'un port de modèle de lecture étend `DrizzleReadModelStore` et n'ajoute rien : il
793
- en reçoit `get`, `upsertIfNewer`, `delete` et `search`.
848
+ en reçoit `get`, `upsertIfNewer`, `updateIfNewer`, `delete` et `search`.
794
849
 
795
850
  <!-- checked sample -->
796
851
  ```ts
@@ -812,8 +867,8 @@ abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
812
867
  // infrastructure/persistence/appointment-list.schema.ts
813
868
  export const appointmentList = contextSchema('scheduling').table('appointment_list', {
814
869
  id: text('id').primaryKey(),
815
- status: text('status').notNull(),
816
- startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }).notNull(),
870
+ status: text('status'), // NULL dans une ligne supprimée, comme chaque colonne de la ligne
871
+ startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }),
817
872
  ...readModelColumns(), // last_event_id, last_event_at, last_event_version, deleted
818
873
  });
819
874
 
@@ -834,8 +889,15 @@ export class DrizzleAppointmentList extends DrizzleReadModelStore<AppointmentRow
834
889
  Chaque écriture passe par `TableReadModelStore` du noyau : une ligne n'est écrite que si son
835
890
  événement est plus récent que celui qu'elle porte, sur l'exécuteur de l'unité de travail, si
836
891
  bien que la ligne et la marque d'événement traité sont validées ensemble. Une ligne supprimée
837
- reste dans la table avec `deleted` posé : une requête à vous sur la table écarte ces lignes, et
838
- un index unique aussi (`WHERE NOT deleted`). `store.table` est ce que prend
892
+ reste dans la table comme une trace, avec `deleted` positionné : sa clé et son tampon, et NULL
893
+ dans toutes les autres colonnes, ce pour quoi chaque colonne de la ligne accepte NULL. La
894
+ suppression d'une clé que la table ne tient pas encore laisse la même trace. Une contrainte de
895
+ vérification garde entières les lignes vivantes (`check (deleted or (status is not null and
896
+ starts_at is not null))`), une requête à vous sur la table écarte les lignes supprimées
897
+ (`deleted = false`), et une table dont des colonnes refusent NULL est refusée par
898
+ `ReadModelTableNotReadyError`, à la construction du registre d'après sa définition et, avant
899
+ l'écriture de la première trace, par une lecture des colonnes que tient la base
900
+ ([Ce que laisse une ligne supprimée](../../docs/concepts/cqrs.fr.md#la-table-dun-modèle-de-lecture-et-ce-que-laisse-une-ligne-supprimée)). Une application n'attend pas cette première trace : `tableState()` d'un `DrizzleReadModelStore` lit sa table comme le registre le fait avant sa première trace, pour les colonnes qu'il associe et aucune autre, et `ReadModelTables` du noyau le demande à chaque registre que l'application liste, puis refuse avec `ReadModelTablesNotReadyError`, qui nomme chaque table qui n'est pas prête, ce qui l'en empêche et la migration à écrire en deux étapes, ainsi que chaque table qu'il n'a pas pu lire ; un projet généré garde la liste, vérifie à son démarrage les tables des contextes qu'il héberge, et `npm run db:read-models` la vérifie avant un déploiement ([Chaque table vérifiée au démarrage, et avant un déploiement](../../docs/concepts/cqrs.fr.md#chaque-table-vérifiée-au-démarrage-et-avant-un-déploiement)). `store.table` est ce que prend
839
901
  `ProjectionRebuild` ; la reconstruction est réservée à PostgreSQL (une copie `<table>__rebuild`
840
902
  faite `LIKE ... INCLUDING ALL`, les clés écrites entre-temps dans `<table>__touched`, l'échange
841
903
  par renommage en une transaction) et ses garanties et limites sont dans le README de
package/README.md CHANGED
@@ -233,7 +233,7 @@ import { and, eq } from 'drizzle-orm';
233
233
  import { integer, text, type PgQueryResultHKT } from 'drizzle-orm/pg-core';
234
234
  import { AggregateRoot } from '@ddd-ts-kit/kernel';
235
235
  import { Repository } from '@ddd-ts-kit/kernel/declarations';
236
- import { contextSchema, DrizzleContext, optimisticUpdate, primaryKeyOf } from '@ddd-ts-kit/drizzle/postgres';
236
+ import { contextSchema, DrizzleContext, insertIgnoringConflict, optimisticUpdate } from '@ddd-ts-kit/drizzle/postgres';
237
237
 
238
238
  // The aggregate and its port of the previous sample, reduced to their shape.
239
239
  type OrderStatus = 'open' | 'placed';
@@ -289,14 +289,16 @@ export class DrizzleOrderRepository implements OrderRepository {
289
289
 
290
290
  await optimisticUpdate(order, async ({ expected, next }) => {
291
291
  const row = OrderMapper.toRow(order, next);
292
- const written =
293
- expected === 0
294
- ? await db.insert(orders).values(row).onConflictDoNothing({ target: primaryKeyOf(orders) }).returning({ id: orders.id })
295
- : await db
296
- .update(orders)
297
- .set(row)
298
- .where(and(eq(orders.id, order.id), eq(orders.version, expected)))
299
- .returning({ id: orders.id });
292
+
293
+ if (expected === 0) {
294
+ return (await insertIgnoringConflict(() => db.insert(orders).values(row), orders)) ? 1 : 0;
295
+ }
296
+
297
+ const written = await db
298
+ .update(orders)
299
+ .set(row)
300
+ .where(and(eq(orders.id, order.id), eq(orders.version, expected)))
301
+ .returning({ id: orders.id });
300
302
 
301
303
  return written.length; // 0 rows: optimisticUpdate throws ConcurrencyError
302
304
  });
@@ -316,16 +318,62 @@ with a relational schema (`drizzle(url, { schema })`), declare `Database` as
316
318
 
317
319
  | `expected` | Statement | No row written means |
318
320
  |---|---|---|
319
- | `0`: never saved | `INSERT ... ON CONFLICT (id) DO NOTHING` | the id is taken |
321
+ | `0`: never saved | `insertIgnoringConflict`: `INSERT ... ON CONFLICT DO NOTHING`, then `ON CONFLICT (id) DO NOTHING` when it wrote nothing | the id is taken |
320
322
  | `n` | `UPDATE ... SET version = n + 1 WHERE id = ... AND version = n` | another transaction saved it since it was read |
321
323
 
322
- The conflict target is the primary key alone, as the table declares it
323
- (`onConflictDoNothing({ target: primaryKeyOf(orders) })`, the id, or every column of a key that
324
- holds the tenant): without
325
- it, PostgreSQL also skips a row that takes a value another row holds under a unique constraint
326
- (an email), and the save reads as a lost update. Named, that row is refused by the database,
327
- and `optimisticUpdate` raises `UniqueViolationError` (code `CONFLICT`, 409), as for an update
328
- that takes such a value.
324
+ `insertIgnoringConflict(() => db.insert(orders).values(row), orders)` inserts unless the primary
325
+ key exists, as the table declares it (`primaryKeyOf(orders)`, the id, or every column of a key that
326
+ holds the tenant), and says whether it did. It takes two statements at most, which is why the
327
+ insert is given as a function. Neither conflict clause is enough alone. Without a target,
328
+ PostgreSQL also skips a row that takes a value another row holds under a unique constraint (an
329
+ email), and the save reads as a lost update. With the key as its target, two first saves of one
330
+ aggregate made at once (a request delivered twice) meet on the other unique index first, and the
331
+ one that lost is refused for a value no other row holds, where it lost an update. So the first
332
+ statement names no target, and only when it wrote nothing the second names the key: a key that is
333
+ held writes no row, which `optimisticUpdate` raises as a `ConcurrencyError`, and a value another
334
+ row holds is refused by the database, which it raises as a `UniqueViolationError` (code
335
+ `CONFLICT`, 409), as for an update that takes such a value.
336
+
337
+ ### A lock on a business key
338
+
339
+ Optimistic concurrency protects a row that exists. A decision taken on rows that do not exist
340
+ yet (count the bookings of a slot then insert one, give the next number of a sequence per
341
+ tenant) has no version to compare: two units of work read the same count and both write.
342
+ `advisoryLock(context, key, { tenant })` serialises them: it waits until no other transaction
343
+ holds the lock on `key`, then holds it until the unit of work commits or rolls back
344
+ (`pg_advisory_xact_lock`). Nothing releases it by hand.
345
+
346
+ ```ts
347
+ // infrastructure/persistence/drizzle-invoice-numbers.repository.ts
348
+ import { advisoryLock } from '@ddd-ts-kit/drizzle/postgres';
349
+
350
+ async next(): Promise<number> {
351
+ // First in the unit of work, before the read it protects.
352
+ await advisoryLock(this.database, 'invoice-number', { tenant: this.scope });
353
+
354
+ return (await this.lastNumber()) + 1;
355
+ }
356
+ ```
357
+
358
+ - **The key is a text**, hashed by PostgreSQL into the 64-bit number it locks on
359
+ (`hashtextextended(text, 0)`). With `tenant`, an `ExecutionScope`, the text is
360
+ `tenant:<id>:<key>` (`tenantKey` of the kernel): two tenants never wait for each other, and
361
+ work that names no tenant is refused. Two texts of the same hash, about one pair in 2^64,
362
+ wait for each other as one key would: a wait, never a wrong answer.
363
+ - **Inside a unit of work only.** Outside of one the lock would be released as its statement
364
+ ends: `AdvisoryLockOutsideUnitOfWorkError`. Keep the default isolation, `read committed`:
365
+ the read that follows the lock then sees what the previous holder committed, where
366
+ `repeatable read` and `serializable` read as of the moment the lock was asked.
367
+ - **`tryAdvisoryLock(context, key, { tenant })`** does not wait: `true` when it took the lock,
368
+ `false` when another transaction holds it (`pg_try_advisory_xact_lock`).
369
+ - **A use case imports no ORM package.** The lock sits in the method of the repository that
370
+ needs it, or behind a port of the context (`InvoiceNumbering.reserve()`) whose adapter is
371
+ this one call and whose fake does nothing.
372
+ - PostgreSQL only. In a tenant-scoped project, `tenancy/scoped-statement` accepts the helper
373
+ and reports a raw `pg_advisory_xact_lock`, as any raw SQL.
374
+ - Held to `advisoryLockContract` of `@ddd-ts-kit/testing/contracts`. The wait of a second unit
375
+ of work is proven on a real server: PGlite is one session, where the second one waits for
376
+ the connection itself.
329
377
 
330
378
  ## Audit columns, tenant scoping and pages
331
379
 
@@ -348,9 +396,9 @@ import {
348
396
  auditColumns,
349
397
  contextSchema,
350
398
  DrizzleContext,
399
+ insertIgnoringConflict,
351
400
  optimisticUpdate,
352
401
  ownTenantCondition,
353
- primaryKeyOf,
354
402
  tenantColumn,
355
403
  tenantCondition,
356
404
  } from '@ddd-ts-kit/drizzle/postgres';
@@ -420,19 +468,17 @@ export class DrizzleInvoiceRepository implements InvoiceRepository {
420
468
  async save(invoice: Invoice): Promise<void> {
421
469
  await optimisticUpdate(invoice, async ({ expected, next }) => {
422
470
  const state = { id: invoice.id, amount: invoice.amount, status: invoice.status, version: next };
423
- const written = expected === 0 ? await this.insert(state) : await this.update(state, expected);
424
471
 
425
- return written.length;
472
+ return expected === 0 ? this.insert(state) : (await this.update(state, expected)).length;
426
473
  });
427
474
  }
428
475
 
429
- private insert(state: VersionedInvoice) {
476
+ private async insert(state: VersionedInvoice): Promise<number> {
430
477
  // tenant_id from the work in progress, created_* and updated_* from its actor and the Clock
431
478
  const row = { ...state, ...tenantScopeOf(this.scope), ...stampCreation(this.scope, this.clock) };
479
+ const insertion = () => this.database.executor().insert(invoices).values(row);
432
480
 
433
- const insertion = this.database.executor().insert(invoices).values(row);
434
-
435
- return insertion.onConflictDoNothing({ target: primaryKeyOf(invoices) }).returning({ id: invoices.id });
481
+ return (await insertIgnoringConflict(insertion, invoices)) ? 1 : 0;
436
482
  }
437
483
 
438
484
  private update(state: VersionedInvoice, expected: number) {
@@ -685,7 +731,7 @@ query: `where` (the filters, the scope of the actor and the keyset of a cursor p
685
731
  the tie-breaker), `limit` and `offset`. `predicateToDrizzle(predicate, columns)` gives one
686
732
  condition. `columns` maps each field of the read model to its column, and is the only source
687
733
  of identifiers: every value is a parameter encoded by its column, a text search is
688
- `like $1 escape $2` with `%`, `_` and `\` escaped.
734
+ `like $1 escape $2` with `%`, `_` and `\` escaped. `containsIgnoringCase` and `startsWithIgnoringCase` are the same search as an `ILIKE`, which PostgreSQL folds with the locale of the database (the rule and its limits are in the README of the kernel, "What a criteria means"); no b-tree index serves it, a GIN index of `pg_trgm` on the column does.
689
735
 
690
736
  A read port declares what a caller may ask with `defineCriteria`; a query of your own on the
691
737
  table of a read model plans the criteria, then hands the plan to the translator:
@@ -719,8 +765,8 @@ abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
719
765
  // infrastructure/persistence/appointment-list.schema.ts
720
766
  export const appointmentList = contextSchema('scheduling').table('appointment_list', {
721
767
  id: text('id').primaryKey(),
722
- status: text('status').notNull(),
723
- startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }).notNull(),
768
+ status: text('status'), // NULL in a deleted row, as every column of the row
769
+ startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }),
724
770
  ...readModelColumns(), // last_event_id, last_event_at, last_event_version, deleted
725
771
  });
726
772
 
@@ -741,7 +787,7 @@ export async function searchAppointments(
741
787
  const { where, counted, orderBy, limit, offset } = criteriaToDrizzle(plan, COLUMNS);
742
788
  const live = eq(appointmentList.deleted, false); // a removed row stays in the table, flagged
743
789
  const db = database.executor();
744
- const rows = await db
790
+ const selected = await db
745
791
  .select(COLUMNS)
746
792
  .from(appointmentList)
747
793
  .where(and(where, live))
@@ -749,6 +795,11 @@ export async function searchAppointments(
749
795
  .limit(limit)
750
796
  .offset(offset);
751
797
 
798
+ // the check constraint holds these columns for a live row, which their types cannot say
799
+ const rows = selected.flatMap(({ id, status, startsAt }) =>
800
+ status === null || startsAt === null ? [] : [{ id, status, startsAt }],
801
+ );
802
+
752
803
  // An offset page counts its total; a cursor page knows what follows from the extra row.
753
804
  const total = plan.kind === 'offset' ? await db.$count(appointmentList, and(counted, live)) : undefined;
754
805
 
@@ -771,7 +822,7 @@ An integer is `integer`: a `bigint` comes back as a string from the driver.
771
822
  ## Read models
772
823
 
773
824
  The adapter of a read model port extends `DrizzleReadModelStore` and adds nothing: it gets
774
- `get`, `upsertIfNewer`, `delete` and `search` from it.
825
+ `get`, `upsertIfNewer`, `updateIfNewer`, `delete` and `search` from it.
775
826
 
776
827
  <!-- checked sample -->
777
828
  ```ts
@@ -793,8 +844,8 @@ abstract class Database extends DrizzleContext<PgQueryResultHKT> {}
793
844
  // infrastructure/persistence/appointment-list.schema.ts
794
845
  export const appointmentList = contextSchema('scheduling').table('appointment_list', {
795
846
  id: text('id').primaryKey(),
796
- status: text('status').notNull(),
797
- startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }).notNull(),
847
+ status: text('status'), // NULL in a deleted row, as every column of the row
848
+ startsAt: timestamp('starts_at', { withTimezone: true, mode: 'date' }),
798
849
  ...readModelColumns(), // last_event_id, last_event_at, last_event_version, deleted
799
850
  });
800
851
 
@@ -814,9 +865,14 @@ export class DrizzleAppointmentList extends DrizzleReadModelStore<AppointmentRow
814
865
 
815
866
  Every write goes through `TableReadModelStore` of the kernel: a row is written only if its
816
867
  event is newer than the one it holds, on the executor of the unit of work, so the row and the
817
- processed-event mark commit together. A removed row stays in the table with `deleted` set:
818
- a query of your own on the table leaves those rows out, and so does a unique index
819
- (`WHERE NOT deleted`). `store.table` is what `ProjectionRebuild` takes; the rebuild is
868
+ processed-event mark commit together. A removed row stays in the table as a trace, with `deleted`
869
+ set: its key and its stamp, and NULL in every other column, which is why every column of the row
870
+ is nullable. A deletion of a key the table does not hold yet leaves the same trace. A check
871
+ constraint keeps the live rows whole (`check (deleted or (status is not null and starts_at is
872
+ not null))`), a query of your own on the table leaves the deleted rows out (`deleted = false`),
873
+ and a table whose columns refuse NULL is refused with `ReadModelTableNotReadyError`, when the store is built from its definition and, before the first
874
+ trace is written, from one read of the columns the database holds
875
+ ([What a deleted row leaves](../../docs/concepts/cqrs.md#the-table-of-a-read-model-and-what-a-deleted-row-leaves)). An application does not wait for that first trace: `tableState()` of a `DrizzleReadModelStore` reads its table as the store does before its first trace, for the columns it maps and no other, and `ReadModelTables` of the kernel asks it of every store the application lists, then refuses with `ReadModelTablesNotReadyError`, which names each table that is not ready, what keeps it from it and the migration to write in two steps, and each table it could not read; a generated project keeps the list, checks at its start the tables of the contexts it hosts, and `npm run db:read-models` checks it before a deployment ([Every table checked at the start, and before a deployment](../../docs/concepts/cqrs.md#every-table-checked-at-the-start-and-before-a-deployment)). `store.table` is what `ProjectionRebuild` takes; the rebuild is
820
876
  PostgreSQL only (a copy `<table>__rebuild` made `LIKE ... INCLUDING ALL`, the keys written
821
877
  meanwhile in `<table>__touched`, the swap by rename in one transaction) and its guarantees
822
878
  and limits are in the README of `@ddd-ts-kit/kernel` ([Rebuild](../kernel/README.md#rebuild)).
@@ -0,0 +1,16 @@
1
+ import { type AdvisoryLockOptions } from '@ddd-ts-kit/kernel';
2
+ import type { DrizzleLockingContext } from './drizzle-locking-context.js';
3
+ /**
4
+ * Serialises the units of work that take the same key: waits until no other transaction holds
5
+ * the lock on `key`, then holds it until the unit of work commits or rolls back
6
+ * (`pg_advisory_xact_lock`). For a decision no row can carry a version for: count then insert, the
7
+ * next number of a sequence per tenant. Taken first in the unit of work, before what it protects
8
+ * is read; the same key taken twice in one unit of work is held once.
9
+ *
10
+ * The key is hashed by PostgreSQL (`advisoryLockKey` of the kernel says how, and what a collision
11
+ * costs); with `tenant`, two tenants never wait for each other. Refused outside a unit of work
12
+ * (`AdvisoryLockOutsideUnitOfWorkError`). PostgreSQL only. It is the one way an adapter of a
13
+ * tenant-scoped project takes such a lock (`tenancy/scoped-statement`).
14
+ */
15
+ export declare function advisoryLock(context: DrizzleLockingContext, key: string, options?: AdvisoryLockOptions): Promise<void>;
16
+ //# sourceMappingURL=advisory-lock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"advisory-lock.d.ts","sourceRoot":"","sources":["../../../src/postgres/locks/advisory-lock.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,KAAK,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAC/E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAEvE;;;;;;;;;;;GAWG;AACH,wBAAsB,YAAY,CAChC,OAAO,EAAE,qBAAqB,EAC9B,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,mBAAwB,GAChC,OAAO,CAAC,IAAI,CAAC,CAIf"}
@@ -0,0 +1,19 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { advisoryLockKey } from '@ddd-ts-kit/kernel';
3
+ /**
4
+ * Serialises the units of work that take the same key: waits until no other transaction holds
5
+ * the lock on `key`, then holds it until the unit of work commits or rolls back
6
+ * (`pg_advisory_xact_lock`). For a decision no row can carry a version for: count then insert, the
7
+ * next number of a sequence per tenant. Taken first in the unit of work, before what it protects
8
+ * is read; the same key taken twice in one unit of work is held once.
9
+ *
10
+ * The key is hashed by PostgreSQL (`advisoryLockKey` of the kernel says how, and what a collision
11
+ * costs); with `tenant`, two tenants never wait for each other. Refused outside a unit of work
12
+ * (`AdvisoryLockOutsideUnitOfWorkError`). PostgreSQL only. It is the one way an adapter of a
13
+ * tenant-scoped project takes such a lock (`tenancy/scoped-statement`).
14
+ */
15
+ export async function advisoryLock(context, key, options = {}) {
16
+ const text = advisoryLockKey(context, key, options);
17
+ await context.executor().execute(sql `select pg_advisory_xact_lock(hashtextextended(${text}, 0))`);
18
+ }
19
+ //# sourceMappingURL=advisory-lock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"advisory-lock.js","sourceRoot":"","sources":["../../../src/postgres/locks/advisory-lock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,eAAe,EAA4B,MAAM,oBAAoB,CAAC;AAG/E;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,OAA8B,EAC9B,GAAW,EACX,OAAO,GAAwB,EAAE;IAEjC,MAAM,IAAI,GAAG,eAAe,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAEpD,MAAM,OAAO,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,CAAA,iDAAiD,IAAI,OAAO,CAAC,CAAC;AACpG,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { SqlExecutor } from '../tenancy/sql-executor.js';
2
+ /** What an advisory lock needs of a `DrizzleContext`, whatever its driver and its schema. */
3
+ export interface DrizzleLockingContext {
4
+ executor(): SqlExecutor;
5
+ inTransaction(): boolean;
6
+ }
7
+ //# sourceMappingURL=drizzle-locking-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drizzle-locking-context.d.ts","sourceRoot":"","sources":["../../../src/postgres/locks/drizzle-locking-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAE3D,6FAA6F;AAC7F,MAAM,WAAW,qBAAqB;IACpC,QAAQ,IAAI,WAAW,CAAC;IACxB,aAAa,IAAI,OAAO,CAAC;CAC1B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=drizzle-locking-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drizzle-locking-context.js","sourceRoot":"","sources":["../../../src/postgres/locks/drizzle-locking-context.ts"],"names":[],"mappings":""}
@@ -0,0 +1,10 @@
1
+ import { type AdvisoryLockOptions } from '@ddd-ts-kit/kernel';
2
+ import type { DrizzleLockingContext } from './drizzle-locking-context.js';
3
+ /**
4
+ * `advisoryLock` without the wait: takes the lock on `key` for the unit of work if no other
5
+ * transaction holds it and answers `true`, answers `false` at once otherwise
6
+ * (`pg_try_advisory_xact_lock`). For work that is skipped, not queued, when somebody else is
7
+ * already at it.
8
+ */
9
+ export declare function tryAdvisoryLock(context: DrizzleLockingContext, key: string, options?: AdvisoryLockOptions): Promise<boolean>;
10
+ //# sourceMappingURL=try-advisory-lock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"try-advisory-lock.d.ts","sourceRoot":"","sources":["../../../src/postgres/locks/try-advisory-lock.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,KAAK,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE/E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAEvE;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,OAAO,EAAE,qBAAqB,EAC9B,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,mBAAwB,GAChC,OAAO,CAAC,OAAO,CAAC,CAQlB"}
@@ -0,0 +1,15 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { advisoryLockKey } from '@ddd-ts-kit/kernel';
3
+ import { rowsOf } from '../read-model/rows-of.js';
4
+ /**
5
+ * `advisoryLock` without the wait: takes the lock on `key` for the unit of work if no other
6
+ * transaction holds it and answers `true`, answers `false` at once otherwise
7
+ * (`pg_try_advisory_xact_lock`). For work that is skipped, not queued, when somebody else is
8
+ * already at it.
9
+ */
10
+ export async function tryAdvisoryLock(context, key, options = {}) {
11
+ const text = advisoryLockKey(context, key, options);
12
+ const [answered] = rowsOf(await context.executor().execute(sql `select pg_try_advisory_xact_lock(hashtextextended(${text}, 0)) as acquired`));
13
+ return answered?.['acquired'] === true;
14
+ }
15
+ //# sourceMappingURL=try-advisory-lock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"try-advisory-lock.js","sourceRoot":"","sources":["../../../src/postgres/locks/try-advisory-lock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,eAAe,EAA4B,MAAM,oBAAoB,CAAC;AAC/E,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAG/C;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,OAA8B,EAC9B,GAAW,EACX,OAAO,GAAwB,EAAE;IAEjC,MAAM,IAAI,GAAG,eAAe,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAEpD,MAAM,CAAC,QAAQ,CAAC,GAAG,MAAM,CACvB,MAAM,OAAO,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,CAAA,qDAAqD,IAAI,mBAAmB,CAAC,CAClH,CAAC;IAEF,OAAO,QAAQ,EAAE,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC;AACzC,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { type ExtractTablesWithRelations, type TablesRelationalConfig } from 'drizzle-orm';
2
2
  import { type PgQueryResultHKT } from 'drizzle-orm/pg-core';
3
- import { type CriteriaPlan, type EventStamp, type SearchedRows, type ReadModelRows, type ReadModelTable, type StampedRow, type TouchedKey } from '@ddd-ts-kit/kernel';
3
+ import { type CriteriaPlan, type EventStamp, type SearchedRows, type ReadModelRows, type ReadModelTable, type ReadModelTableState, type StampedRow, type TouchedKey } from '@ddd-ts-kit/kernel';
4
4
  import type { DrizzleContext } from '../unit-of-work/drizzle-context.js';
5
5
  import type { DrizzleReadModelOptions } from './drizzle-read-model-options.js';
6
6
  /**
@@ -15,11 +15,14 @@ export declare class DrizzleReadModelTable<Row extends object, Q extends PgQuery
15
15
  private readonly rows;
16
16
  private readonly copy;
17
17
  private readonly rebuild;
18
+ private readonly traces;
18
19
  constructor(context: DrizzleContext<Q, F, S>, options: DrizzleReadModelOptions<Row>);
19
20
  find(key: string): Promise<StampedRow<Row> | undefined>;
20
21
  insert(entry: StampedRow<Row>): Promise<boolean>;
21
22
  replace(entry: StampedRow<Row>, held: EventStamp): Promise<boolean>;
22
23
  search(plan: CriteriaPlan): Promise<SearchedRows<Row>>;
24
+ /** What the table can hold of the trace of a deleted row, read as before the first trace: what `ReadModelTables` asks. */
25
+ tableState(): Promise<ReadModelTableState>;
23
26
  rebuilding(): Promise<boolean>;
24
27
  touch(key: string): Promise<void>;
25
28
  beginRebuild(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle-read-model-table.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/drizzle-read-model-table.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,0BAA0B,EAAE,KAAK,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACzG,OAAO,EAAkB,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,UAAU,EACf,KAAK,UAAU,EAChB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAGtE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAM5E;;;;GAIG;AACH,qBAAa,qBAAqB,CAChC,GAAG,SAAS,MAAM,EAClB,CAAC,SAAS,gBAAgB,EAC1B,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,EACzD,CAAC,SAAS,sBAAsB,GAAG,0BAA0B,CAAC,CAAC,CAAC,CAChE,YAAW,cAAc,CAAC,GAAG,CAAC;IAW5B,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAV1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAe;IAEtC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAmC;IAExD,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAmC;IAExD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA2B;IAEnD,YACmB,OAAO,EAAE,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAChC,OAAO,EAAE,uBAAuB,CAAC,GAAG,CAAC,EAoBvD;IAED,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,CAEtD;IAED,MAAM,CAAC,KAAK,EAAE,UAAU,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAE/C;IAED,OAAO,CAAC,KAAK,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAElE;IAEK,MAAM,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAmB3D;IAED,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC,CAE7B;IAED,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhC;IAED,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAE5B;IAED,MAAM,IAAI,aAAa,CAAC,GAAG,CAAC,CAE3B;IAED,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,UAAU,EAAE,CAAC,CAErD;IAED,MAAM,CAAC,IAAI,EAAE,SAAS,UAAU,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAEjD;IAED,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3B;IAED,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAEvB;IAED,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CAE9B;IAED,gHAAgH;YAClG,GAAG;CAelB"}
1
+ {"version":3,"file":"drizzle-read-model-table.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/drizzle-read-model-table.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,0BAA0B,EAAE,KAAK,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACzG,OAAO,EAAiC,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC3F,OAAO,EAKL,KAAK,YAA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,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,CAElE;IAEK,MAAM,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAmB3D;IAED,0HAA0H;IAC1H,UAAU,IAAI,OAAO,CAAC,mBAAmB,CAAC,CAEzC;IAED,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC,CAE7B;IAED,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhC;IAED,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAE5B;IAED,MAAM,IAAI,aAAa,CAAC,GAAG,CAAC,CAE3B;IAED,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,UAAU,EAAE,CAAC,CAErD;IAED,MAAM,CAAC,IAAI,EAAE,SAAS,UAAU,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAEjD;IAED,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3B;IAED,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAEvB;IAED,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CAE9B;IAED,gHAAgH;YAClG,GAAG;CAelB"}
@@ -1,6 +1,6 @@
1
1
  import { and, eq, sql } from 'drizzle-orm';
2
2
  import { getTableConfig } from 'drizzle-orm/pg-core';
3
- import { PostgresReadModelRebuild, } from '@ddd-ts-kit/kernel';
3
+ import { PostgresReadModelRebuild, PostgresTraceColumns, ReadModelTableNotReadyError, } from '@ddd-ts-kit/kernel';
4
4
  import { tenantCondition } from '../tenancy/tenant-condition.js';
5
5
  import { criteriaToDrizzle } from './criteria-to-drizzle.js';
6
6
  import { DrizzleStampedRows } from './drizzle-stamped-rows.js';
@@ -19,22 +19,29 @@ export class DrizzleReadModelTable {
19
19
  rows;
20
20
  copy;
21
21
  rebuild;
22
+ traces;
22
23
  constructor(context, options) {
23
24
  this.context = context;
24
25
  this.options = options;
25
26
  const { name, schema } = getTableConfig(options.table);
27
+ const stamps = stampColumns(options.table);
28
+ const named = { table: name, deleted: stamps.deleted.name, ...(schema === undefined ? {} : { schema }) };
29
+ const data = holdsTraces(options, named);
30
+ this.traces = new PostgresTraceColumns((statement, parameters) => this.run(statement, parameters), () => ({ ...named, data }));
26
31
  this.target = {
27
32
  schema,
28
33
  name,
29
34
  key: options.key,
30
35
  columns: options.columns,
31
- stamps: stampColumns(options.table),
36
+ stamps,
37
+ traces: this.traces,
32
38
  ...(options.tenant === undefined ? {} : { tenant: options.tenant }),
33
39
  };
34
40
  this.rows = new DrizzleStampedRows(context, this.target);
35
41
  this.copy = new DrizzleStampedRows(context, { ...this.target, name: PostgresReadModelRebuild.shadowOf(name) });
36
42
  this.rebuild = new PostgresReadModelRebuild((statement, parameters) => this.run(statement, parameters), {
37
43
  table: name,
44
+ deletedColumn: stamps.deleted.name,
38
45
  ...(schema === undefined ? {} : { schema }),
39
46
  });
40
47
  }
@@ -64,6 +71,10 @@ export class DrizzleReadModelTable {
64
71
  const rows = records.map((record) => mapper.fromSelected(record));
65
72
  return plan.kind === 'cursor' ? { rows } : { rows, total: await db.$count(table, and(kept, counted)) };
66
73
  }
74
+ /** What the table can hold of the trace of a deleted row, read as before the first trace: what `ReadModelTables` asks. */
75
+ tableState() {
76
+ return this.traces.state();
77
+ }
67
78
  rebuilding() {
68
79
  return this.rebuild.rebuilding();
69
80
  }
@@ -98,4 +109,27 @@ export class DrizzleReadModelTable {
98
109
  return rowsOf(await this.context.executor().execute(query));
99
110
  }
100
111
  }
112
+ /**
113
+ * Refuses, when the store is built, a table whose definition could not hold the trace of a
114
+ * deleted row: every column of the row accepts NULL, the key and the tenant apart. An early
115
+ * signal: the database is asked before the first trace. Answers the columns of the row.
116
+ */
117
+ function holdsTraces({ columns, key, tenant }, named) {
118
+ const mapped = Object.values(columns);
119
+ const kept = new Set([key.name, tenant?.column.name]);
120
+ const data = mapped.filter((column) => !kept.has(column.name));
121
+ const row = data.map((column) => column.name);
122
+ const refusing = data.filter((column) => column.notNull).map((column) => column.name);
123
+ if (refusing.length > 0) {
124
+ throw new ReadModelTableNotReadyError({
125
+ ...named,
126
+ deleted: named.deleted ?? 'deleted',
127
+ exists: true,
128
+ refusing,
129
+ unfit: [],
130
+ row,
131
+ });
132
+ }
133
+ return row;
134
+ }
101
135
  //# sourceMappingURL=drizzle-read-model-table.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle-read-model-table.js","sourceRoot":"","sources":["../../../src/postgres/read-model/drizzle-read-model-table.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAgE,MAAM,aAAa,CAAC;AACzG,OAAO,EAAE,cAAc,EAAyB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EACL,wBAAwB,GAQzB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,EAAE,kBAAkB,EAAqB,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C;;;;GAIG;AACH,MAAM,OAAO,qBAAqB;IAgBb,OAAO;IACP,OAAO;IAVT,MAAM,CAAe;IAErB,IAAI,CAAmC;IAEvC,IAAI,CAAmC;IAEvC,OAAO,CAA2B;IAEnD,YACmB,OAAgC,EAChC,OAAqC;uBADrC,OAAO;uBACP,OAAO;QAExB,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAEvD,IAAI,CAAC,MAAM,GAAG;YACZ,MAAM;YACN,IAAI;YACJ,GAAG,EAAE,OAAO,CAAC,GA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O,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAC9D,CAAC;CACF"}
1
+ {"version":3,"file":"drizzle-read-model-table.js","sourceRoot":"","sources":["../../../src/postgres/read-model/drizzle-read-model-table.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAgE,MAAM,aAAa,CAAC;AACzG,OAAO,EAAE,cAAc,EAAwC,MAAM,qBAAqB,CAAC;AAC3F,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,2BAA2B,GAU5B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE1D,OAAO,EAAE,kBAAkB,EAAqB,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C;;;;GAIG;AACH,MAAM,OAAO,qBAAqB;IAkBb,OAAO;IACP,OAAO;IAZT,MAAM,CAAe;IAErB,IAAI,CAAmC;IAEvC,IAAI,CAAmC;IAEvC,OAAO,CAA2B;IAElC,MAAM,CAAuB;IAE9C,YACmB,OAAgC,EAChC,OAAqC;uBADrC,OAAO;uBACP,OAAO;QAExB,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAEvD,MAAM,MAAM,GAAG,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAC3C,MAAM,KAAK,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAA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M,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAEtF,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACxB,MAAM,IAAI,2BAA2B,CAAC;YACpC,GAAG,KAAK;YACR,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,SAAS;YACnC,MAAM,EAAE,IAAI;YACZ,QAAQ;YACR,KAAK,EAAE,EAAE;YACT,GAAG;SACJ,CAAC,CAAC;IACL,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { type TablesRelationalConfig } from 'drizzle-orm';
2
2
  import type { PgColumn, PgQueryResultHKT } from 'drizzle-orm/pg-core';
3
- import { type EventStamp, type ReadModelRows, type StampedRow } from '@ddd-ts-kit/kernel';
3
+ import { type EventStamp, type PostgresTraceColumns, type ReadModelRows, type StampedRow } from '@ddd-ts-kit/kernel';
4
4
  import type { ReadModelTenant } from './read-model-tenant.js';
5
5
  import type { DrizzleContext } from '../unit-of-work/drizzle-context.js';
6
6
  import type { StampColumns } from './stamp-columns.js';
@@ -11,6 +11,8 @@ export interface StampedTable {
11
11
  readonly columns: Readonly<Record<string, PgColumn>>;
12
12
  readonly stamps: StampColumns;
13
13
  readonly tenant?: ReadModelTenant;
14
+ /** Of the table itself, which the copy of a rebuild is made like. */
15
+ readonly traces: PostgresTraceColumns;
14
16
  }
15
17
  /**
16
18
  * The stamped rows of one table, the copy of a rebuild as well as the table itself: the
@@ -25,9 +27,11 @@ export declare class DrizzleStampedRows<Row extends object, Q extends PgQueryRes
25
27
  find(key: string): Promise<StampedRow<Row> | undefined>;
26
28
  insert(entry: StampedRow<Row>): Promise<boolean>;
27
29
  replace(entry: StampedRow<Row>, held: EventStamp): Promise<boolean>;
30
+ private inserted;
28
31
  /** What a read may reach: every row, or those of the tenants of the work for a read model of tenant data. */
29
32
  private reach;
30
33
  private own;
34
+ /** The trace of a deleted row is written once the table is known, in the database, to accept it. */
31
35
  private valuesOf;
32
36
  /** The tenant of a written row, for a read model of tenant data. */
33
37
  private tenantValue;
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle-stamped-rows.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/drizzle-stamped-rows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAiB,KAAK,UAAU,EAAE,KAAK,aAAa,EAAE,KAAK,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEzG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAGtE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;IACrD,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,MAAM,CAAC,EAAE,eAAe,CAAC;CACnC;AAED;;;;GAIG;AACH,qBAAa,kBAAkB,CAC7B,GAAG,SAAS,MAAM,EAClB,CAAC,SAAS,gBAAgB,EAC1B,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,CAAC,SAAS,sBAAsB,CAChC,YAAW,aAAa,CAAC,GAAG,CAAC;IA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,oGAAoG;YACtF,QAAQ;IAqBtB,oEAAoE;IACpE,OAAO,CAAC,WAAW;IAMnB,OAAO,CAAC,KAAK;CAKd"}
@@ -1,5 +1,5 @@
1
1
  import { sql } from 'drizzle-orm';
2
- import { tenantScopeOf } from '@ddd-ts-kit/kernel';
2
+ import { tenantScopeOf, } from '@ddd-ts-kit/kernel';
3
3
  import { reachCondition } from '../tenancy/reach-condition.js';
4
4
  import { RowMapper } from './row.mapper.js';
5
5
  import { rowsOf } from './rows-of.js';
@@ -37,27 +37,31 @@ export class DrizzleStampedRows {
37
37
  };
38
38
  }
39
39
  async insert(entry) {
40
- if (entry.row === undefined) {
41
- return false;
42
- }
43
- const values = this.valuesOf(entry);
40
+ const values = await this.valuesOf(entry);
44
41
  const columns = sql.join(values.map(([column]) => named(column)), sql `, `);
45
42
  const written = sql.join(values.map(([, value]) => sql `${value}`), sql `, `);
46
43
  const key = named(this.target.key);
47
- const inserted = await this.context
48
- .executor()
49
- .execute(sql `insert into ${this.table()} (${columns}) values (${written}) on conflict (${key}) do nothing returning ${key}`);
50
- return rowsOf(inserted).length === 1;
44
+ const row = sql `insert into ${this.table()} (${columns}) values (${written})`;
45
+ // On the key alone, two writers of one key inserting at once may be refused on another unique
46
+ // value of the row they both write. The first statement skips on any unique value; when it wrote
47
+ // nothing, the second names the key: `false` for a key that is held, and the refusal of the
48
+ // database for a value another row holds.
49
+ return ((await this.inserted(sql `${row} on conflict do nothing returning ${key}`)) ||
50
+ this.inserted(sql `${row} on conflict (${key}) do nothing returning ${key}`));
51
51
  }
52
52
  async replace(entry, held) {
53
53
  const { stamps } = this.target;
54
- const changes = sql.join(this.valuesOf(entry).map(([column, value]) => sql `${named(column)} = ${value}`), sql `, `);
54
+ const values = await this.valuesOf(entry);
55
+ const changes = sql.join(values.map(([column, value]) => sql `${named(column)} = ${value}`), sql `, `);
55
56
  const key = named(this.target.key);
56
57
  const replaced = await this.context
57
58
  .executor()
58
- .execute(sql `update ${this.table()} set ${changes} where ${key} = ${entry.key} and ${named(stamps.lastEventId)} = ${held.eventId} and ${named(stamps.lastEventAt)} = ${held.occurredAt.toISOString()} and ${this.own()} returning ${key}`);
59
+ .execute(sql `update ${this.table()} set ${changes} where ${key} = ${entry.key} and ${named(stamps.lastEventId)} = ${held.eventId} and ${named(stamps.lastEventAt)} = ${held.occurredAt.toISOString()} and ${named(stamps.lastEventVersion)} is not distinct from ${held.version ?? null}::bigint and ${this.own()} returning ${key}`);
59
60
  return rowsOf(replaced).length === 1;
60
61
  }
62
+ async inserted(statement) {
63
+ return rowsOf(await this.context.executor().execute(statement)).length === 1;
64
+ }
61
65
  /** What a read may reach: every row, or those of the tenants of the work for a read model of tenant data. */
62
66
  reach() {
63
67
  const { tenant } = this.target;
@@ -67,13 +71,16 @@ export class DrizzleStampedRows {
67
71
  const { tenant } = this.target;
68
72
  return tenant === undefined ? sql `true` : sql `${named(tenant.column)} = ${tenantScopeOf(tenant.scope).tenantId}`;
69
73
  }
70
- valuesOf({ key, row, stamp }) {
71
- const { stamps, tenant } = this.target;
72
- const written = row === undefined
73
- ? []
74
- : this.mapper.toValues(row).filter(([column]) => column !== this.target.key && column !== tenant?.column);
74
+ /** The trace of a deleted row is written once the table is known, in the database, to accept it. */
75
+ async valuesOf({ key, row, stamp }) {
76
+ const { stamps, tenant, traces } = this.target;
77
+ if (row === undefined) {
78
+ await traces.require();
79
+ }
80
+ // A deleted row keeps no data: every column of the row is written NULL, not left to its default.
81
+ const data = row === undefined ? this.mapper.toNulls() : this.mapper.toValues(row);
75
82
  return [
76
- ...written,
83
+ ...data.filter(([column]) => column !== this.target.key && column !== tenant?.column),
77
84
  [this.target.key, key],
78
85
  [stamps.lastEventId, stamp.eventId],
79
86
  [stamps.lastEventAt, stamp.occurredAt.toISOString()],
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle-stamped-rows.js","sourceRoot":"","sources":["../../../src/postgres/read-model/drizzle-stamped-rows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG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G,IAAI,CAAC,MAAM,CAAC;QAE/B,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC7F,CAAC;IAEO,KAAK;QACX,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC;QAErC,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,GAAG,CAAA,GAAG,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAA,GAAG,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;IACtH,CAAC;CACF;AAED,SAAS,KAAK,CAAC,MAAgB;IAC7B,OAAO,GAAG,CAAA,GAAG,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;AAC7C,CAAC"}
@@ -1,4 +1,4 @@
1
- import type { FilterOperator } from '@ddd-ts-kit/kernel';
1
+ import type { TextSearch } from '@ddd-ts-kit/kernel';
2
2
  /** The `LIKE` pattern of a text search, the text itself taken literally: `%`, `_` and `\` are escaped by `\`. */
3
- export declare function likePattern(operator: FilterOperator, text: string): string;
3
+ export declare function likePattern(operator: TextSearch, text: string): string;
4
4
  //# sourceMappingURL=like-pattern.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"like-pattern.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/like-pattern.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEzD,iHAAiH;AACjH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAI1E"}
1
+ {"version":3,"file":"like-pattern.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/like-pattern.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,iHAAiH;AACjH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAItE"}
@@ -1,6 +1,6 @@
1
1
  /** The `LIKE` pattern of a text search, the text itself taken literally: `%`, `_` and `\` are escaped by `\`. */
2
2
  export function likePattern(operator, text) {
3
3
  const literal = text.replace(/[\\%_]/g, (special) => `\\${special}`);
4
- return operator === 'startsWith' ? `${literal}%` : `%${literal}%`;
4
+ return operator === 'startsWith' || operator === 'startsWithIgnoringCase' ? `${literal}%` : `%${literal}%`;
5
5
  }
6
6
  //# sourceMappingURL=like-pattern.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"like-pattern.js","sourceRoot":"","sources":["../../../src/postgres/read-model/like-pattern.ts"],"names":[],"mappings":"AAEA,iHAAiH;AACjH,MAAM,UAAU,WAAW,CAAC,QAAwB,EAAE,IAAY;IAChE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC;IAErE,OAAO,QAAQ,KAAK,YAAY,CAAC,CAAC,CAAC,GAAG,OAAO,GAAG,CAAC,CAAC,CAAC,IAAI,OAAO,GAAG,CAAC;AACpE,CAAC"}
1
+ {"version":3,"file":"like-pattern.js","sourceRoot":"","sources":["../../../src/postgres/read-model/like-pattern.ts"],"names":[],"mappings":"AAEA,iHAAiH;AACjH,MAAM,UAAU,WAAW,CAAC,QAAoB,EAAE,IAAY;IAC5D,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC;IAErE,OAAO,QAAQ,KAAK,YAAY,IAAI,QAAQ,KAAK,wBAAwB,CAAC,CAAC,CAAC,GAAG,OAAO,GAAG,CAAC,CAAC,CAAC,IAAI,OAAO,GAAG,CAAC;AAC7G,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import { type SQL } from 'drizzle-orm';
2
2
  import type { PgColumn } from 'drizzle-orm/pg-core';
3
- import type { Predicate } from '@ddd-ts-kit/kernel';
3
+ import { type Predicate } from '@ddd-ts-kit/kernel';
4
4
  type Columns = Readonly<Record<string, PgColumn>>;
5
5
  /**
6
6
  * A predicate of a criteria plan as a drizzle condition. Every value is a parameter, encoded
@@ -1 +1 @@
1
- {"version":3,"file":"predicate-to-drizzle.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/predicate-to-drizzle.ts"],"names":[],"mappings":"AAAA,OAAO,EAeL,KAAK,GAAG,EACT,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAA6C,SAAS,EAAiB,MAAM,oBAAoB,CAAC;AAI9G,KAAK,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;AAOlD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,SAAS,GAAG,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,GAAG,GAAG,SAAS,CAYtG"}
1
+ {"version":3,"file":"predicate-to-drizzle.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/predicate-to-drizzle.ts"],"names":[],"mappings":"AAAA,OAAO,EAeL,KAAK,GAAG,EACT,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAKL,KAAK,SAAS,EAEf,MAAM,oBAAoB,CAAC;AAI5B,KAAK,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;AAelD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,SAAS,GAAG,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,GAAG,GAAG,SAAS,CAYtG"}
@@ -1,6 +1,14 @@
1
1
  import { and, between, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, or, sql, } from 'drizzle-orm';
2
+ import { isTextSearch, } from '@ddd-ts-kit/kernel';
2
3
  import { columnOf } from './column-of.js';
3
4
  import { likePattern } from './like-pattern.js';
5
+ /** A search that ignores case is an `ilike`: PostgreSQL folds it with the locale of the database, see `foldCase` of the kernel. */
6
+ const LIKE = {
7
+ contains: sql `like`,
8
+ startsWith: sql `like`,
9
+ containsIgnoringCase: sql `ilike`,
10
+ startsWithIgnoringCase: sql `ilike`,
11
+ };
4
12
  const COMPARISONS = { eq, ne, gt, gte, lt, lte };
5
13
  /**
6
14
  * A predicate of a criteria plan as a drizzle condition. Every value is a parameter, encoded
@@ -27,14 +35,14 @@ function tested(test, column) {
27
35
  function compared(operator, value, column) {
28
36
  const values = typeof value === 'object' && !(value instanceof Date) ? [...value] : [value];
29
37
  const [first = null, second = null] = values;
38
+ if (isTextSearch(operator)) {
39
+ return sql `${column} ${LIKE[operator]} ${likePattern(operator, String(first))} escape ${'\\'}`;
40
+ }
30
41
  switch (operator) {
31
42
  case 'in':
32
43
  return inArray(column, values);
33
44
  case 'between':
34
45
  return between(column, first, second);
35
- case 'contains':
36
- case 'startsWith':
37
- return sql `${column} like ${likePattern(operator, String(first))} escape ${'\\'}`;
38
46
  default:
39
47
  return COMPARISONS[operator](column, first);
40
48
  }
@@ -1 +1 @@
1
- {"version":3,"file":"predicate-to-drizzle.js","sourceRoot":"","sources":["../../../src/postgres/read-model/predicate-to-drizzle.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,OAAO,EACP,EAAE,EACF,EAAE,EACF,GAAG,EACH,OAAO,EACP,SAAS,EACT,MAAM,EACN,EAAE,EACF,GAAG,EACH,EAAE,E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AC,CAAC;IAClE,CAAC;IAED,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAE/D,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;AACrD,CAAC;AAED,SAAS,QAAQ,CAAC,QAAoB,EAAE,KAAoB,EAAE,MAAgB;IAC5E,MAAM,MAAM,GAAiB,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAC1G,MAAM,CAAC,KAAK,GAAG,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,GAAG,MAAM,CAAC;IAE7C,IAAI,YAAY,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC3B,OAAO,GAAG,CAAA,GAAG,MAAM,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,WAAW,CAAC,QAAQ,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,WAAW,IAAI,EAAE,CAAC;IACjG,CAAC;IAED,QAAQ,QAAQ,EAAE,CAAC;QACjB,KAAK,IAAI;YACP,OAAO,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,KAAK,SAAS;YACZ,OAAO,OAAO,CAAC,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;QACxC;YACE,OAAO,WAAW,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAChD,CAAC;AACH,CAAC"}
@@ -8,6 +8,8 @@ export declare class RowMapper<Row extends object> {
8
8
  toRow(record: Readonly<Record<string, unknown>>): Row;
9
9
  /** From a record keyed by field, already decoded: what `select(columns)` of the query builder answers. */
10
10
  fromSelected(selected: Readonly<Record<string, unknown>>): Row;
11
+ /** NULL in every column of the row: what a deleted row holds. */
12
+ toNulls(): [PgColumn, unknown][];
11
13
  /** The values of the row by column, encoded as the driver expects them. */
12
14
  toValues(row: Row): [PgColumn, unknown][];
13
15
  }
@@ -1 +1 @@
1
- {"version":3,"file":"row.mapper.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/row.mapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,KAAK,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;AAElD,6FAA6F;AAC7F,qBAAa,SAAS,CAAC,GAAG,SAAS,MAAM;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,OAAO,EAAI;IAEjD,oFAAoF;IACpF,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,GAAG,CAIpD;IAED,0GAA0G;IAC1G,YAAY,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,GAAG,CAE7D;IAED,2EAA2E;IAC3E,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,CAExC;CACF"}
1
+ {"version":3,"file":"row.mapper.d.ts","sourceRoot":"","sources":["../../../src/postgres/read-model/row.mapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,KAAK,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;AAElD,6FAA6F;AAC7F,qBAAa,SAAS,CAAC,GAAG,SAAS,MAAM;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,OAAO,EAAI;IAEjD,oFAAoF;IACpF,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,GAAG,CAIpD;IAED,0GAA0G;IAC1G,YAAY,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,GAAG,CAE7D;IAED,iEAAiE;IACjE,OAAO,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,CAE/B;IAED,2EAA2E;IAC3E,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,CAExC;CACF"}
@@ -12,6 +12,10 @@ export class RowMapper {
12
12
  fromSelected(selected) {
13
13
  return Object.fromEntries(Object.keys(this.columns).map((field) => [field, selected[field] ?? null]));
14
14
  }
15
+ /** NULL in every column of the row: what a deleted row holds. */
16
+ toNulls() {
17
+ return Object.values(this.columns).map((column) => [column, null]);
18
+ }
15
19
  /** The values of the row by column, encoded as the driver expects them. */
16
20
  toValues(row) {
17
21
  return Object.entries(this.columns).map(([field, column]) => [column, encoded(column, Reflect.get(row, field))]);
@@ -1 +1 @@
1
- {"version":3,"file":"row.mapper.js","sourceRoot":"","sources":["../../../src/postgres/read-model/row.mapper.ts"],"names":[],"mappings":"AAIA,6FAA6F;AAC7F,MAAM,OAAO,SAAS;IACS,OAAO;IAApC,YAA6B,OAAgB;uBAAhB,OAAO;IAAY,CAAC;IAEjD,oFAAoF;IACpF,KAAK,CAAC,MAAyC;QAC7C,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAC9F,CAA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KAAc;IAC/C,OAAO,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;AACvF,CAAC"}
@@ -0,0 +1,29 @@
1
+ import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
2
+ /** The insert of one row as the query builder holds it before its conflict clause: `executor.insert(table).values(row)`. */
3
+ export interface IgnoringInsertion {
4
+ onConflictDoNothing(config?: {
5
+ target: PgColumn[];
6
+ }): {
7
+ returning(fields: Record<string, PgColumn>): PromiseLike<readonly unknown[]>;
8
+ };
9
+ }
10
+ /**
11
+ * Inserts one row unless its primary key already exists, and says whether it did insert: the
12
+ * first save of an aggregate under `optimisticUpdate`. Unlike catching the unique violation, it
13
+ * leaves the surrounding transaction usable.
14
+ *
15
+ * Only a conflict on the primary key of `table` is ignored (`primaryKeyOf`): a row that takes a
16
+ * value another row holds under another unique constraint (an email) is refused by the database,
17
+ * as any statement would be.
18
+ *
19
+ * That takes two statements at most, which is why the insert is given as a function. A conflict
20
+ * target on the key alone lets two inserts of one key made at once meet on the other unique index
21
+ * first, and one of them is then refused for a value no other row holds. The first statement
22
+ * skips on any unique value; when it wrote nothing, the second names the key: `false` for a key
23
+ * that is held, and the refusal of the database for a value another row holds.
24
+ *
25
+ * `insertIgnoringConflict(() => executor.insert(invoices).values(row), invoices)`: the statement
26
+ * stays written where the row is, with its tenant.
27
+ */
28
+ export declare function insertIgnoringConflict(insertion: () => IgnoringInsertion, table: PgTable): Promise<boolean>;
29
+ //# sourceMappingURL=insert-ignoring-conflict.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"insert-ignoring-conflict.d.ts","sourceRoot":"","sources":["../../../src/postgres/sql/insert-ignoring-conflict.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAG7D,4HAA4H;AAC5H,MAAM,WAAW,iBAAiB;IAChC,mBAAmB,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,EAAE,QAAQ,EAAE,CAAA;KAAE,GAAG;QACpD,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,GAAG,WAAW,CAAC,SAAS,OAAO,EAAE,CAAC,CAAC;KAC9E,CAAC;CACH;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,sBAAsB,CAAC,SAAS,EAAE,MAAM,iBAAiB,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAQjH"}
@@ -0,0 +1,26 @@
1
+ import { primaryKeyOf } from './primary-key-of.js';
2
+ /**
3
+ * Inserts one row unless its primary key already exists, and says whether it did insert: the
4
+ * first save of an aggregate under `optimisticUpdate`. Unlike catching the unique violation, it
5
+ * leaves the surrounding transaction usable.
6
+ *
7
+ * Only a conflict on the primary key of `table` is ignored (`primaryKeyOf`): a row that takes a
8
+ * value another row holds under another unique constraint (an email) is refused by the database,
9
+ * as any statement would be.
10
+ *
11
+ * That takes two statements at most, which is why the insert is given as a function. A conflict
12
+ * target on the key alone lets two inserts of one key made at once meet on the other unique index
13
+ * first, and one of them is then refused for a value no other row holds. The first statement
14
+ * skips on any unique value; when it wrote nothing, the second names the key: `false` for a key
15
+ * that is held, and the refusal of the database for a value another row holds.
16
+ *
17
+ * `insertIgnoringConflict(() => executor.insert(invoices).values(row), invoices)`: the statement
18
+ * stays written where the row is, with its tenant.
19
+ */
20
+ export async function insertIgnoringConflict(insertion, table) {
21
+ const key = primaryKeyOf(table);
22
+ const returned = Object.fromEntries(key.map((column) => [column.name, column]));
23
+ const wrote = async (conflict) => (await insertion().onConflictDoNothing(conflict).returning(returned)).length === 1;
24
+ return (await wrote()) || wrote({ target: key });
25
+ }
26
+ //# sourceMappingURL=insert-ignoring-conflict.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"insert-ignoring-conflict.js","sourceRoot":"","sources":["../../../src/postgres/sql/insert-ignoring-conflict.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAShD;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,SAAkC,EAAE,KAAc;IAC7F,MAAM,GAAG,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IAChC,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;IAEhF,MAAM,KAAK,GAAG,KAAK,EAAE,QAAiC,EAAoB,EAAE,CAC1E,CAAC,MAAM,SAAS,EAAE,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;IAErF,OAAO,CAAC,MAAM,KAAK,EAAE,CAAC,IAAI,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;AACnD,CAAC"}
@@ -10,6 +10,10 @@ export * from './postgres/outbox/processed-events-table.js';
10
10
  export * from './postgres/outbox/drizzle-outbox-store.js';
11
11
  export * from './postgres/outbox/drizzle-processed-event-store.js';
12
12
  export * from './postgres/sql/primary-key-of.js';
13
+ export * from './postgres/sql/insert-ignoring-conflict.js';
14
+ export * from './postgres/locks/drizzle-locking-context.js';
15
+ export * from './postgres/locks/advisory-lock.js';
16
+ export * from './postgres/locks/try-advisory-lock.js';
13
17
  export * from './postgres/columns/audit-columns.js';
14
18
  export * from './postgres/columns/tenant-column.js';
15
19
  export * from './postgres/read-model/read-model-columns.js';
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EA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,qDAAqD,CAAC;AACpE,cAAc,kCAAkC,CAAC;AACjD,cAAc,yDAAyD,CAAC;AACxE,cAAc,8CAA8C,CAAC;AAC7D,cAAc,gCAAgC,CAAC;AAC/C,cAAc,uCAAuC,CAAC;AACtD,cAAc,0CAA0C,CAAC;AACzD,cAAc,wCAAwC,CAAC;AACvD,cAAc,iDAAiD,CAAC;AAChE,cAAc,+BAA+B,CAAC;AAC9C,cAAc,yCAAyC,CAAC;AACxD,cAAc,0CAA0C,CAAC;AACzD,cAAc,gCAAgC,CAAC;AAC/C,cAAc,oCAAoC,CAAC;AACnD,cAAc,kCAAkC,CAAC;AACjD,cAAc,kCAAkC,CAAC;AACjD,cAAc,0CAA0C,CAAC;AACzD,cAAc,4CAA4C,CAAC;AAC3D,cAAc,2CAA2C,CAAC;AAC1D,cAAc,kDAAkD,CAAC;AACjE,cAAc,yCAAyC,CAAC;AACxD,cAAc,gDAAgD,CAAC;AAC/D,cAAc,gDAAgD,CAAC;AAC/D,cAAc,iCAAiC,CAAC;AAChD,cAAc,qCAAqC,CAAC;AACpD,cAAc,yCAAyC,CAAC;AACxD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6CAA6C,CAAC;AAC5D,cAAc,mCAAmC,CAAC;AAClD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,mCAAmC,CAAC;AAClD,cAAc,sCAAsC,CAAC;AACrD,cAAc,4CAA4C,CAAC;AAC3D,cAAc,wDAAwD,CAAC;AACvE,cAAc,gEAAgE,CAAC;AAC/E,cAAc,uDAAuD,CAAC;AACtE,cAAc,+DAA+D,CAAC;AAC9E,cAAc,kDAAkD,CAAC"}
package/dist/postgres.js CHANGED
@@ -10,6 +10,10 @@ export * from './postgres/outbox/processed-events-table.js';
10
10
  export * from './postgres/outbox/drizzle-outbox-store.js';
11
11
  export * from './postgres/outbox/drizzle-processed-event-store.js';
12
12
  export * from './postgres/sql/primary-key-of.js';
13
+ export * from './postgres/sql/insert-ignoring-conflict.js';
14
+ export * from './postgres/locks/drizzle-locking-context.js';
15
+ export * from './postgres/locks/advisory-lock.js';
16
+ export * from './postgres/locks/try-advisory-lock.js';
13
17
  export * from './postgres/columns/audit-columns.js';
14
18
  export * from './postgres/columns/tenant-column.js';
15
19
  export * from './postgres/read-model/read-model-columns.js';
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,GAEb,MAAM,oBAAoB,CAAC;AAC5B,cAAc,yCAAyC,CAAC;AACxD,cAAc,qDAAqD,CAAC;AACpE,cAAc,kCAAkC,CAAC;AACjD,cAAc,yDAAyD,CAAC;AACxE,cAAc,8CAA8C,CAAC;AAC7D,cAAc,gCAAgC,CAAC;AAC/C,cAAc,uCAAuC,CAAC;AACtD,cAAc,0CAA0C,CAAC;AACzD,cAAc,wCAAwC,CAAC;AACvD,cAAc,iDAAiD,CAAC;AAChE,cAAc,+BAA+B,CAAC;AAC9C,cAAc,kCAAkC,CAAC;AACjD,cAAc,kCAAkC,CAAC;AACjD,cAAc,0CAA0C,CAAC;AACzD,cAAc,4CAA4C,CAAC;AAC3D,cAAc,2CAA2C,CAAC;AAC1D,cAAc,kDAAkD,CAAC;AACjE,cAAc,yCAAyC,CAAC;AACxD,cAAc,gDAAgD,CAAC;AAC/D,cAAc,gDAAgD,CAAC;AAC/D,cAAc,iCAAiC,CAAC;AAChD,cAAc,qCAAqC,CAAC;AACpD,cAAc,yCAAyC,CAAC;AACxD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6CAA6C,CAAC;AAC5D,cAAc,mCAAmC,CAAC;AAClD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,mCAAmC,CAAC;AAClD,cAAc,sCAAsC,CAAC;AACrD,cAAc,4CAA4C,CAAC;AAC3D,cAAc,wDAAwD,CAAC;AACvE,cAAc,gEAAgE,CAAC;AAC/E,cAAc,uDAAuD,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A+D,CAAC;AAC9E,cAAc,kDAAkD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ddd-ts-kit/drizzle",
3
- "version": "0.110.1",
3
+ "version": "0.112.0",
4
4
  "description": "Drizzle adapters for the kernel ports on PostgreSQL: unit of work, transactional outbox store, processed-event store, event store, background job store, process store, one schema per context.",
5
5
  "keywords": [
6
6
  "ddd",
@@ -42,9 +42,9 @@
42
42
  "dist"
43
43
  ],
44
44
  "dependencies": {
45
- "@ddd-ts-kit/kernel": "0.110.1",
46
- "@ddd-ts-kit/events": "0.110.1",
47
- "@ddd-ts-kit/scheduling": "0.110.1"
45
+ "@ddd-ts-kit/kernel": "0.112.0",
46
+ "@ddd-ts-kit/events": "0.112.0",
47
+ "@ddd-ts-kit/scheduling": "0.112.0"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "drizzle-orm": ">=0.40.0"
@@ -52,7 +52,7 @@
52
52
  "devDependencies": {
53
53
  "drizzle-orm": "latest",
54
54
  "@electric-sql/pglite": "0.5.15",
55
- "@ddd-ts-kit/testing": "0.110.1",
55
+ "@ddd-ts-kit/testing": "0.112.0",
56
56
  "pg": "^8.23.1",
57
57
  "@types/pg": "^8.23.1"
58
58
  }