@postxl/generators 6.2.0 → 6.3.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 (35) hide show
  1. package/dist/backend-database-prisma/generators/database-config.generator.js +4 -0
  2. package/dist/backend-database-prisma/generators/database-config.generator.js.map +1 -1
  3. package/dist/backend-database-prisma/generators/database-service.generator.js +24 -3
  4. package/dist/backend-database-prisma/generators/database-service.generator.js.map +1 -1
  5. package/dist/backend-database-prisma/prisma.generator.js +24 -3
  6. package/dist/backend-database-prisma/prisma.generator.js.map +1 -1
  7. package/dist/backend-repositories/generators/model-repository.generator.js +124 -33
  8. package/dist/backend-repositories/generators/model-repository.generator.js.map +1 -1
  9. package/dist/backend-repositories/model.types.d.ts +7 -0
  10. package/dist/backend-repositories/model.types.js +19 -4
  11. package/dist/backend-repositories/model.types.js.map +1 -1
  12. package/dist/backend-repositories/repositories.generator.js +1 -1
  13. package/dist/backend-repositories/repositories.generator.js.map +1 -1
  14. package/dist/frontend-actions/actions.generator.d.ts +14 -1
  15. package/dist/frontend-actions/actions.generator.js.map +1 -1
  16. package/dist/frontend-actions/generators/base-global-actions.generator.js +4 -1
  17. package/dist/frontend-actions/generators/base-global-actions.generator.js.map +1 -1
  18. package/dist/frontend-actions/generators/command-palette-store.generator.js +29 -0
  19. package/dist/frontend-actions/generators/command-palette-store.generator.js.map +1 -1
  20. package/dist/frontend-actions/generators/command-palette.generator.js +141 -8
  21. package/dist/frontend-actions/generators/command-palette.generator.js.map +1 -1
  22. package/dist/frontend-actions/index.d.ts +1 -0
  23. package/dist/frontend-actions/index.js.map +1 -1
  24. package/dist/frontend-admin/admin.generator.d.ts +14 -0
  25. package/dist/frontend-admin/admin.generator.js +131 -122
  26. package/dist/frontend-admin/admin.generator.js.map +1 -1
  27. package/dist/frontend-admin/index.d.ts +2 -0
  28. package/dist/frontend-admin/index.js +2 -1
  29. package/dist/frontend-admin/index.js.map +1 -1
  30. package/dist/frontend-admin/utils.js +16 -13
  31. package/dist/frontend-admin/utils.js.map +1 -1
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +3 -2
  34. package/dist/index.js.map +1 -1
  35. package/package.json +2 -2
@@ -7,6 +7,10 @@ import { Injectable } from '@nestjs/common'
7
7
 
8
8
  export type ${config.type.name} = Readonly<{
9
9
  readonly connectionString: string
10
+ readonly max?: number
11
+ readonly connectionTimeoutMillis?: number
12
+ readonly idleTimeoutMillis?: number
13
+ readonly statementTimeoutMs?: number
10
14
  }>
11
15
 
12
16
  @Injectable()
@@ -1 +1 @@
1
- {"version":3,"file":"database-config.generator.js","sourceRoot":"","sources":["../../../src/backend-database-prisma/generators/database-config.generator.ts"],"names":[],"mappings":";;;AAEA,gCAAuC,EAAE,MAAM,EAAmB;IAChE,OAAO,QAAQ,CAAC;;;cAGJ,MAAM,CAAC,IAAI,CAAC,IAAI;;;;;eAKf,MAAM,CAAC,IAAI;wCACc,MAAM,CAAC,IAAI,CAAC,IAAI;;CAEvD,CAAA;AACD,CAAC"}
1
+ {"version":3,"file":"database-config.generator.js","sourceRoot":"","sources":["../../../src/backend-database-prisma/generators/database-config.generator.ts"],"names":[],"mappings":";;;AAEA,gCAAuC,EAAE,MAAM,EAAmB;IAChE,OAAO,QAAQ,CAAC;;;cAGJ,MAAM,CAAC,IAAI,CAAC,IAAI;;;;;;;;;eASf,MAAM,CAAC,IAAI;wCACc,MAAM,CAAC,IAAI,CAAC,IAAI;;CAEvD,CAAA;AACD,CAAC"}
@@ -13,19 +13,40 @@ import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'
13
13
  import { Pool } from 'pg'
14
14
  import { PrismaPg } from '@prisma/adapter-pg'
15
15
  ${imports.generate()}
16
+
17
+ const DEFAULT_POOL_MAX = 20
18
+ const DEFAULT_CONNECTION_TIMEOUT_MS = 10_000
19
+ const DEFAULT_IDLE_TIMEOUT_MS = 30_000
20
+ const DEFAULT_STATEMENT_TIMEOUT_MS = 30_000
21
+
16
22
  @Injectable()
17
23
  export class ${service.name} extends PrismaClient implements OnModuleDestroy {
18
24
  private readonly logger = new Logger(${service.name}.name)
25
+ private readonly pool: Pool
19
26
 
20
27
  constructor(config: ${config.name}) {
21
- const pool = new Pool({ connectionString: config.config.connectionString })
28
+ const pool = new Pool({
29
+ connectionString: config.config.connectionString,
30
+ max: config.config.max ?? DEFAULT_POOL_MAX,
31
+ connectionTimeoutMillis: config.config.connectionTimeoutMillis ?? DEFAULT_CONNECTION_TIMEOUT_MS,
32
+ idleTimeoutMillis: config.config.idleTimeoutMillis ?? DEFAULT_IDLE_TIMEOUT_MS,
33
+ statement_timeout: config.config.statementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS,
34
+ })
22
35
  const adapter = new PrismaPg(pool)
23
36
 
24
- super({adapter})
37
+ super({ adapter })
38
+ this.pool = pool
39
+ this.pool.on('error', (error) => {
40
+ this.logger.error('Unexpected error on idle database client', error)
41
+ })
25
42
  }
26
43
 
27
44
  public async onModuleDestroy() {
28
- await this.$disconnect()
45
+ try {
46
+ await this.$disconnect()
47
+ } finally {
48
+ await this.pool.end().catch(() => undefined)
49
+ }
29
50
  }
30
51
 
31
52
  // eslint-disable-next-line @typescript-eslint/require-await
@@ -1 +1 @@
1
- {"version":3,"file":"database-service.generator.js","sourceRoot":"","sources":["../../../src/backend-database-prisma/generators/database-service.generator.ts"],"names":[],"mappings":";;;AAAA,iDAAmD;AAInD,iCAAwC,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAmB;IACxF,MAAM,OAAO,GAAG,2BAAe;QAC7B,EAAE;SACD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;SACtB,GAAG,CAAC,YAAY,CAAC;SACjB,GAAG,CAAC,MAAM,CAAC,CAAA;IAEd,OAAO,QAAQ,CAAC;;;;EAIhB,OAAO,CAAC,QAAQ,EAAE;;eAEL,OAAO,CAAC,IAAI;yCACc,OAAO,CAAC,IAAI;;wBAE7B,MAAM,CAAC,IAAI;;;;;;;;;;;;;;;;;;;EAmBjC,CAAA;AACF,CAAC"}
1
+ {"version":3,"file":"database-service.generator.js","sourceRoot":"","sources":["../../../src/backend-database-prisma/generators/database-service.generator.ts"],"names":[],"mappings":";;;AAAA,iDAAmD;AAInD,iCAAwC,EAAE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAmB;IACxF,MAAM,OAAO,GAAG,2BAAe;QAC7B,EAAE;SACD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;SACtB,GAAG,CAAC,YAAY,CAAC;SACjB,GAAG,CAAC,MAAM,CAAC,CAAA;IAEd,OAAO,QAAQ,CAAC;;;;EAIhB,OAAO,CAAC,QAAQ,EAAE;;;;;;;;eAQL,OAAO,CAAC,IAAI;yCACc,OAAO,CAAC,IAAI;;;wBAG7B,MAAM,CAAC,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiCjC,CAAA;AACF,CAAC"}
@@ -63,9 +63,30 @@ exports.generator = {
63
63
  DatabaseModule.forRoot(config.db)`),
64
64
  },
65
65
  envConfig: {
66
- dotEnvExample: `DATABASE_CONNECTION=postgresql://postgres:postgres@localhost:5432/${context.schema.slug}`, // NOSONAR - this is an example
67
- decoder: (0, generator_1.ts)('DATABASE_CONNECTION: z.string()'),
68
- transformer: (0, generator_1.ts)('db: { connectionString: val.DATABASE_CONNECTION }'),
66
+ dotEnvExample: `
67
+ DATABASE_CONNECTION=postgresql://postgres:postgres@localhost:5432/${context.schema.slug}
68
+ # Optional pg.Pool tuning (defaults: max=20, connectionTimeoutMillis=10000, idleTimeoutMillis=30000, statementTimeoutMs=30000)
69
+ # DATABASE_POOL_MAX=20
70
+ # DATABASE_POOL_CONNECTION_TIMEOUT_MS=10000
71
+ # DATABASE_POOL_IDLE_TIMEOUT_MS=30000
72
+ # DATABASE_STATEMENT_TIMEOUT_MS=30000
73
+ `, // NOSONAR - this is an example
74
+ decoder: (0, generator_1.ts)(`
75
+ DATABASE_CONNECTION: z.string(),
76
+ DATABASE_POOL_MAX: z.coerce.number().int().positive().optional(),
77
+ DATABASE_POOL_CONNECTION_TIMEOUT_MS: z.coerce.number().int().nonnegative().optional(),
78
+ DATABASE_POOL_IDLE_TIMEOUT_MS: z.coerce.number().int().nonnegative().optional(),
79
+ DATABASE_STATEMENT_TIMEOUT_MS: z.coerce.number().int().nonnegative().optional()
80
+ `),
81
+ transformer: (0, generator_1.ts)(`
82
+ db: {
83
+ connectionString: val.DATABASE_CONNECTION,
84
+ max: val.DATABASE_POOL_MAX,
85
+ connectionTimeoutMillis: val.DATABASE_POOL_CONNECTION_TIMEOUT_MS,
86
+ idleTimeoutMillis: val.DATABASE_POOL_IDLE_TIMEOUT_MS,
87
+ statementTimeoutMs: val.DATABASE_STATEMENT_TIMEOUT_MS,
88
+ }
89
+ `),
69
90
  },
70
91
  };
71
92
  context.backend.modules.push(module);
@@ -1 +1 @@
1
- {"version":3,"file":"prisma.generator.js","sourceRoot":"","sources":["../../src/backend-database-prisma/prisma.generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAAmC;AAEnC,MAAY,SAAS,8CAAyB;AAC9C,iDAAsC;AAEtC,kDAA+E;AAC/E,kCAAmD;AAEnD,sFAA+E;AAC/E,sFAA+E;AAC/E,wFAAiF;AACjF,kEAAkE;AAClE,kFAA2E;AA4B9D,QAAA,WAAW,GAAG,SAAS,CAAC,sBAAsB,CAAC,yBAAyB,CAAC,CAAA;AACzE,QAAA,mBAAmB,GAAG,SAAS,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,CAAA;AAE1E,QAAA,SAAS,GAAiC;IACrD,EAAE,EAAE,QAAA,WAAW;IACf,mBAAmB,EAAE,CAAC,QAAA,mBAAmB,CAAC;IAE1C,QAAQ,EAAE,CAAC,iCAAkB,EAAE,sBAAe,CAAC;IAE/C,QAAQ,EAAE,CAAsC,OAAgB,EAAyB,EAAE;QACzF,MAAM,WAAW,GAA8B;YAC7C,IAAI,EAAE,S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AC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,WAAY,CAAC,EAAE,IAAA,kDAAsB,EAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA,CAAC,UAAU;QAC9H,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,WAAW,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,IAAA,oDAAuB,EAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;QACxG,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,WAAW,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAA,kDAAsB,EAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;QACtG,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,IAAA,qCAAmB,EAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;QAE/D,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,iBAAiB,EAAE,CAAA;QACnD,SAAS,CAAC,aAAa,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,CAAA;QAE3D,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,UAAU,EAAE,uBAAuB,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC,CAAA;QAClF,MAAM,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,IAAA,mBAAO,EAAC,SAAS,EAAE,UAAU,CAAC,EAAE,CAAC,CAAA;QAE1E,OAAO,OAAO,CAAA;IAChB,CAAC;CACF,CAAA"}
@@ -85,7 +85,10 @@ const generateRepository_DatabaseCached = (model, context) => {
85
85
  const indexBlocks = generateIndexBlocks_Cached(params);
86
86
  const relationsBlocks = generateRelationsBlocks_Cached(params);
87
87
  const fields = Array.from(model.fields.values());
88
- const userRepositorySpecificBlocks = generateUserRepositorySpecificBlocks_Database(params);
88
+ const userRepositorySpecificBlocks = generateUserRepositorySpecificBlocks_Database({
89
+ ...params,
90
+ hasSetFunction: true,
91
+ });
89
92
  const idField = model.idField;
90
93
  /**
91
94
  * In case of Action or ActionOperation model, we do not want to log the actions, as this would lead to an endless recursion
@@ -123,6 +126,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
123
126
  ${userRepositorySpecificBlocks.getterBlock}
124
127
 
125
128
  private readonly mutex = new Mutex()
129
+ private mirrorMutationSeq = 0
126
130
 
127
131
  constructor(protected db: ${context.database.service.name}) {}
128
132
 
@@ -269,15 +273,6 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
269
273
 
270
274
  const result = dbItems.map((item) => ${model.decoder.flattened.decoder.parseFunction.name}(item))
271
275
 
272
- ${indexBlocks.assertFunction === ''
273
- ? ''
274
- : `// Check the whole batch against the cache before storing any of it, so a
275
- // stale cache that rejects one row is not left holding the rows before it.
276
- const claimed = { indexes: { ${indexBlocks.claimedInitEntries.join(', ')} } }
277
- for (const item of result) {
278
- ${assertUniqueIndexesCall({ indexBlocks, item: 'item', claimed: 'claimed.indexes' })}
279
- ${indexBlocks.claimCode.join('\n')}
280
- }`}
281
276
  for (const item of result) {
282
277
  this.set(item)
283
278
  }
@@ -302,7 +297,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
302
297
  public async update(
303
298
  { item, execution, expect }: { item: ${model.types.dto.update.name}, execution: ${context.actions.execution.interface.name}, expect?: ${(0, expect_type_helper_1.generateExpectType)(model)} }
304
299
  ): Promise<${model.types.name}> {
305
- const snapshot = await this.get(item.${idField.name})
300
+ const snapshot = await this.getOrFetchFromDb(item.${idField.name})
306
301
  if (!snapshot) {
307
302
  throw new Error(\`Could not update ${model.userFriendlyName} with id \${item.id}. Not found!\`)
308
303
  }
@@ -347,14 +342,6 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
347
342
  }),
348
343
  )
349
344
 
350
- ${assertUniqueIndexesCall({
351
- indexBlocks,
352
- item: 'newItem',
353
- comment: [
354
- 'Checked before remove(), so a violation leaves the cached row in place.',
355
- 'The row being replaced is excluded, so keeping its own values is fine.',
356
- ],
357
- })}
358
345
  this.remove(existingItem)
359
346
  this.set(newItem)
360
347
  release()
@@ -374,7 +361,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
374
361
  public async upsert(
375
362
  { item, execution }: { item: ${model.types.dto.upsert.name}, execution: ${context.actions.execution.interface.name} }
376
363
  ): Promise<${model.types.name}> {
377
- const existingItem = item.${model.idField.name} ? (await this.get(item.${model.idField.name})) : null
364
+ const existingItem = item.${model.idField.name} ? (await this.getOrFetchFromDb(item.${model.idField.name})) : null
378
365
  if (existingItem) {
379
366
  return this.update({ item: item as ${model.types.dto.update.name}, execution })
380
367
  } else {
@@ -388,7 +375,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
388
375
  public async delete(
389
376
  { id, execution }: { id: ${model.types.id.name}, execution: ${context.actions.execution.interface.name} }
390
377
  ): Promise<${model.types.id.name}> {
391
- const snapshot = await this.get(id)
378
+ const snapshot = await this.getOrFetchFromDb(id)
392
379
  if (!snapshot) {
393
380
  throw new Error(\`Could not delete ${model.types.name} with id \${id}. Not found!\`)
394
381
  }
@@ -442,7 +429,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
442
429
  item: (item: ${model.types.name}) => ${model.types.dto.clone.name},
443
430
  execution: ${context.actions.execution.interface.name}
444
431
  }): Promise<${model.types.name}> {
445
- const source = await this.get(id)
432
+ const source = await this.getOrFetchFromDb(id)
446
433
  if (!source) {
447
434
  throw new Error(\`${model.userFriendlyName} with id \${id} not found\`)
448
435
  }
@@ -458,13 +445,64 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
458
445
 
459
446
  ${uniqueStringFieldsBlocks.ensureUniqueFunctions.join('\n\n')}
460
447
 
461
- ${indexBlocks.assertFunction}
448
+ /**
449
+ * Reads an item from the local mirror, falling back to Postgres on a mirror
450
+ * miss (e.g. a row created by another replica) and populating the mirror if found.
451
+ */
452
+ private async getOrFetchFromDb(id: ${model.types.id.name}): Promise<${model.types.name} | null> {
453
+ const cached = await this.get(id)
454
+ if (cached) {
455
+ return cached
456
+ }
457
+
458
+ const seqBeforeFetch = this.mirrorMutationSeq
459
+ const raw = await this.db.${repository.prismaClientName}.findUnique({ where: { ${idField.databaseName}: id } })
460
+ if (!raw) {
461
+ return null
462
+ }
463
+
464
+ const release = await this.mutex.acquire()
465
+ try {
466
+ const rechecked = this.data.get(id)
467
+ if (rechecked) {
468
+ release()
469
+ return rechecked
470
+ }
471
+
472
+ const item = ${model.decoder.flattened.decoder.parseFunction.name}(raw)
473
+ if (this.mirrorMutationSeq === seqBeforeFetch) {
474
+ this.set(item)
475
+ }
476
+ release()
477
+ return item
478
+ } catch (error) {
479
+ release()
480
+ throw error
481
+ }
482
+ }
483
+
484
+ /**
485
+ * Evicts any stale mirror entry that collides with a row Postgres has already committed.
486
+ *
487
+ * In multi-replica deployments another replica may have deleted or renamed a row that
488
+ * still sits in this process mirror. Evicting the stale entry before updating the maps
489
+ * keeps the mirror consistent with Postgres without throwing post-commit.
490
+ */
491
+ private evictStaleMirrorCollisions(item: ${model.types.name}): void {
492
+ const existingById = this.data.get(item.${idField.name})
493
+ if (existingById) {
494
+ this.remove(existingById)
495
+ }
496
+ ${uniqueStringFieldsBlocks.evictCode.join('\n')}
497
+ ${indexBlocks.evictCode.join('\n')}
498
+ }
462
499
 
463
500
  /**
464
501
  * Function that adds/updates a given item to the internal data store, indexes, etc.
465
502
  */
466
503
  private set(item: ${model.types.name}): void {
467
- ${assertUniqueIndexesCall({ indexBlocks, item: 'item', comment: ['Before any mutation, so a violation leaves the state unchanged.'] })}
504
+ this.evictStaleMirrorCollisions(item)
505
+ this.mirrorMutationSeq++
468
506
 
469
507
  ${idBlocks.setCode}
470
508
 
@@ -481,6 +519,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
481
519
  * Function that removes a given item from the internal data store, indexes, etc.
482
520
  */
483
521
  private remove(item: ${model.types.name}): void {
522
+ this.mirrorMutationSeq++
484
523
  this.data.delete(item.id)
485
524
  ${uniqueStringFieldsBlocks.removeCode.join('\n')}
486
525
 
@@ -541,9 +580,9 @@ const generateRepository_DatabaseDirect = (model, context) => {
541
580
  const indexBlocks = generateIndexBlocks_Database(params);
542
581
  const relationsBlocks = generateRelationsBlocks_Database(params);
543
582
  const fields = Array.from(model.fields.values());
544
- const userRepositorySpecificBlocks = generateUserRepositorySpecificBlocks_Database(params);
545
583
  const idField = model.idField;
546
584
  const hasSetFunction = idBlocks.setCode.length > 0;
585
+ const userRepositorySpecificBlocks = generateUserRepositorySpecificBlocks_Database({ ...params, hasSetFunction });
547
586
  const setFunction = hasSetFunction
548
587
  ? `
549
588
  /**
@@ -1295,12 +1334,13 @@ const blankUserRepositorySpecificBlocks = {
1295
1334
  initCall: '',
1296
1335
  rootUserInitializeBlock: '',
1297
1336
  };
1298
- function generateUserRepositorySpecificBlocks_Database({ model, context, imports, }) {
1337
+ function generateUserRepositorySpecificBlocks_Database({ model, context, imports, hasSetFunction, }) {
1299
1338
  if (model.name !== 'User') {
1300
1339
  return blankUserRepositorySpecificBlocks;
1301
1340
  }
1302
1341
  const { types, repository } = model;
1303
1342
  const rootUserValue = generateSharedRootUserBlocks({ model, context, imports });
1343
+ const setRootUserLine = hasSetFunction ? '\n this.set(newRootUser)' : '';
1304
1344
  return {
1305
1345
  rootUserNameConst: `public static readonly ROOT_USER_ID = ${types.id.toBranded.name}('${context.schema.systemUser.id}')`,
1306
1346
  getterBlock: `
@@ -1323,8 +1363,7 @@ function generateUserRepositorySpecificBlocks_Database({ model, context, imports
1323
1363
  const rawUser = await this.db.${model.repository.prismaClientName}.create({
1324
1364
  data: ${model.decoder.flattened.encoder.name}(${rootUserValue} as unknown as any),
1325
1365
  })
1326
- const newRootUser = ${model.decoder.flattened.decoder.parseFunction.name}(rawUser)
1327
- this.set(newRootUser)
1366
+ const newRootUser = ${model.decoder.flattened.decoder.parseFunction.name}(rawUser)${setRootUserLine}
1328
1367
  this._rootUser = newRootUser
1329
1368
  release()
1330
1369
  }`,
@@ -1614,6 +1653,7 @@ function initUniqueIds() {
1614
1653
  ensureUniqueFunctions: [],
1615
1654
  setCode: [],
1616
1655
  removeCode: [],
1656
+ evictCode: [],
1617
1657
  claimedTypeEntries: [],
1618
1658
  claimedInitEntries: [],
1619
1659
  claimCode: [],
@@ -1702,6 +1742,23 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
1702
1742
  result.setCode.push(`if (item.${f.name} !== null) { this.uniqueIds.${f.name}.set(item.${f.name}, item) }`);
1703
1743
  result.removeCode.push(`if (item.${f.name} !== null) { this.uniqueIds.${f.name}.delete(item.${f.name}) }`);
1704
1744
  }
1745
+ if (!isInMemory && !isId) {
1746
+ const existingVar = `existingUnique${(0, utils_1.toPascalCase)(f.name)}`;
1747
+ const evictBody = `
1748
+ const ${existingVar} = this.uniqueIds.${f.name}.get(item.${f.name})
1749
+ if (${existingVar} && ${existingVar}.${idField.name} !== item.${idField.name}) {
1750
+ this.logger.warn(\`Evicting stale ${types.name} (id=\${${existingVar}.${idField.name}}) colliding with committed ${types.name} (id=\${item.${idField.name}}) on unique field ${f.name}\`)
1751
+ this.remove(${existingVar})
1752
+ }`;
1753
+ if (f.isRequired) {
1754
+ result.evictCode.push(evictBody);
1755
+ }
1756
+ else {
1757
+ result.evictCode.push(`
1758
+ if (item.${f.name} !== null) {${evictBody}
1759
+ }`);
1760
+ }
1761
+ }
1705
1762
  if (isInMemory) {
1706
1763
  result.claimedTypeEntries.push(`${f.name}: Set<string>`);
1707
1764
  result.claimedInitEntries.push(`${f.name}: new Set<string>()`);
@@ -1877,6 +1934,7 @@ function initIndexBlockOptions() {
1877
1934
  getterFunctions: [],
1878
1935
  setCode: [],
1879
1936
  removeCode: [],
1937
+ evictCode: [],
1880
1938
  assertFunction: '',
1881
1939
  claimedTypeEntries: [],
1882
1940
  claimedInitEntries: [],
@@ -1979,9 +2037,13 @@ function generateIndexBlocks_Cached({ model, context, imports }) {
1979
2037
  await this.mutex.waitForUnlock()
1980
2038
  return Promise.resolve(this.${i.name}.get(this.${keyFnName}(${keyArgFromFields})) ?? null) // NOSONAR
1981
2039
  }`);
2040
+ const nullableFields = i.fields.filter((f) => !f.isRequired);
2041
+ const nonNullGuard = nullableFields.map((f) => `item.${f.name} !== null`).join(' && ');
1982
2042
  // A stored entry holding the item's own id is the row an update replaces,
1983
2043
  // which keeping its own values does not conflict with.
1984
- assertCode.push(`{
2044
+ // Postgres treats NULLs as distinct in unique indexes, so rows with a null
2045
+ // index column never collide with each other.
2046
+ const assertBlock = `{
1985
2047
  const ${i.name}Key = this.${keyFnName}(item)
1986
2048
  const ${existingVar} = [this.${i.name}.get(${i.name}Key), claimed?.${i.name}.get(${i.name}Key)].find(
1987
2049
  (existing) => existing !== undefined && existing.id !== item.id,
@@ -1989,12 +2051,41 @@ function generateIndexBlocks_Cached({ model, context, imports }) {
1989
2051
  if (${existingVar}) {
1990
2052
  throw new Error(\`Uniqueness violation on index ${i.name} of ${model.types.name}: another item (id=\${${existingVar}.id}) already has the same values for [${fieldsListForError}]\`)
1991
2053
  }
1992
- }`);
1993
- result.setCode.push(`this.${i.name}.set(this.${keyFnName}(item), item)`);
1994
- result.removeCode.push(`this.${i.name}.delete(this.${keyFnName}(item))`);
2054
+ }`;
2055
+ assertCode.push(nullableFields.length === 0 ? assertBlock : `if (${nonNullGuard}) ${assertBlock}`);
2056
+ if (nullableFields.length === 0) {
2057
+ result.setCode.push(`this.${i.name}.set(this.${keyFnName}(item), item)`);
2058
+ result.removeCode.push(`this.${i.name}.delete(this.${keyFnName}(item))`);
2059
+ }
2060
+ else {
2061
+ // Postgres treats NULLs as distinct in unique indexes, so rows with a null
2062
+ // index column never collide with each other and must not overwrite or evict
2063
+ // one another in the mirror.
2064
+ result.setCode.push(`if (${nonNullGuard}) { this.${i.name}.set(this.${keyFnName}(item), item) }`);
2065
+ result.removeCode.push(`if (${nonNullGuard}) { this.${i.name}.delete(this.${keyFnName}(item)) }`);
2066
+ }
2067
+ if (!isInMemory) {
2068
+ const existingIndexVar = `existingIndex${(0, utils_1.toPascalCase)(i.name)}`;
2069
+ const evictBody = `
2070
+ const ${existingIndexVar} = this.${i.name}.get(this.${keyFnName}(item))
2071
+ if (${existingIndexVar} && ${existingIndexVar}.${model.idField.name} !== item.${model.idField.name}) {
2072
+ this.logger.warn(\`Evicting stale ${model.types.name} (id=\${${existingIndexVar}.${model.idField.name}}) colliding with committed ${model.types.name} (id=\${item.${model.idField.name}}) on unique index ${i.name}\`)
2073
+ this.remove(${existingIndexVar})
2074
+ }`;
2075
+ if (nullableFields.length === 0) {
2076
+ result.evictCode.push(evictBody);
2077
+ }
2078
+ else {
2079
+ result.evictCode.push(`
2080
+ if (${nonNullGuard}) {${evictBody}
2081
+ }`);
2082
+ }
2083
+ }
1995
2084
  result.claimedTypeEntries.push(`${i.name}: Map<string, ${model.types.name}>`);
1996
2085
  result.claimedInitEntries.push(`${i.name}: new Map<string, ${model.types.name}>()`);
1997
- result.claimCode.push(`claimed.indexes.${i.name}.set(this.${keyFnName}(item), item)`);
2086
+ result.claimCode.push(nullableFields.length === 0
2087
+ ? `claimed.indexes.${i.name}.set(this.${keyFnName}(item), item)`
2088
+ : `if (${nonNullGuard}) { claimed.indexes.${i.name}.set(this.${keyFnName}(item), item) }`);
1998
2089
  }
1999
2090
  result.assertFunction = `${Generator.toJsDocComment([
2000
2091
  `Throws if storing the given ${model.userFriendlyName} would violate one of its unique indexes.`,