@ddd-ts-kit/knex 0.113.2 → 0.115.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 (72) hide show
  1. package/README.fr.md +50 -18
  2. package/README.md +45 -16
  3. package/dist/aggregates/aggregate-table.d.ts +6 -0
  4. package/dist/aggregates/aggregate-table.d.ts.map +1 -0
  5. package/dist/aggregates/aggregate-table.js +2 -0
  6. package/dist/aggregates/aggregate-table.js.map +1 -0
  7. package/dist/aggregates/row-statements-on.d.ts +12 -0
  8. package/dist/aggregates/row-statements-on.d.ts.map +1 -0
  9. package/dist/aggregates/row-statements-on.js +22 -0
  10. package/dist/aggregates/row-statements-on.js.map +1 -0
  11. package/dist/aggregates/save-aggregate.d.ts +16 -0
  12. package/dist/aggregates/save-aggregate.d.ts.map +1 -0
  13. package/dist/aggregates/save-aggregate.js +15 -0
  14. package/dist/aggregates/save-aggregate.js.map +1 -0
  15. package/dist/aggregates/save-tenant-aggregate.d.ts +12 -0
  16. package/dist/aggregates/save-tenant-aggregate.d.ts.map +1 -0
  17. package/dist/aggregates/save-tenant-aggregate.js +11 -0
  18. package/dist/aggregates/save-tenant-aggregate.js.map +1 -0
  19. package/dist/index.d.ts +5 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +5 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/jobs/claimed-of-row.d.ts +2 -2
  24. package/dist/jobs/claimed-of-row.d.ts.map +1 -1
  25. package/dist/jobs/claimed-of-row.js +3 -1
  26. package/dist/jobs/claimed-of-row.js.map +1 -1
  27. package/dist/jobs/create-job-table.d.ts.map +1 -1
  28. package/dist/jobs/create-job-table.js +2 -0
  29. package/dist/jobs/create-job-table.js.map +1 -1
  30. package/dist/jobs/job-row.d.ts +2 -0
  31. package/dist/jobs/job-row.d.ts.map +1 -1
  32. package/dist/jobs/knex-job-store.d.ts +1 -1
  33. package/dist/jobs/knex-job-store.d.ts.map +1 -1
  34. package/dist/jobs/knex-job-store.js +11 -11
  35. package/dist/jobs/knex-job-store.js.map +1 -1
  36. package/dist/outbox/knex-outbox-store.d.ts +1 -0
  37. package/dist/outbox/knex-outbox-store.d.ts.map +1 -1
  38. package/dist/outbox/knex-outbox-store.js +7 -0
  39. package/dist/outbox/knex-outbox-store.js.map +1 -1
  40. package/dist/read-model/criteria-to-knex.d.ts +3 -2
  41. package/dist/read-model/criteria-to-knex.d.ts.map +1 -1
  42. package/dist/read-model/criteria-to-knex.js +3 -2
  43. package/dist/read-model/criteria-to-knex.js.map +1 -1
  44. package/dist/read-model/knex-read-model-table.d.ts +3 -2
  45. package/dist/read-model/knex-read-model-table.d.ts.map +1 -1
  46. package/dist/read-model/knex-read-model-table.js +7 -5
  47. package/dist/read-model/knex-read-model-table.js.map +1 -1
  48. package/dist/read-model/knex-stamped-rows.d.ts +2 -2
  49. package/dist/read-model/knex-stamped-rows.d.ts.map +1 -1
  50. package/dist/read-model/knex-stamped-rows.js +1 -1
  51. package/dist/read-model/knex-stamped-rows.js.map +1 -1
  52. package/dist/read-model/postgres-only.d.ts +12 -0
  53. package/dist/read-model/postgres-only.d.ts.map +1 -0
  54. package/dist/read-model/postgres-only.js +29 -0
  55. package/dist/read-model/postgres-only.js.map +1 -0
  56. package/dist/tenancy/conjunct-builder.d.ts +2 -2
  57. package/dist/tenancy/conjunct-builder.d.ts.map +1 -1
  58. package/dist/tenancy/conjunct-builder.js +21 -7
  59. package/dist/tenancy/conjunct-builder.js.map +1 -1
  60. package/dist/tenancy/create-tenant-routed-unit-of-work.d.ts.map +1 -1
  61. package/dist/tenancy/create-tenant-routed-unit-of-work.js +15 -13
  62. package/dist/tenancy/create-tenant-routed-unit-of-work.js.map +1 -1
  63. package/dist/tenancy/tenant-databases-options.d.ts +5 -0
  64. package/dist/tenancy/tenant-databases-options.d.ts.map +1 -1
  65. package/dist/tenancy/tenant-databases.d.ts.map +1 -1
  66. package/dist/tenancy/tenant-databases.js +4 -1
  67. package/dist/tenancy/tenant-databases.js.map +1 -1
  68. package/dist/unit-of-work/create-knex-unit-of-work.d.ts +4 -3
  69. package/dist/unit-of-work/create-knex-unit-of-work.d.ts.map +1 -1
  70. package/dist/unit-of-work/create-knex-unit-of-work.js +11 -16
  71. package/dist/unit-of-work/create-knex-unit-of-work.js.map +1 -1
  72. package/package.json +8 -8
package/README.fr.md CHANGED
@@ -1,5 +1,5 @@
1
1
  [English](README.md) · **Français**
2
- <!-- translation-of: README.md sha256:d723d12bcfe5ca31 -->
2
+ <!-- translation-of: README.md sha256:519276fb49ffd20f -->
3
3
 
4
4
  # @ddd-ts-kit/knex
5
5
 
@@ -28,7 +28,7 @@ vivent dans l'`infrastructure/` de chaque contexte, et l'unité de travail est c
28
28
  `UnitOfWork` dans lequel le bus de commandes exécute chaque commande, et au `KnexContext` par
29
29
  lequel chaque adaptateur atteint la base de données.
30
30
 
31
- ![Le bus de commandes appelle run sur le port UnitOfWork ; les repositories, les lecteurs, les stores du package et le journal d'audit appellent executor sur le port KnexContext ; les deux ports sont l'objet unique que renvoie createKnexUnitOfWork, qui garde la transaction ouverte dans un AsyncLocalStorage : chaque instruction d'une commande s'exécute ainsi dans une seule transaction PostgreSQL, avec un schéma par contexte](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/knex-place-in-an-application.fr.svg)
31
+ ![Le bus de commandes appelle run sur le port UnitOfWork ; les repositories, les lecteurs, les stores du package et le journal d'audit appellent executor sur le port KnexContext ; les deux ports sont l'objet unique que renvoie createKnexUnitOfWork, qui garde la transaction ouverte dans un AsyncLocalStorage : chaque instruction d'une commande s'exécute ainsi dans une seule transaction PostgreSQL, avec un schéma par contexte](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/knex-place-in-an-application.fr.svg)
32
32
 
33
33
  Plutôt que de faire descendre une transaction le long des appels, ce qui met un type knex dans
34
34
  chaque signature, du gestionnaire (handler) à l'adaptateur, et fait de son oubli un bogue
@@ -236,14 +236,18 @@ gestionnaire qui échoue ensuite est annulé avec l'écriture métier : c'est to
236
236
  de l'outbox. `createKnexUnitOfWork(db, { isolationLevel: 'repeatable read' })` transmet la
237
237
  configuration de transaction de knex.
238
238
 
239
- `run` repose sur `withinUnitOfWork` du noyau. Les événements du domaine des agrégats sauvegardés
239
+ `run` repose sur `unitOfWorkOver` du noyau. Les événements du domaine des agrégats sauvegardés
240
240
  à l'intérieur attendent que `work` ait rendu la main, puis sont distribués dans la transaction,
241
241
  avant la validation (commit) : leurs gestionnaires voient chaque sauvegarde, et ce qu'ils
242
242
  écrivent est validé ou annulé avec elle. Si `work`, un gestionnaire ou la validation échoue, il
243
243
  ne reste rien : aucune ligne, aucun enregistrement d'outbox, aucun gestionnaire exécuté après la
244
244
  validation. Les gestionnaires déclarés `after-commit` s'exécutent une fois la transaction
245
245
  validée. Un `run` imbriqué rejoint l'unité de travail en cours : une seule distribution, à la fin
246
- du plus externe. Un `run` appelé directement (un consommateur, un script) a le même déroulement
246
+ du plus externe. Appelé dans l'unité de travail d'une autre base de données, `run` ouvre la sienne : ses
247
+ événements sont distribués avant sa propre validation. L'unité de travail est validée ou annulée
248
+ en entier : dès qu'un `run` imbriqué a échoué elle n'est plus validée, et quand le travail a
249
+ intercepté cet échec et continué, le `run` le plus externe est rejeté avec une
250
+ `UnitOfWorkAbortedError` dont il est la `cause`. Un `run` appelé directement (un consommateur, un script) a le même déroulement
247
251
  qu'une commande. `unitOfWorkContract` de `@ddd-ts-kit/testing/contracts` le prouve, avec une
248
252
  contrainte différée pour la validation qui échoue ; sur un vrai PostgreSQL
249
253
  (`DDD_TS_KIT_TEST_DATABASE_URL`), il prouve aussi que les lignes d'un gestionnaire
@@ -274,7 +278,7 @@ export abstract class InvoiceRepository extends Repository<Invoice> {}
274
278
  import type { Knex } from 'knex';
275
279
  import { AggregateRoot } from '@ddd-ts-kit/kernel';
276
280
  import { Repository } from '@ddd-ts-kit/kernel/declarations';
277
- import { insertIgnoringConflict, KnexContext, optimisticUpdate, schemaNameOf } from '@ddd-ts-kit/knex';
281
+ import { insertIgnoringConflict, KnexContext, loadedAt, optimisticUpdate, schemaNameOf } from '@ddd-ts-kit/knex';
278
282
 
279
283
  const BILLING = schemaNameOf('billing-core'); // billing_core
280
284
 
@@ -309,10 +313,7 @@ export class KnexInvoiceRepository implements InvoiceRepository {
309
313
  return undefined;
310
314
  }
311
315
 
312
- const invoice = Invoice.rehydrate(row);
313
- invoice.version = row.version;
314
-
315
- return invoice;
316
+ return loadedAt(Invoice.rehydrate(row), row.version);
316
317
  }
317
318
 
318
319
  async save(invoice: Invoice): Promise<void> {
@@ -386,6 +387,25 @@ Dans le style explicite, sans le décorateur, la même liaison tient en une lign
386
387
  `<context>.module.ts` :
387
388
  `builder.bind(InvoiceRepository).toClass(KnexInvoiceRepository, [KnexContext])`.
388
389
 
390
+ La sauvegarde ci-dessus est écrite en entier pour montrer chaque instruction. `saveAggregate` fait
391
+ la même chose en un appel : il prend une table qui garde la clé sous `id` et la version sous
392
+ `version`, et une sauvegarde, l'agrégat, les colonnes que son *mapper* a données, le *scope* et
393
+ l'horloge qui tamponnent les colonnes d'audit. `saveTenantAggregate` fait de même pour
394
+ une table que tous les *tenants* partagent : il écrit la ligne dans le *tenant* du travail en
395
+ cours et confine sa mise à jour à ce *tenant*. Un *repository* généré sauvegarde ainsi et ne porte
396
+ rien d'autre de la plomberie.
397
+
398
+ ```ts
399
+ async save(invoice: Invoice): Promise<void> {
400
+ await saveAggregate(this.context, { schema: 'billing', table: 'invoices' }, {
401
+ aggregate: invoice,
402
+ row: InvoiceMapper.toRow(invoice),
403
+ scope: this.scope,
404
+ clock: this.clock,
405
+ });
406
+ }
407
+ ```
408
+
389
409
  `optimisticUpdate` donne la version à attendre et la version à écrire, lève une
390
410
  `ConcurrencyError` (une `DomainError` de code `CONCURRENCY_CONFLICT`) quand l'instruction gardée
391
411
  n'a écrit aucune ligne, et fait avancer `invoice.version` sinon. `insertIgnoringConflict` insère
@@ -397,7 +417,7 @@ autre ligne détient sous une contrainte d'unicité (un e-mail) est refusée par
397
417
  `optimisticUpdate` lève `UniqueViolationError` (code `CONFLICT`, 409), pas une mise à jour
398
418
  perdue ; sur MySQL, qui n'a pas de cible de conflit et dont `INSERT IGNORE` écarte aussi cette ligne, l'utilitaire demande si une ligne détient la clé quand rien n'a été écrit, et lève `UniqueViolationError` quand aucune ne la détient. Deux premiers enregistrements d'un même agrégat faits en même temps (une requête livrée deux fois) ne sont pas refusés pour la valeur unique qu'ils écrivent tous les deux : sur PostgreSQL, une cible de conflit sur la clé seule les laisse se rencontrer d'abord sur l'autre index unique, si bien que l'utilitaire insère par une instruction qui passe sur toute valeur unique, et seulement quand elle n'a rien écrit par une seconde qui nomme la clé. Celui qui a perdu n'écrit aucune ligne, une `ConcurrencyError`.
399
419
 
400
- ![Deux transactions chargent la facture inv-1 à la version 3 ; la première sauvegarde, sa mise à jour trouve la version 3 et la ligne passe à la version 4 ; la seconde sauvegarde ensuite, sa mise à jour attend toujours la version 3, n'écrit aucune ligne, et optimisticUpdate lève ConcurrencyError, code CONCURRENCY_CONFLICT](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/persistence-optimistic-concurrency.fr.svg)
420
+ ![Deux transactions chargent la facture inv-1 à la version 3 ; la première sauvegarde, sa mise à jour trouve la version 3 et la ligne passe à la version 4 ; la seconde sauvegarde ensuite, sa mise à jour attend toujours la version 3, n'écrit aucune ligne, et optimisticUpdate lève ConcurrencyError, code CONCURRENCY_CONFLICT](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/persistence-optimistic-concurrency.fr.svg)
401
421
 
402
422
  Le second écrivain est refusé au lieu d'écraser le premier en silence. Rien ne le retente pour
403
423
  vous : l'appelant reçoit la `ConcurrencyError` et décide s'il recharge la facture.
@@ -627,7 +647,7 @@ base de données :
627
647
  Ce que le curseur apporte, sur des factures triées par montant, quand une ligne est insérée entre
628
648
  deux pages :
629
649
 
630
- ![Des factures dans un ordre total par montant puis par id ; la page 1 lit quatre lignes pour une limite de 3 et garde comme curseur la position de la dernière, montant 40 et id inv-7 ; après l'insertion d'une facture de 10, la page 2 par offset 3 lit inv-7 une seconde fois, tandis que la page 2 après le curseur compare la position comme un tuple et renvoie inv-9, inv-2 et inv-4 : rien de répété, rien de sauté, aucun comptage](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/knex-cursor-page.fr.svg)
650
+ ![Des factures dans un ordre total par montant puis par id ; la page 1 lit quatre lignes pour une limite de 3 et garde comme curseur la position de la dernière, montant 40 et id inv-7 ; après l'insertion d'une facture de 10, la page 2 par offset 3 lit inv-7 une seconde fois, tandis que la page 2 après le curseur compare la position comme un tuple et renvoie inv-9, inv-2 et inv-4 : rien de répété, rien de sauté, aucun comptage](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/knex-cursor-page.fr.svg)
631
651
 
632
652
  ## Isolation des tenants
633
653
 
@@ -635,7 +655,7 @@ Quatre stratégies, choisies par projet ([Multitenance](../../docs/concepts/mult
635
655
  dit quand chacune convient). Chacune est prouvée ici par `tenantIsolationContract` de
636
656
  `@ddd-ts-kit/testing/contracts`, sur PGlite et sur PostgreSQL.
637
657
 
638
- ![Les quatre stratégies, de la plus partagée à la plus séparée, et les helpers de chacune : tables partagées avec tenantColumn, tenantTable, ownTenantTable, tenantRow et whereTenant ; sécurité au niveau des lignes avec enableTenantIsolation ou tenantIsolationStatements, tenantSession et un rôle sans BYPASSRLS ; schéma par tenant avec tenantSchemaOf, tenantSchemaTable, tenantOfMigration, migrateTenantSchema et tenantSearchPath ; base par tenant avec TenantDatabases, createTenantRoutedUnitOfWork et migrateEveryTenant](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/knex-tenant-isolation-helpers.fr.svg)
658
+ ![Les quatre stratégies, de la plus partagée à la plus séparée, et les helpers de chacune : tables partagées avec tenantColumn, tenantTable, ownTenantTable, tenantRow et whereTenant ; sécurité au niveau des lignes avec enableTenantIsolation ou tenantIsolationStatements, tenantSession et un rôle sans BYPASSRLS ; schéma par tenant avec tenantSchemaOf, tenantSchemaTable, tenantOfMigration, migrateTenantSchema et tenantSearchPath ; base par tenant avec TenantDatabases, createTenantRoutedUnitOfWork et migrateEveryTenant](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/knex-tenant-isolation-helpers.fr.svg)
639
659
 
640
660
  **Tables partagées.** Une table par agrégat, une colonne `tenant_id`, et chaque instruction
641
661
  restreinte par le kit plutôt que par une condition écrite à la main :
@@ -656,7 +676,9 @@ nomme aucun *tenant* lève `NoCurrentTenantError` avant tout SQL. Les trois gard
656
676
  `and` avec le reste de l'instruction : SQL lie `and` avant `or`, donc `.orWhere*` et `.or` au sommet
657
677
  de leur *builder* lèvent `UngroupedOrError` et les alternatives vont dans un groupe,
658
678
  `.where((either) => either.where(a).orWhere(b))` ; le texte d'un `whereRaw`, ou un `knex.raw` donné
659
- à un *where*, reste entre parenthèses comme un seul terme, avec ses paramètres ; `clearWhere()` et
679
+ à n'importe quel *where* (`where`, `whereIn`, `whereBetween`, `whereNull`, `whereLike`...) comme
680
+ sa condition, sa colonne, une valeur ou une borne, reste entre parenthèses comme un seul terme,
681
+ avec ses paramètres ; `clearWhere()` et
660
682
  `clear('where')` lèvent `ClearedTenantConditionError`. Un `orHaving` s'applique après le *where* et
661
683
  reste libre. Un modèle de lecture de données
662
684
  d'un *tenant* passe `tenant: scope` à `KnexReadModelTable` et à `KnexReadModelStore` : chaque
@@ -728,7 +750,8 @@ que le serveur n'a jamais à accepter plus de `maxTenants * pool.max` connexions
728
750
  l'application. Un travail tient l'instance de son *tenant* par un bail
729
751
  (`databases.lease(tenantId, (knex) => ...)`) : une instance n'est fermée que lorsqu'aucun travail
730
752
  ne la tient, la moins récemment utilisée d'abord, et un travail pour un autre *tenant* attend une
731
- place au lieu d'ouvrir au-delà de la borne. `createTenantRoutedUnitOfWork(databases, scope)` est
753
+ place au lieu d'ouvrir au-delà de la borne. Une instance inactive qui ne peut pas être fermée
754
+ cède sa place malgré tout, et `onCloseFailure(error, tenantId)` en est averti. `createTenantRoutedUnitOfWork(databases, scope)` est
732
755
  l'unité de travail et le `KnexContext` : chaque transaction tient un bail sur la base du *tenant*
733
756
  du travail jusqu'à sa fin ; chaque instruction s'exécute à l'intérieur
734
757
  (`StatementOutsideUnitOfWorkError` sinon, donc les requêtes passent elles aussi par l'unité de
@@ -764,7 +787,8 @@ async search(criteria: ScopedCriteria<AppointmentRow>): Promise<Page<Appointment
764
787
  Une page par curseur est lue avec une ligne de plus que demandé : c'est ainsi que `pageOfPlan`
765
788
  sait si une autre suit ; une page par offset tire son total d'une seconde instruction
766
789
  (`predicateToKnex(...).count()`). Un champ déclaré `nullable` est trié `nulls last` en ordre
767
- croissant et `nulls first` en ordre décroissant, sur tous les dialectes.
790
+ croissant et `nulls first` en ordre décroissant. Les critères sont écrits pour PostgreSQL, comme
791
+ les modèles de lecture : une recherche qui ignore la casse est un `ILIKE`.
768
792
 
769
793
  **Chaînes.** Une colonne de texte est triée et comparée par plage selon la collation de la
770
794
  colonne ; les critères trient les chaînes par point de code. Déclarez avec `COLLATE "C"` les
@@ -816,7 +840,13 @@ faite par `LIKE ... INCLUDING ALL`, les clés écrites entre-temps dans `<table>
816
840
  l'échange par renommage dans une seule transaction), et ses garanties et ses limites sont dans le
817
841
  README de `@ddd-ts-kit/kernel` (« Reconstruction »). Le store passe `criteriaContract` et
818
842
  `readModelStoreContract` de `@ddd-ts-kit/testing/contracts`, sur PGlite et sur PostgreSQL 18.
819
- Les critères et les modèles de lecture n'ont jamais été exécutés sur MySQL ni sur SQLite.
843
+ Les modèles de lecture sont réservés à PostgreSQL : un `KnexReadModelStore` (un
844
+ `KnexReadModelTable`) construit sur une instance knex d'une autre base de données est refusé
845
+ nommément, `The read model of @ddd-ts-kit/knex runs on PostgreSQL, and this knex speaks sqlite`,
846
+ à sa construction, ou à sa première instruction sous une base de données par *tenant*, où la
847
+ base n'est connue que dans une unité de travail. Ses estampilles, la trace d'une ligne supprimée
848
+ et la reconstruction reposent sur `timestamptz`, `boolean` et le catalogue de PostgreSQL ; sur
849
+ SQLite ils répondaient faux avant d'échouer.
820
850
 
821
851
  ## Effacement des données personnelles
822
852
 
@@ -900,10 +930,12 @@ garderait ce qu'il ne doit pas. L'adaptateur implémente `PersonalDataRetention`
900
930
  validée avec les effets du gestionnaire, et disparaît avec eux s'il échoue.
901
931
 
902
932
  La vie d'un enregistrement dans la table `outbox`. Le relais de `@ddd-ts-kit/events` le conduit
903
- par `claimBatch`, `markPublished` et `markFailed` ; `retryDead`, `purgePublished` et `stats` sont
933
+ par `claimBatch`, `markPublished`, `markFailed` et `postpone` (un enregistrement retenu pour
934
+ l'ordre derrière un précédent de sa clé : il attend, sans avoir été tenté) ; `retryDead`,
935
+ `purgePublished` et `stats` sont
904
936
  appelés par un opérateur ou par un job planifié, jamais par le relais :
905
937
 
906
- ![Un enregistrement est ajouté en attente par la validation de la commande ; le relais le réclame quand il est dû et le publie, puis le marque publié, et purgePublished le supprime plus tard ; une publication en échec le laisse en attente, retenté après un délai exponentiel ; après la dernière tentative il est mort, jusqu'à ce que retryDead le remette en attente ; stats compte les enregistrements en attente, en échec et morts](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/transactional-outbox-record-lifecycle.fr.svg)
938
+ ![Un enregistrement est ajouté en attente par la validation de la commande ; le relais le réclame quand il est dû et le publie, puis le marque publié, et purgePublished le supprime plus tard ; une publication en échec le laisse en attente, retenté après un délai exponentiel ; après la dernière tentative il est mort, jusqu'à ce que retryDead le remette en attente ; stats compte les enregistrements en attente, en échec et morts](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/transactional-outbox-record-lifecycle.fr.svg)
907
939
 
908
940
  ## Event store
909
941
 
package/README.md CHANGED
@@ -25,7 +25,7 @@ ports and the application its query ports; the adapters written with this packag
25
25
  the hinge: `createKnexUnitOfWork(db)` answers the `UnitOfWork` the command bus runs every
26
26
  command in, and the `KnexContext` every adapter reaches the database through.
27
27
 
28
- ![The command bus calls run on the UnitOfWork port; repositories, readers, the stores of the package and the audit trail call executor on the KnexContext port; both ports are the one object createKnexUnitOfWork answers, which keeps the open transaction in an AsyncLocalStorage, so every statement of a command runs in one PostgreSQL transaction, one schema per context](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/knex-place-in-an-application.svg)
28
+ ![The command bus calls run on the UnitOfWork port; repositories, readers, the stores of the package and the audit trail call executor on the KnexContext port; both ports are the one object createKnexUnitOfWork answers, which keeps the open transaction in an AsyncLocalStorage, so every statement of a command runs in one PostgreSQL transaction, one schema per context](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/knex-place-in-an-application.svg)
29
29
 
30
30
  Instead of handing a transaction down the calls, which puts a knex type in every signature from
31
31
  the handler to the adapter and makes forgetting it a silent bug, the adapter asks the context
@@ -225,12 +225,17 @@ rolled back with the business write: that is the whole point of the outbox.
225
225
  `createKnexUnitOfWork(db, { isolationLevel: 'repeatable read' })` forwards the transaction
226
226
  configuration of knex.
227
227
 
228
- `run` is built on `withinUnitOfWork` of the kernel. The domain events of the aggregates saved
228
+ `run` is built on `unitOfWorkOver` of the kernel. The domain events of the aggregates saved
229
229
  inside it wait until `work` has returned, then are dispatched inside the transaction, before
230
230
  the commit: their handlers see every save, and what they write commits or rolls back with it.
231
231
  If `work`, a handler or the commit fails, nothing is left: no row, no outbox record, no handler
232
232
  run after the commit. Handlers declared `after-commit` run once the transaction has committed.
233
233
  A nested `run` joins the unit of work in progress: one dispatch, at the end of the outermost.
234
+ Called inside the unit of work of another database, `run` opens its own: its events are
235
+ dispatched before its own commit.
236
+ The unit of work commits or rolls back as a whole: once a nested `run` has failed it no longer
237
+ commits, and when the work caught that failure and went on the outermost `run` rejects with a
238
+ `UnitOfWorkAbortedError` whose `cause` it is.
234
239
  A `run` called directly (a consumer, a script) has the same timing as a command.
235
240
  `unitOfWorkContract` of `@ddd-ts-kit/testing/contracts` proves it, with a deferred constraint
236
241
  for the commit that fails; on a real PostgreSQL (`DDD_TS_KIT_TEST_DATABASE_URL`) it also proves
@@ -260,7 +265,7 @@ export abstract class InvoiceRepository extends Repository<Invoice> {}
260
265
  import type { Knex } from 'knex';
261
266
  import { AggregateRoot } from '@ddd-ts-kit/kernel';
262
267
  import { Repository } from '@ddd-ts-kit/kernel/declarations';
263
- import { insertIgnoringConflict, KnexContext, optimisticUpdate, schemaNameOf } from '@ddd-ts-kit/knex';
268
+ import { insertIgnoringConflict, KnexContext, loadedAt, optimisticUpdate, schemaNameOf } from '@ddd-ts-kit/knex';
264
269
 
265
270
  const BILLING = schemaNameOf('billing-core'); // billing_core
266
271
 
@@ -295,10 +300,7 @@ export class KnexInvoiceRepository implements InvoiceRepository {
295
300
  return undefined;
296
301
  }
297
302
 
298
- const invoice = Invoice.rehydrate(row);
299
- invoice.version = row.version;
300
-
301
- return invoice;
303
+ return loadedAt(Invoice.rehydrate(row), row.version);
302
304
  }
303
305
 
304
306
  async save(invoice: Invoice): Promise<void> {
@@ -371,6 +373,24 @@ In the explicit style, without the decorator, the same binding is one line of
371
373
  `<context>.module.ts`:
372
374
  `builder.bind(InvoiceRepository).toClass(KnexInvoiceRepository, [KnexContext])`.
373
375
 
376
+ The save above is written out to show each statement. `saveAggregate` does the same in one
377
+ call: it takes a table that keeps the key under `id` and the version under `version`, and one
378
+ save, the aggregate, the columns its mapper gave, the scope and the clock that stamp the audit
379
+ columns. `saveTenantAggregate` is the same for a table every tenant shares: it writes the row in
380
+ the tenant of the work in progress and confines its update to that tenant. A generated repository
381
+ saves this way and holds nothing else of the plumbing.
382
+
383
+ ```ts
384
+ async save(invoice: Invoice): Promise<void> {
385
+ await saveAggregate(this.context, { schema: 'billing', table: 'invoices' }, {
386
+ aggregate: invoice,
387
+ row: InvoiceMapper.toRow(invoice),
388
+ scope: this.scope,
389
+ clock: this.clock,
390
+ });
391
+ }
392
+ ```
393
+
374
394
  `optimisticUpdate` gives the version to expect and the version to write, raises a
375
395
  `ConcurrencyError` (a `DomainError` with code `CONCURRENCY_CONFLICT`) when the guarded
376
396
  statement wrote no row, and moves `invoice.version` on otherwise. `insertIgnoringConflict`
@@ -381,7 +401,7 @@ ignores a conflict on `conflict` alone (the id): a row that takes a value anothe
381
401
  under a unique constraint (an email) is refused by the database, and `optimisticUpdate` raises
382
402
  `UniqueViolationError` (code `CONFLICT`, 409), not a lost update; on MySQL, which has no conflict target and whose `INSERT IGNORE` skips that row too, the helper asks whether a row holds the key when nothing was written, and raises `UniqueViolationError` when none does. Two first saves of one aggregate made at once (a request delivered twice) are not refused for the unique value they both write: on PostgreSQL a conflict target on the key alone lets them meet on the other unique index first, so the helper inserts with a statement that skips on any unique value, and only when it wrote nothing with a second one that names the key. The one that lost writes no row, a `ConcurrencyError`.
383
403
 
384
- ![Two transactions load invoice inv-1 at version 3; the first saves, its update matches version 3 and the row moves to version 4; the second saves afterwards, its update still expects version 3, writes no row, and optimisticUpdate throws ConcurrencyError, code CONCURRENCY_CONFLICT](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/persistence-optimistic-concurrency.svg)
404
+ ![Two transactions load invoice inv-1 at version 3; the first saves, its update matches version 3 and the row moves to version 4; the second saves afterwards, its update still expects version 3, writes no row, and optimisticUpdate throws ConcurrencyError, code CONCURRENCY_CONFLICT](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/persistence-optimistic-concurrency.svg)
385
405
 
386
406
  The second writer is refused instead of silently overwriting the first. Nothing retries it for
387
407
  you: the caller receives the `ConcurrencyError` and decides whether to load the invoice again.
@@ -602,7 +622,7 @@ The rules these examples hold, and that the tests of this package check on a rea
602
622
 
603
623
  What the cursor buys, on invoices sorted by amount, when a row is inserted between two pages:
604
624
 
605
- ![Invoices in total order by amount then id; page 1 reads four rows for a limit of 3 and keeps the position of the last, amount 40 and id inv-7, as its cursor; after an invoice of 10 is inserted, page 2 by offset 3 reads inv-7 a second time, while page 2 after the cursor compares the position as a tuple and answers inv-9, inv-2 and inv-4, nothing repeated, nothing skipped, no count](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/knex-cursor-page.svg)
625
+ ![Invoices in total order by amount then id; page 1 reads four rows for a limit of 3 and keeps the position of the last, amount 40 and id inv-7, as its cursor; after an invoice of 10 is inserted, page 2 by offset 3 reads inv-7 a second time, while page 2 after the cursor compares the position as a tuple and answers inv-9, inv-2 and inv-4, nothing repeated, nothing skipped, no count](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/knex-cursor-page.svg)
606
626
 
607
627
  ## Tenant isolation
608
628
 
@@ -610,7 +630,7 @@ Four strategies, chosen per project ([Multitenancy](../../docs/concepts/multiten
610
630
  when each fits). Every one of them is proven here by `tenantIsolationContract` of
611
631
  `@ddd-ts-kit/testing/contracts`, on PGlite and on PostgreSQL.
612
632
 
613
- ![The four strategies from the most shared to the most separated, and the helpers of each: shared tables with tenantColumn, tenantTable, ownTenantTable, tenantRow and whereTenant; row-level security with enableTenantIsolation or tenantIsolationStatements, tenantSession and a role without BYPASSRLS; schema per tenant with tenantSchemaOf, tenantSchemaTable, tenantOfMigration, migrateTenantSchema and tenantSearchPath; database per tenant with TenantDatabases, createTenantRoutedUnitOfWork and migrateEveryTenant](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/knex-tenant-isolation-helpers.svg)
633
+ ![The four strategies from the most shared to the most separated, and the helpers of each: shared tables with tenantColumn, tenantTable, ownTenantTable, tenantRow and whereTenant; row-level security with enableTenantIsolation or tenantIsolationStatements, tenantSession and a role without BYPASSRLS; schema per tenant with tenantSchemaOf, tenantSchemaTable, tenantOfMigration, migrateTenantSchema and tenantSearchPath; database per tenant with TenantDatabases, createTenantRoutedUnitOfWork and migrateEveryTenant](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/knex-tenant-isolation-helpers.svg)
614
634
 
615
635
  **Shared tables.** One table per aggregate, a `tenant_id` column, and every statement confined
616
636
  by the kit instead of by a condition written by hand:
@@ -631,7 +651,8 @@ no tenant raises `NoCurrentTenantError` before any SQL. The three keep the condi
631
651
  the statement: SQL binds `and` before `or`, so `.orWhere*` and `.or` at the top of their builder
632
652
  throw `UngroupedOrError` and the alternatives go in a group,
633
653
  `.where((either) => either.where(a).orWhere(b))`; the text of a `whereRaw`, or a `knex.raw` given
634
- to a where, is kept in parentheses as one conjunct, with its bindings; `clearWhere()` and
654
+ to any where (`where`, `whereIn`, `whereBetween`, `whereNull`, `whereLike`...) as its condition,
655
+ its column, a value or a bound, is kept in parentheses as one conjunct, with its bindings; `clearWhere()` and
635
656
  `clear('where')` throw `ClearedTenantConditionError`. An `orHaving` applies after the where, and
636
657
  is free. A read model of tenant data passes
637
658
  `tenant: scope` to `KnexReadModelTable` and `KnexReadModelStore`: each row is written with the
@@ -696,7 +717,8 @@ maxTenants: 20 })` opens one knex (one bounded pool) per tenant on first use. At
696
717
  accept more than `maxTenants * pool.max` connections per instance of the application. Work holds
697
718
  the instance of its tenant by a lease (`databases.lease(tenantId, (knex) => ...)`): an instance is
698
719
  closed only when no work holds it, the least recently used first, and work for another tenant
699
- waits for a place instead of opening beyond the bound. `createTenantRoutedUnitOfWork(databases,
720
+ waits for a place instead of opening beyond the bound. An idle instance that cannot be closed
721
+ gives its place all the same, and `onCloseFailure(error, tenantId)` is told. `createTenantRoutedUnitOfWork(databases,
700
722
  scope)` is the unit of work and `KnexContext`: each transaction holds a lease on the database of
701
723
  the tenant of the work until it ends; every statement runs inside it
702
724
  (`StatementOutsideUnitOfWorkError` otherwise, so queries go through the unit of work too), work
@@ -732,7 +754,8 @@ async search(criteria: ScopedCriteria<AppointmentRow>): Promise<Page<Appointment
732
754
  A cursor page is fetched one row longer than asked, which is how `pageOfPlan` knows whether
733
755
  another follows; an offset page takes its total from a second statement
734
756
  (`predicateToKnex(...).count()`). A field declared `nullable` is ordered `nulls last`
735
- ascending and `nulls first` descending on every dialect.
757
+ ascending and `nulls first` descending. The criteria are written for PostgreSQL, as the read
758
+ models are: a search that ignores case is an `ILIKE`.
736
759
 
737
760
  **Strings.** A text column is ordered and compared by range in the collation of the column;
738
761
  criteria order strings by code point. Declare the text columns that are sorted or compared
@@ -781,7 +804,12 @@ meanwhile in `<table>__touched`, the swap by rename in one transaction) and its
781
804
  and limits are in the README of `@ddd-ts-kit/kernel` ("Rebuild"). The store passes
782
805
  `criteriaContract` and `readModelStoreContract` of `@ddd-ts-kit/testing/contracts`, on PGlite
783
806
  and on PostgreSQL 18.
784
- Criteria and read models were never run on MySQL or SQLite.
807
+ Read models are PostgreSQL only: a `KnexReadModelStore` (a `KnexReadModelTable`) built on a knex
808
+ instance of another database is refused by name, `The read model of @ddd-ts-kit/knex runs on
809
+ PostgreSQL, and this knex speaks sqlite`, when it is built, or at its first statement under
810
+ database per tenant, where the database is known only inside a unit of work. Its stamps, the
811
+ trace of a deleted row and the rebuild rely on `timestamptz`, `boolean` and the catalog of
812
+ PostgreSQL; on SQLite they answered wrong before they failed.
785
813
 
786
814
  ## Personal data erasure
787
815
 
@@ -861,10 +889,11 @@ every copy, and `auditedPersonalDataRetention` of `@ddd-ts-kit/audit` records ea
861
889
  the effects of the handler, and disappears with them if it fails.
862
890
 
863
891
  The life of one record in the `outbox` table. The relay of `@ddd-ts-kit/events` drives it through
864
- `claimBatch`, `markPublished` and `markFailed`; `retryDead`, `purgePublished` and `stats` are
892
+ `claimBatch`, `markPublished`, `markFailed` and `postpone` (a record held for order behind an
893
+ earlier one of its key: it waits, untried); `retryDead`, `purgePublished` and `stats` are
865
894
  called by an operator or a scheduled job, never by the relay:
866
895
 
867
- ![A record is appended pending by the commit of the command; the relay claims it when due and publishes it, then marks it published, and purgePublished removes it later; a failed publication leaves it pending, retried after an exponential backoff; after the last attempt it is dead until retryDead puts it back pending; stats counts pending, failed and dead records](https://raw.githubusercontent.com/gbourgeat/ddd-ts-kit/main/docs/assets/diagrams/transactional-outbox-record-lifecycle.svg)
896
+ ![A record is appended pending by the commit of the command; the relay claims it when due and publishes it, then marks it published, and purgePublished removes it later; a failed publication leaves it pending, retried after an exponential backoff; after the last attempt it is dead until retryDead puts it back pending; stats counts pending, failed and dead records](https://raw.githubusercontent.com/ddd-ts-kit/ddd-ts-kit/main/docs/assets/diagrams/transactional-outbox-record-lifecycle.svg)
868
897
 
869
898
  ## Event store
870
899
 
@@ -0,0 +1,6 @@
1
+ /** The table of an aggregate: its name and its schema. It keeps the key under `id` and the optimistic concurrency token under `version`. */
2
+ export interface AggregateTable {
3
+ readonly table: string;
4
+ readonly schema?: string;
5
+ }
6
+ //# sourceMappingURL=aggregate-table.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate-table.d.ts","sourceRoot":"","sources":["../../src/aggregates/aggregate-table.ts"],"names":[],"mappings":"AAAA,4IAA4I;AAC5I,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=aggregate-table.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregate-table.js","sourceRoot":"","sources":["../../src/aggregates/aggregate-table.ts"],"names":[],"mappings":""}
@@ -0,0 +1,12 @@
1
+ import type { RowStatements, TenantScoped } from '@ddd-ts-kit/kernel';
2
+ import type { TenantTableTarget } from '../tenancy/tenant-table-target.js';
3
+ import type { KnexContext } from '../unit-of-work/knex-context.js';
4
+ /**
5
+ * The insert and the guarded update of the row of an aggregate, on the executor of the unit of
6
+ * work in progress. Given the tenant of the work, the row is written in it and its update reaches
7
+ * the row of that tenant alone.
8
+ */
9
+ export declare function rowStatementsOn<Columns extends {
10
+ readonly id: string | number;
11
+ }>(context: KnexContext, target: TenantTableTarget, tenant?: TenantScoped): RowStatements<Columns>;
12
+ //# sourceMappingURL=row-statements-on.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"row-statements-on.d.ts","sourceRoot":"","sources":["../../src/aggregates/row-statements-on.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAItE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAExE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAIhE;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,SAAS;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,EAC9E,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,iBAAiB,EACzB,MAAM,CAAC,EAAE,YAAY,GACpB,aAAa,CAAC,OAAO,CAAC,CAcxB"}
@@ -0,0 +1,22 @@
1
+ import { auditRow } from '../columns/audit-row.js';
2
+ import { insertIgnoringConflict } from '../sql/insert-ignoring-conflict.js';
3
+ import { tableIn } from '../tenancy/table-in.js';
4
+ import { TENANT_COLUMN } from '../tenancy/where-tenant.js';
5
+ /**
6
+ * The insert and the guarded update of the row of an aggregate, on the executor of the unit of
7
+ * work in progress. Given the tenant of the work, the row is written in it and its update reaches
8
+ * the row of that tenant alone.
9
+ */
10
+ export function rowStatementsOn(context, target, tenant) {
11
+ const own = tenant === undefined ? {} : { [target.column ?? TENANT_COLUMN]: tenant.tenantId };
12
+ return {
13
+ insert: (row, stamp) => insertIgnoringConflict(context.executor(), tableIn(context, target), {
14
+ row: { ...row, ...own, ...auditRow(stamp) },
15
+ conflict: 'id',
16
+ }),
17
+ update: (row, stamp, expected) => tableIn(context, target)
18
+ .where({ id: row.id, version: expected, ...own })
19
+ .update({ ...row, ...auditRow(stamp) }),
20
+ };
21
+ }
22
+ //# sourceMappingURL=row-statements-on.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"row-statements-on.js","sourceRoot":"","sources":["../../src/aggregates/row-statements-on.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAE9C,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAKxD;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAC7B,OAAoB,EACpB,MAAyB,EACzB,MAAqB;IAErB,MAAM,GAAG,GAAQ,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,MAAM,IAAI,aAAa,CAAC,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC;IAEnG,OAAO;QACL,MAAM,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CACrB,sBAAsB,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,OAAO,CAAM,OAAO,EAAE,MAAM,CAAC,EAAE;YACxE,GAAG,EAAE,EAAE,GAAG,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,EAAE;YAC3C,QAAQ,EAAE,IAAI;SACf,CAAC;QACJ,MAAM,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,CAC/B,OAAO,CAAM,OAAO,EAAE,MAAM,CAAC;aAC1B,KAAK,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,GAAG,EAAE,CAAC;aAChD,MAAM,CAAC,EAAE,GAAG,GAAG,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;KAC5C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,16 @@
1
+ import { type AggregateSave } from '@ddd-ts-kit/kernel';
2
+ import type { KnexContext } from '../unit-of-work/knex-context.js';
3
+ import type { AggregateTable } from './aggregate-table.js';
4
+ /**
5
+ * Saves an aggregate in the row of its table, under optimistic concurrency: an insert the first
6
+ * time, that a taken key makes a `ConcurrencyError` and a value another row holds a
7
+ * `UniqueViolationError`; afterwards an update of the row while it still holds the version the
8
+ * aggregate was loaded at, a `ConcurrencyError` otherwise. The row carries the columns of the
9
+ * mapper, the next version and the audit stamp of the work in progress (`auditRow`).
10
+ *
11
+ * await saveAggregate(this.database, INVOICES, { aggregate: saved, row: InvoiceMapper.toRow(saved), scope, clock });
12
+ */
13
+ export declare function saveAggregate<Columns extends {
14
+ readonly id: string | number;
15
+ }>(context: KnexContext, table: AggregateTable, save: AggregateSave<Columns>): Promise<void>;
16
+ //# sourceMappingURL=save-aggregate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"save-aggregate.d.ts","sourceRoot":"","sources":["../../src/aggregates/save-aggregate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGxD;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAAC,OAAO,SAAS;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,EAC5E,OAAO,EAAE,WAAW,EACpB,KAAK,EAAE,cAAc,EACrB,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC,CAEf"}
@@ -0,0 +1,15 @@
1
+ import { saveAggregateRow } from '@ddd-ts-kit/kernel';
2
+ import { rowStatementsOn } from './row-statements-on.js';
3
+ /**
4
+ * Saves an aggregate in the row of its table, under optimistic concurrency: an insert the first
5
+ * time, that a taken key makes a `ConcurrencyError` and a value another row holds a
6
+ * `UniqueViolationError`; afterwards an update of the row while it still holds the version the
7
+ * aggregate was loaded at, a `ConcurrencyError` otherwise. The row carries the columns of the
8
+ * mapper, the next version and the audit stamp of the work in progress (`auditRow`).
9
+ *
10
+ * await saveAggregate(this.database, INVOICES, { aggregate: saved, row: InvoiceMapper.toRow(saved), scope, clock });
11
+ */
12
+ export function saveAggregate(context, table, save) {
13
+ return saveAggregateRow(save, rowStatementsOn(context, table));
14
+ }
15
+ //# sourceMappingURL=save-aggregate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"save-aggregate.js","sourceRoot":"","sources":["../../src/aggregates/save-aggregate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAsB,MAAM,oBAAoB,CAAC;AAG1E,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;;;;;GAQG;AACH,MAAM,UAAU,aAAa,CAC3B,OAAoB,EACpB,KAAqB,EACrB,IAA4B;IAE5B,OAAO,gBAAgB,CAAC,IAAI,EAAE,eAAe,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AACjE,CAAC"}
@@ -0,0 +1,12 @@
1
+ import { type AggregateSave } from '@ddd-ts-kit/kernel';
2
+ import type { TenantTableTarget } from '../tenancy/tenant-table-target.js';
3
+ import type { KnexContext } from '../unit-of-work/knex-context.js';
4
+ /**
5
+ * `saveAggregate` for a table that keeps the rows of every tenant under its tenant column: the
6
+ * row is written in the tenant of the work in progress, and its update reaches the row of that
7
+ * tenant alone, whatever an elevation widens. A row another tenant holds is a `ConcurrencyError`.
8
+ */
9
+ export declare function saveTenantAggregate<Columns extends {
10
+ readonly id: string | number;
11
+ }>(context: KnexContext, table: TenantTableTarget, save: AggregateSave<Columns>): Promise<void>;
12
+ //# sourceMappingURL=save-tenant-aggregate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"save-tenant-aggregate.d.ts","sourceRoot":"","sources":["../../src/aggregates/save-tenant-aggregate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmC,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACzF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAGhE;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,SAAS;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,EAClF,OAAO,EAAE,WAAW,EACpB,KAAK,EAAE,iBAAiB,EACxB,IAAI,EAAE,aAAa,CAAC,OAAO,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC,CAEf"}
@@ -0,0 +1,11 @@
1
+ import { saveAggregateRow, tenantScopeOf } from '@ddd-ts-kit/kernel';
2
+ import { rowStatementsOn } from './row-statements-on.js';
3
+ /**
4
+ * `saveAggregate` for a table that keeps the rows of every tenant under its tenant column: the
5
+ * row is written in the tenant of the work in progress, and its update reaches the row of that
6
+ * tenant alone, whatever an elevation widens. A row another tenant holds is a `ConcurrencyError`.
7
+ */
8
+ export function saveTenantAggregate(context, table, save) {
9
+ return saveAggregateRow(save, rowStatementsOn(context, table, tenantScopeOf(save.scope)));
10
+ }
11
+ //# sourceMappingURL=save-tenant-aggregate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"save-tenant-aggregate.js","sourceRoot":"","sources":["../../src/aggregates/save-tenant-aggregate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAsB,MAAM,oBAAoB,CAAC;AAGzF,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CACjC,OAAoB,EACpB,KAAwB,EACxB,IAA4B;IAE5B,OAAO,gBAAgB,CAAC,IAAI,EAAE,eAAe,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC5F,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { CONCURRENCY_CONFLICT, ConcurrencyError, optimisticUpdate, schemaNameOf, type VersionStep, } from '@ddd-ts-kit/kernel';
1
+ export { CONCURRENCY_CONFLICT, ConcurrencyError, aggregateMapper, loadedAt, optimisticUpdate, schemaNameOf, type VersionStep, } from '@ddd-ts-kit/kernel';
2
2
  export * from './unit-of-work/knex-context.js';
3
3
  export * from './unit-of-work/create-knex-unit-of-work.js';
4
4
  export * from './event-sourcing/add-event-store-tenant-column.js';
@@ -19,6 +19,9 @@ export * from './columns/tenant-row.js';
19
19
  export * from './columns/add-tenant-column-options.js';
20
20
  export * from './columns/add-tenant-column.js';
21
21
  export * from './sql/insert-ignoring-conflict.js';
22
+ export * from './aggregates/aggregate-table.js';
23
+ export * from './aggregates/save-aggregate.js';
24
+ export * from './aggregates/save-tenant-aggregate.js';
22
25
  export * from './locks/advisory-lock.js';
23
26
  export * from './locks/try-advisory-lock.js';
24
27
  export * from './read-model/read-model-columns.js';
@@ -31,6 +34,7 @@ export * from './tenancy/cleared-tenant-condition-error.js';
31
34
  export * from './tenancy/ungrouped-or-error.js';
32
35
  export * from './tenancy/where-tenant.js';
33
36
  export * from './tenancy/tenant-table-target.js';
37
+ export * from './tenancy/table-in.js';
34
38
  export * from './tenancy/tenant-table.js';
35
39
  export * from './tenancy/own-tenant-table.js';
36
40
  export * from './tenancy/derived-table.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,KAAK,WAAW,GACjB,MAAM,oBAAoB,CAAC;AAC5B,cAAc,6BAA6B,CAAC;AAC5C,cAAc,yCAAyC,CAAC;AACxD,cAAc,gDAAgD,CAAC;AA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,cAAc,oDAAoD,CAAC;AACnE,cAAc,2CAA2C,CAAC;AAC1D,cAAc,mDAAmD,CAAC;AAClE,cAAc,sCAAsC,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { CONCURRENCY_CONFLICT, ConcurrencyError, optimisticUpdate, schemaNameOf, } from '@ddd-ts-kit/kernel';
1
+ export { CONCURRENCY_CONFLICT, ConcurrencyError, aggregateMapper, loadedAt, optimisticUpdate, schemaNameOf, } from '@ddd-ts-kit/kernel';
2
2
  export * from './unit-of-work/knex-context.js';
3
3
  export * from './unit-of-work/create-knex-unit-of-work.js';
4
4
  export * from './event-sourcing/add-event-store-tenant-column.js';
@@ -19,6 +19,9 @@ export * from './columns/tenant-row.js';
19
19
  export * from './columns/add-tenant-column-options.js';
20
20
  export * from './columns/add-tenant-column.js';
21
21
  export * from './sql/insert-ignoring-conflict.js';
22
+ export * from './aggregates/aggregate-table.js';
23
+ export * from './aggregates/save-aggregate.js';
24
+ export * from './aggregates/save-tenant-aggregate.js';
22
25
  export * from './locks/advisory-lock.js';
23
26
  export * from './locks/try-advisory-lock.js';
24
27
  export * from './read-model/read-model-columns.js';
@@ -31,6 +34,7 @@ export * from './tenancy/cleared-tenant-condition-error.js';
31
34
  export * from './tenancy/ungrouped-or-error.js';
32
35
  export * from './tenancy/where-tenant.js';
33
36
  export * from './tenancy/tenant-table-target.js';
37
+ export * from './tenancy/table-in.js';
34
38
  export * from './tenancy/tenant-table.js';
35
39
  export * from './tenancy/own-tenant-table.js';
36
40
  export * from './tenancy/derived-table.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,GAEb,MAAM,oBAAoB,CAAC;AAC5B,cAAc,6BAA6B,CAAC;AAC5C,cAAc,yCAAyC,CAAC;AACxD,cAAc,gDAAgD,C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,CAAC;AACnE,cAAc,2CAA2C,CAAC;AAC1D,cAAc,mDAAmD,CAAC;AAClE,cAAc,sCAAsC,CAAC"}
@@ -1,5 +1,5 @@
1
- import type { ClaimedJob } from '@ddd-ts-kit/scheduling';
1
+ import { type ClaimedJob } from '@ddd-ts-kit/scheduling';
2
2
  import type { JobRow } from './job-row.js';
3
- /** A row as the worker receives it, the attempt of this claim counted. */
3
+ /** A row read before its claim was written, as the worker receives it: the attempt and the lease of this claim counted. */
4
4
  export declare function claimedOfRow(row: JobRow): ClaimedJob;
5
5
  //# sourceMappingURL=claimed-of-row.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"claimed-of-row.d.ts","sourceRoot":"","sources":["../../src/jobs/claimed-of-row.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAExC,0EAA0E;AAC1E,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAWpD"}
1
+ {"version":3,"file":"claimed-of-row.d.ts","sourceRoot":"","sources":["../../src/jobs/claimed-of-row.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAExC,2HAA2H;AAC3H,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAYpD"}
@@ -1,4 +1,5 @@
1
- /** A row as the worker receives it, the attempt of this claim counted. */
1
+ import { JobLease } from '@ddd-ts-kit/scheduling';
2
+ /** A row read before its claim was written, as the worker receives it: the attempt and the lease of this claim counted. */
2
3
  export function claimedOfRow(row) {
3
4
  return {
4
5
  id: row.id,
@@ -8,6 +9,7 @@ export function claimedOfRow(row) {
8
9
  enqueuedBy: row.enqueued_by,
9
10
  enqueuedAt: new Date(row.enqueued_at),
10
11
  attempt: row.attempts + 1,
12
+ lease: JobLease.ofClaim(row.id, row.claims + 1),
11
13
  ...(row.checkpoint === null ? {} : { checkpoint: row.checkpoint }),
12
14
  };
13
15
  }
@@ -1 +1 @@
1
- {"version":3,"file":"claimed-of-row.js","sourceRoot":"","sources":["../../src/jobs/claimed-of-row.ts"],"names":[],"mappings":"AAGA,0EAA0E;AAC1E,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,OAAO;QACL,EAAE,EAAE,GAAG,CAAC,EAAE;QACV,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,UAAU,EAAE,GAAG,CAAC,WAAW;QAC3B,UAAU,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC;QACrC,OAAO,EAAE,GAAG,CAAC,QAAQ,GAAG,CAAC;QACzB,GAAG,CAAC,GAAG,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC;KACnE,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"claimed-of-row.js","sourceRoot":"","sources":["../../src/jobs/claimed-of-row.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAmB,MAAM,wBAAwB,CAAC;AAGnE,2HAA2H;AAC3H,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,OAAO;QACL,EAAE,EAAE,GAAG,CAAC,EAAE;QACV,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,KAAK,EAAE,GAAG,CAAC,KAAK;QAChB,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,UAAU,EAAE,GAAG,CAAC,WAAW;QAC3B,UAAU,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC;QACrC,OAAO,EAAE,GAAG,CAAC,QAAQ,GAAG,CAAC;QACzB,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC;QAC/C,GAAG,CAAC,GAAG,CAAC,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,CAAC;KACnE,CAAC;AACJ,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"create-job-table.d.ts","sourceRoot":"","sources":["../../src/jobs/create-job-table.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAKjC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkC7F"}
1
+ {"version":3,"file":"create-job-table.d.ts","sourceRoot":"","sources":["../../src/jobs/create-job-table.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAKjC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAoC7F"}