@postxl/generators 6.0.1 → 6.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend-actions/generators/dispatcher-service.generator.js +6 -1
- package/dist/backend-actions/generators/dispatcher-service.generator.js.map +1 -1
- package/dist/backend-ai/ai.generator.d.ts +2 -7
- package/dist/backend-ai/ai.generator.js.map +1 -1
- package/dist/backend-ai/get-backend-ai.d.ts +18 -0
- package/dist/backend-ai/get-backend-ai.js +11 -0
- package/dist/backend-ai/get-backend-ai.js.map +1 -0
- package/dist/backend-ai/index.d.ts +1 -0
- package/dist/backend-ai/index.js +3 -1
- package/dist/backend-ai/index.js.map +1 -1
- package/dist/backend-core/backend.generator.js +1 -1
- package/dist/backend-core/backend.generator.js.map +1 -1
- package/dist/backend-core/template/libs/xlport/README.md +5 -5
- package/dist/backend-database-prisma/generators/prisma-schema.generator.js +5 -0
- package/dist/backend-database-prisma/generators/prisma-schema.generator.js.map +1 -1
- package/dist/backend-excel-io/template/README.md +3 -3
- package/dist/backend-import/generators/detect-delta/model-function.generator.js +4 -1
- package/dist/backend-import/generators/detect-delta/model-function.generator.js.map +1 -1
- package/dist/backend-repositories/generators/model-repository.generator.js +245 -74
- package/dist/backend-repositories/generators/model-repository.generator.js.map +1 -1
- package/dist/backend-router-trpc/generators/app-routes.generator.js +7 -3
- package/dist/backend-router-trpc/generators/app-routes.generator.js.map +1 -1
- package/dist/backend-router-trpc/generators/trpc-plugin.generator.js +10 -3
- package/dist/backend-router-trpc/generators/trpc-plugin.generator.js.map +1 -1
- package/dist/backend-router-trpc/generators/trpc-router-module.generator.js +13 -6
- package/dist/backend-router-trpc/generators/trpc-router-module.generator.js.map +1 -1
- package/dist/backend-router-trpc/generators/trpc-shared.generator.js +16 -3
- package/dist/backend-router-trpc/generators/trpc-shared.generator.js.map +1 -1
- package/dist/backend-router-trpc/router-trpc.generator.d.ts +1 -2
- package/dist/backend-router-trpc/router-trpc.generator.js +2 -1
- package/dist/backend-router-trpc/router-trpc.generator.js.map +1 -1
- package/dist/backend-router-trpc/template/viewer.router.ts +31 -0
- package/dist/backend-update/model-update-service.generator.js +20 -4
- package/dist/backend-update/model-update-service.generator.js.map +1 -1
- package/dist/backend-update/update.generator.js +6 -2
- package/dist/backend-update/update.generator.js.map +1 -1
- package/dist/base/base.generator.js +6 -16
- package/dist/base/base.generator.js.map +1 -1
- package/dist/base/generators/claudemd.generator.js +21 -0
- package/dist/base/generators/claudemd.generator.js.map +1 -1
- package/dist/base/template/.claude/commands/README.md +10 -1
- package/dist/base/template/.claude/commands/browser-observe.md +72 -72
- package/dist/base/template/.claude/commands/fix-ci.md +12 -7
- package/dist/base/template/.oxfmtrc.json +17 -0
- package/dist/base/template/.oxlintrc.json +1130 -0
- package/dist/base/template/.vscode/extensions.json +2 -4
- package/dist/base/template/.vscode/settings.json +7 -5
- package/dist/decoders/default-value.helper.d.ts +25 -1
- package/dist/decoders/default-value.helper.js +44 -0
- package/dist/decoders/default-value.helper.js.map +1 -1
- package/dist/decoders/excel-field-decoder.helper.js +23 -5
- package/dist/decoders/excel-field-decoder.helper.js.map +1 -1
- package/dist/decoders/field-decoder.helper.js +16 -9
- package/dist/decoders/field-decoder.helper.js.map +1 -1
- package/dist/devops/generators/bitbucket-pipelines-yml.generator.js +7 -1
- package/dist/devops/generators/bitbucket-pipelines-yml.generator.js.map +1 -1
- package/dist/devops/generators/e2e-yml.generator.js +9 -2
- package/dist/devops/generators/e2e-yml.generator.js.map +1 -1
- package/dist/devops/generators/prisma-migrations.d.ts +14 -0
- package/dist/devops/generators/prisma-migrations.js +18 -0
- package/dist/devops/generators/prisma-migrations.js.map +1 -0
- package/dist/e2e/e2e.generator.js +2 -0
- package/dist/e2e/e2e.generator.js.map +1 -1
- package/dist/e2e/template/.claude/commands/run-e2e-tests.md +7 -1
- package/dist/e2e/template/e2e/package.json +1 -1
- package/dist/e2e/template/e2e/specs/example.spec.ts +2 -2
- package/dist/e2e/template/e2e/tsconfig.json +0 -3
- package/dist/frontend-actions/actions.generator.js +12 -6
- package/dist/frontend-actions/actions.generator.js.map +1 -1
- package/dist/frontend-actions/generators/base-global-actions.generator.d.ts +7 -1
- package/dist/frontend-actions/generators/base-global-actions.generator.js +89 -1
- package/dist/frontend-actions/generators/base-global-actions.generator.js.map +1 -1
- package/dist/frontend-actions/generators/sidepanel-toggle.generator.d.ts +4 -0
- package/dist/frontend-actions/generators/sidepanel-toggle.generator.js +4 -0
- package/dist/frontend-actions/generators/sidepanel-toggle.generator.js.map +1 -1
- package/dist/frontend-admin/generators/admin-global-actions.generator.js +3 -0
- package/dist/frontend-admin/generators/admin-global-actions.generator.js.map +1 -1
- package/dist/frontend-admin/generators/detail-sidebar.generator.js +30 -17
- package/dist/frontend-admin/generators/detail-sidebar.generator.js.map +1 -1
- package/dist/frontend-admin/generators/model-admin-page.generator.js +56 -61
- package/dist/frontend-admin/generators/model-admin-page.generator.js.map +1 -1
- package/dist/frontend-core/frontend.generator.js +15 -11
- package/dist/frontend-core/frontend.generator.js.map +1 -1
- package/dist/frontend-core/template/README.md +45 -10
- package/dist/frontend-core/template/src/components/ui/application-header/application-header.tsx +1 -1
- package/dist/frontend-core/template/src/context-providers/auth-context-provider.tsx +27 -1
- package/dist/frontend-core/template/src/pages/dashboard/dashboard.page.tsx +3 -5
- package/dist/frontend-core/template/src/stories/Configure.mdx +34 -26
- package/dist/frontend-core/template/vite.config.ts +2 -1
- package/dist/frontend-forms/generators/model/forms.generator.js +72 -30
- package/dist/frontend-forms/generators/model/forms.generator.js.map +1 -1
- package/dist/frontend-tables/generators/model-table.generator.js +4 -0
- package/dist/frontend-tables/generators/model-table.generator.js.map +1 -1
- package/dist/mock-data/generators/data-mocker.generator.js +27 -3
- package/dist/mock-data/generators/data-mocker.generator.js.map +1 -1
- package/dist/skailify/generators/capabilities-file.generator.js +14 -2
- package/dist/skailify/generators/capabilities-file.generator.js.map +1 -1
- package/dist/types/generators/models.generator.d.ts +9 -0
- package/dist/types/generators/models.generator.js +15 -3
- package/dist/types/generators/models.generator.js.map +1 -1
- package/dist/types/types.generator.d.ts +5 -0
- package/dist/types/types.generator.js +4 -0
- package/dist/types/types.generator.js.map +1 -1
- package/package.json +7 -7
- package/dist/base/template/.prettierignore +0 -6
- package/dist/base/template/eslint.config.mjs +0 -207
- package/dist/base/template/prettier.config.js +0 -10
- package/dist/frontend-core/template/.prettierignore +0 -4
- package/dist/frontend-core/template/vitest.shims.d.ts +0 -1
|
@@ -206,7 +206,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
206
206
|
`In case none exists, ${idBlocks.verifyFunctionComment}`,
|
|
207
207
|
uniqueStringFieldsBlocks.verifyFunctionComment,
|
|
208
208
|
maxLengthBlocks.verifyFunctionComment,
|
|
209
|
-
])}
|
|
209
|
+
].filter((line) => line !== ''))}
|
|
210
210
|
private verifyItem(
|
|
211
211
|
item: ${idBlocks.verifyFunctionParameterType}
|
|
212
212
|
): ${idBlocks.createFunctionParameterType} {
|
|
@@ -231,7 +231,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
231
231
|
})`)}
|
|
232
232
|
|
|
233
233
|
const release = await this.mutex.acquire()
|
|
234
|
-
|
|
234
|
+
|
|
235
235
|
try {
|
|
236
236
|
this.verifyItem(item)
|
|
237
237
|
const newItem = ${model.decoder.flattened.decoder.parseFunction.name}(
|
|
@@ -269,6 +269,15 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
269
269
|
|
|
270
270
|
const result = dbItems.map((item) => ${model.decoder.flattened.decoder.parseFunction.name}(item))
|
|
271
271
|
|
|
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
|
+
}`}
|
|
272
281
|
for (const item of result) {
|
|
273
282
|
this.set(item)
|
|
274
283
|
}
|
|
@@ -338,6 +347,14 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
338
347
|
}),
|
|
339
348
|
)
|
|
340
349
|
|
|
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
|
+
})}
|
|
341
358
|
this.remove(existingItem)
|
|
342
359
|
this.set(newItem)
|
|
343
360
|
release()
|
|
@@ -441,10 +458,14 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
441
458
|
|
|
442
459
|
${uniqueStringFieldsBlocks.ensureUniqueFunctions.join('\n\n')}
|
|
443
460
|
|
|
461
|
+
${indexBlocks.assertFunction}
|
|
462
|
+
|
|
444
463
|
/**
|
|
445
464
|
* Function that adds/updates a given item to the internal data store, indexes, etc.
|
|
446
465
|
*/
|
|
447
466
|
private set(item: ${model.types.name}): void {
|
|
467
|
+
${assertUniqueIndexesCall({ indexBlocks, item: 'item', comment: ['Before any mutation, so a violation leaves the state unchanged.'] })}
|
|
468
|
+
|
|
448
469
|
${idBlocks.setCode}
|
|
449
470
|
|
|
450
471
|
this.data.set(item.id, item)
|
|
@@ -617,17 +638,19 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
617
638
|
|
|
618
639
|
${uniqueStringFieldsBlocks.getByFunctions.join('\n')}
|
|
619
640
|
|
|
620
|
-
public async filter({ prisma: where }: Filter): Promise<${model.types.name}[]> {
|
|
641
|
+
public async filter({ predicate, prisma: where }: Filter): Promise<${model.types.name}[]> {
|
|
621
642
|
await this.mutex.waitForUnlock()
|
|
622
|
-
|
|
643
|
+
|
|
623
644
|
const data = await this.db.${repository.prismaClientName}.findMany({ where })
|
|
624
|
-
return data.map((item) => ${model.decoder.flattened.decoder.parseFunction.name}(item))
|
|
645
|
+
return data.map((item) => ${model.decoder.flattened.decoder.parseFunction.name}(item)).filter(predicate)
|
|
625
646
|
}
|
|
626
647
|
|
|
627
|
-
public async findFirst({ prisma: where }: Filter): Promise<${model.types.name} | null> {
|
|
648
|
+
public async findFirst({ predicate, prisma: where }: Filter): Promise<${model.types.name} | null> {
|
|
628
649
|
await this.mutex.waitForUnlock()
|
|
629
|
-
|
|
630
|
-
|
|
650
|
+
// The predicate must be applied before taking the first row, so it cannot be pushed into a
|
|
651
|
+
// single-row \`findFirst\` query: scan the rows matching \`prisma\` and take the first predicate match.
|
|
652
|
+
const data = await this.db.${repository.prismaClientName}.findMany({ where })
|
|
653
|
+
return data.map((item) => ${model.decoder.flattened.decoder.parseFunction.name}(item)).find(predicate) ?? null
|
|
631
654
|
}
|
|
632
655
|
|
|
633
656
|
${generateGetByKeyMethod_Database({ model })}
|
|
@@ -654,7 +677,8 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
654
677
|
`In case none exists, ${idBlocks.verifyFunctionComment}`,
|
|
655
678
|
uniqueStringFieldsBlocks.verifyFunctionComment,
|
|
656
679
|
maxLengthBlocks.verifyFunctionComment,
|
|
657
|
-
])}
|
|
680
|
+
].filter((line) => line !== ''))}
|
|
681
|
+
${uniqueStringFieldsBlocks.verifyCode.length === 0 ? '// eslint-disable-next-line @typescript-eslint/require-await' : ''}
|
|
658
682
|
private async verifyItem(item: ${idBlocks.verifyFunctionParameterType}): Promise<void> {
|
|
659
683
|
this.assertId(item)
|
|
660
684
|
|
|
@@ -676,7 +700,7 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
676
700
|
})`)}
|
|
677
701
|
|
|
678
702
|
const release = await this.mutex.acquire()
|
|
679
|
-
|
|
703
|
+
|
|
680
704
|
try {
|
|
681
705
|
await this.verifyItem(item)
|
|
682
706
|
this.assertId(item)
|
|
@@ -910,6 +934,22 @@ const generateRepository_InMemory = (model, context) => {
|
|
|
910
934
|
const indexBlocks = generateIndexBlocks_Cached(params);
|
|
911
935
|
const relationsBlocks = generateRelationsBlocks_Cached(params);
|
|
912
936
|
const userRepositorySpecificBlocks = generateUserRepositorySpecificBlocks_InMemory(params);
|
|
937
|
+
// createMany() verifies the whole batch before storing any of it, so the
|
|
938
|
+
// uniqueness checks have to see what earlier items of the batch claimed.
|
|
939
|
+
const hasClaimedUniqueIds = uniqueStringFieldsBlocks.claimedTypeEntries.length > 0;
|
|
940
|
+
const hasClaimedIndexes = indexBlocks.claimedTypeEntries.length > 0;
|
|
941
|
+
const claimedUniqueIdsParam = hasClaimedUniqueIds
|
|
942
|
+
? `, claimed?: { ${uniqueStringFieldsBlocks.claimedTypeEntries.join('; ')} }`
|
|
943
|
+
: '';
|
|
944
|
+
const claimedUniqueIdsArg = hasClaimedUniqueIds ? ', claimed.uniqueIds' : '';
|
|
945
|
+
const claimedEntries = [
|
|
946
|
+
...(hasClaimedUniqueIds ? [`uniqueIds: { ${uniqueStringFieldsBlocks.claimedInitEntries.join(', ')} }`] : []),
|
|
947
|
+
...(hasClaimedIndexes ? [`indexes: { ${indexBlocks.claimedInitEntries.join(', ')} }`] : []),
|
|
948
|
+
];
|
|
949
|
+
const createManyClaimedDeclaration = claimedEntries.length > 0
|
|
950
|
+
? `// Values claimed by the items verified so far - none is stored until all pass.
|
|
951
|
+
const claimed = { ${claimedEntries.join(', ')} }`
|
|
952
|
+
: '';
|
|
913
953
|
const idField = model.idField;
|
|
914
954
|
return `
|
|
915
955
|
import { Injectable, Logger } from '@nestjs/common'
|
|
@@ -1010,9 +1050,9 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
1010
1050
|
`In case none exists, ${idBlocks.verifyFunctionComment}`,
|
|
1011
1051
|
uniqueStringFieldsBlocks.verifyFunctionComment,
|
|
1012
1052
|
maxLengthBlocks.verifyFunctionComment,
|
|
1013
|
-
])}
|
|
1053
|
+
].filter((line) => line !== ''))}
|
|
1014
1054
|
private verifyItem(
|
|
1015
|
-
item: ${idBlocks.verifyFunctionParameterType}
|
|
1055
|
+
item: ${idBlocks.verifyFunctionParameterType}${claimedUniqueIdsParam}
|
|
1016
1056
|
): ${idBlocks.createFunctionParameterType} {
|
|
1017
1057
|
${idBlocks.verifyCode}
|
|
1018
1058
|
|
|
@@ -1040,19 +1080,37 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
1040
1080
|
}
|
|
1041
1081
|
}
|
|
1042
1082
|
|
|
1043
|
-
${Generator.toJsDocComment([
|
|
1083
|
+
${Generator.toJsDocComment([
|
|
1084
|
+
`Creates multiple new ${model.internalPluralName} and returns them.`,
|
|
1085
|
+
'',
|
|
1086
|
+
'All-or-nothing: every item is verified - against the stored rows and against',
|
|
1087
|
+
'the items before it in the batch - before any of them is stored, so a rejected',
|
|
1088
|
+
'item leaves the repository unchanged.',
|
|
1089
|
+
])}
|
|
1044
1090
|
public async createMany(
|
|
1045
1091
|
{items}: { items: ${model.types.dto.create.name}[], execution: ${context.actions.execution.interface.name} }
|
|
1046
1092
|
): Promise<${model.types.name}[]> {
|
|
1047
1093
|
const result: ${model.types.name}[] = []
|
|
1048
1094
|
const release = await this.mutex.acquire()
|
|
1049
1095
|
try {
|
|
1096
|
+
${createManyClaimedDeclaration}
|
|
1050
1097
|
for (const item of items) {
|
|
1051
|
-
this.verifyItem(item)
|
|
1052
|
-
|
|
1098
|
+
this.verifyItem(item${claimedUniqueIdsArg})
|
|
1099
|
+
${assertUniqueIndexesCall({ indexBlocks, item: 'item', claimed: 'claimed.indexes' })}
|
|
1100
|
+
${uniqueStringFieldsBlocks.claimCode.join('\n')}
|
|
1101
|
+
${indexBlocks.claimCode.join('\n')}
|
|
1102
|
+
${idBlocks.setCode === ''
|
|
1103
|
+
? ''
|
|
1104
|
+
: `// set() only runs once the whole batch has passed, so advance the id
|
|
1105
|
+
// counter here: the next item without an id must not reuse this one's.
|
|
1106
|
+
${idBlocks.setCode}`}
|
|
1053
1107
|
result.push(item)
|
|
1054
1108
|
}
|
|
1055
1109
|
|
|
1110
|
+
for (const item of result) {
|
|
1111
|
+
this.set(item)
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1056
1114
|
release()
|
|
1057
1115
|
return Promise.resolve(result) // NOSONAR - keep all validations async to adhere to the same interface
|
|
1058
1116
|
} catch (error) {
|
|
@@ -1098,6 +1156,14 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
1098
1156
|
) as Partial<${model.types.dto.update.name}>
|
|
1099
1157
|
const newItem = { ...existingItem, ...definedUpdates }
|
|
1100
1158
|
|
|
1159
|
+
${assertUniqueIndexesCall({
|
|
1160
|
+
indexBlocks,
|
|
1161
|
+
item: 'newItem',
|
|
1162
|
+
comment: [
|
|
1163
|
+
'Checked before remove(), so a violation leaves the stored row in place.',
|
|
1164
|
+
'The row being replaced is excluded, so keeping its own values is fine.',
|
|
1165
|
+
],
|
|
1166
|
+
})}
|
|
1101
1167
|
this.remove(existingItem)
|
|
1102
1168
|
this.set(newItem)
|
|
1103
1169
|
|
|
@@ -1188,10 +1254,14 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
1188
1254
|
|
|
1189
1255
|
${uniqueStringFieldsBlocks.ensureUniqueFunctions.join('\n\n')}
|
|
1190
1256
|
|
|
1257
|
+
${indexBlocks.assertFunction}
|
|
1258
|
+
|
|
1191
1259
|
/**
|
|
1192
1260
|
* Function that adds/updates a given item to the internal data store, indexes, etc.
|
|
1193
1261
|
*/
|
|
1194
1262
|
private set(item: ${model.types.name}): void {
|
|
1263
|
+
${assertUniqueIndexesCall({ indexBlocks, item: 'item', comment: ['Before any mutation, so a violation leaves the state unchanged.'] })}
|
|
1264
|
+
|
|
1195
1265
|
${idBlocks.setCode}
|
|
1196
1266
|
|
|
1197
1267
|
this.data.set(item.id, item)
|
|
@@ -1295,7 +1365,7 @@ function generateUserRepositorySpecificBlocks_InMemory({ model, context, imports
|
|
|
1295
1365
|
/**
|
|
1296
1366
|
* The literal the root user is seeded from.
|
|
1297
1367
|
*
|
|
1298
|
-
* A declared scalar `defaultValue` becomes a Prisma `@default` on the column, so
|
|
1368
|
+
* A declared scalar or enum `defaultValue` becomes a Prisma `@default` on the column, so
|
|
1299
1369
|
* on the database path the seed row gets it whether or not it is in the payload.
|
|
1300
1370
|
* The in-memory path has no column to fall back on - it stores this literal as
|
|
1301
1371
|
* the row - so a non-nullable field with a default that `systemUser` does not
|
|
@@ -1309,6 +1379,9 @@ function generateSharedRootUserBlocks({ model, context }) {
|
|
|
1309
1379
|
if (field.kind === 'scalar' && field.defaultValue !== undefined && !field.isCreatedAt && !field.isUpdatedAt) {
|
|
1310
1380
|
declaredDefaults[field.name] = field.defaultValue;
|
|
1311
1381
|
}
|
|
1382
|
+
if (field.kind === 'enum' && field.defaultValue !== undefined) {
|
|
1383
|
+
declaredDefaults[field.name] = field.defaultValue;
|
|
1384
|
+
}
|
|
1312
1385
|
}
|
|
1313
1386
|
return JSON.stringify({ ...declaredDefaults, ...context.schema.systemUser });
|
|
1314
1387
|
}
|
|
@@ -1385,10 +1458,15 @@ function generateIdBlocks_InMemory({ model, imports }) {
|
|
|
1385
1458
|
const verifyCodeNullableFields = nullableFieldsToNormalize
|
|
1386
1459
|
.map((f) => `;(item as Record<string, unknown>).${f.name} ??= null`)
|
|
1387
1460
|
.join('\n ');
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1461
|
+
// Empty entries are left out rather than interpolated as blank lines, which Oxfmt keeps.
|
|
1462
|
+
const verifyCodeDateFields = [
|
|
1463
|
+
createdAtField ? `;(item as any).${createdAtField.name} = new Date()` : '',
|
|
1464
|
+
updatedAtField ? `;(item as any).${updatedAtField.name} = new Date()` : '',
|
|
1465
|
+
verifyCodeNullableFields,
|
|
1466
|
+
]
|
|
1467
|
+
.filter((line) => line.length > 0)
|
|
1468
|
+
.map((line) => `\n ${line}`)
|
|
1469
|
+
.join('');
|
|
1392
1470
|
const createFunctionParameterType = `asserts item is ${types.name}`;
|
|
1393
1471
|
switch (idField.idType) {
|
|
1394
1472
|
case 'Increment': {
|
|
@@ -1536,10 +1614,23 @@ function initUniqueIds() {
|
|
|
1536
1614
|
ensureUniqueFunctions: [],
|
|
1537
1615
|
setCode: [],
|
|
1538
1616
|
removeCode: [],
|
|
1617
|
+
claimedTypeEntries: [],
|
|
1618
|
+
claimedInitEntries: [],
|
|
1619
|
+
claimCode: [],
|
|
1539
1620
|
};
|
|
1540
1621
|
}
|
|
1541
1622
|
/**
|
|
1542
1623
|
* Generates code chunks that enforce the uniqueness of a given field.
|
|
1624
|
+
*
|
|
1625
|
+
* A value that another item already holds is rejected (issue #946), as on the
|
|
1626
|
+
* `DatabaseDirect` repository (#943). It used to be rewritten to `"<value> (2)"`,
|
|
1627
|
+
* so the caller's write silently stored a value it never sent. The check runs
|
|
1628
|
+
* before any state is touched, so a rejected write leaves the maps unchanged.
|
|
1629
|
+
*
|
|
1630
|
+
* On the in-memory repository, `ensureUnique…` additionally takes the values that
|
|
1631
|
+
* earlier items of the same `createMany` batch have claimed: the batch is verified
|
|
1632
|
+
* in full before any of it is stored (issue #922), so the stored-value maps alone
|
|
1633
|
+
* no longer see those earlier items.
|
|
1543
1634
|
*/
|
|
1544
1635
|
function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
1545
1636
|
const fields = [];
|
|
@@ -1548,13 +1639,25 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1548
1639
|
fields.push(field);
|
|
1549
1640
|
}
|
|
1550
1641
|
}
|
|
1642
|
+
const { types, idField } = model;
|
|
1643
|
+
const isInMemory = model.repository.kind === 'InMemory';
|
|
1551
1644
|
const result = initUniqueIds();
|
|
1552
1645
|
for (const f of fields) {
|
|
1553
1646
|
const returnType = `string${f.isRequired ? '' : ' | null'}`;
|
|
1554
|
-
|
|
1647
|
+
const isId = f.kind === 'id';
|
|
1648
|
+
const claimedParam = isInMemory ? ', claimed?: Set<string>' : '';
|
|
1649
|
+
// An id is never changed by an update, so any stored item holding it is a conflict. For any
|
|
1650
|
+
// other field, the stored item holding the item's own id is the one an update replaces.
|
|
1651
|
+
const itemType = isId
|
|
1652
|
+
? `{ ${f.name}?: ${returnType} }`
|
|
1653
|
+
: `{ ${idField.name}?: ${types.id.name} | null; ${f.name}?: ${returnType} }`;
|
|
1654
|
+
const conflictCondition = isId
|
|
1655
|
+
? 'existing !== undefined'
|
|
1656
|
+
: `existing !== undefined && existing.${idField.name} !== item.${idField.name}`;
|
|
1657
|
+
result.mapDeclarations.push(`'${f.name}': new Map<string, ${types.name}>()`);
|
|
1555
1658
|
result.getByFunctions.push(`
|
|
1556
1659
|
|
|
1557
|
-
public async getBy${(0, utils_1.toPascalCase)(f.name)}(${f.name}: ${returnType}): Promise<${
|
|
1660
|
+
public async getBy${(0, utils_1.toPascalCase)(f.name)}(${f.name}: ${returnType}): Promise<${types.name} | undefined> {
|
|
1558
1661
|
${f.isRequired
|
|
1559
1662
|
? ''
|
|
1560
1663
|
: `if (${f.name} === null) {
|
|
@@ -1564,32 +1667,33 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1564
1667
|
return Promise.resolve(this.uniqueIds.${f.name}.get(${f.name})) // NOSONAR
|
|
1565
1668
|
}`);
|
|
1566
1669
|
result.clearCode.push(`this.uniqueIds.${f.name}.clear()`);
|
|
1567
|
-
result.verifyCode.push(`this.${getEnsureUniqueFnName(f)}(item)`);
|
|
1568
|
-
|
|
1670
|
+
result.verifyCode.push(`this.${getEnsureUniqueFnName(f)}(item${isInMemory ? `, claimed?.${f.name}` : ''})`);
|
|
1671
|
+
if (!isId) {
|
|
1672
|
+
result.updateCode.push(`
|
|
1569
1673
|
if (item.${f.name} !== undefined && existingItem.${f.name} !== item.${f.name}) {
|
|
1570
1674
|
this.${getEnsureUniqueFnName(f)}(item)
|
|
1571
1675
|
}`);
|
|
1676
|
+
}
|
|
1572
1677
|
result.ensureUniqueFunctions.push(`
|
|
1573
1678
|
/**
|
|
1574
|
-
*
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
}`);
|
|
1679
|
+
* Throws if another ${model.userFriendlyName} already has the given value for ${f.name}.${isInMemory
|
|
1680
|
+
? `
|
|
1681
|
+
*
|
|
1682
|
+
* @param claimed - values claimed by earlier items of the same batch, which are not stored yet`
|
|
1683
|
+
: ''}
|
|
1684
|
+
*/
|
|
1685
|
+
private ${getEnsureUniqueFnName(f)}(item: ${itemType}${claimedParam}): void {
|
|
1686
|
+
if (item.${f.name} === null || item.${f.name} === undefined) { return }
|
|
1687
|
+
const existing = this.uniqueIds.${f.name}.get(item.${f.name})
|
|
1688
|
+
if (${conflictCondition}) {
|
|
1689
|
+
throw new Error(\`Uniqueness violation on field ${f.name} of ${types.name}: another item (id=\${existing.${idField.name}}) already has the same value for ${f.name}\`)
|
|
1690
|
+
}${isInMemory
|
|
1691
|
+
? `
|
|
1692
|
+
if (claimed?.has(item.${f.name}) === true) {
|
|
1693
|
+
throw new Error('Uniqueness violation on field ${f.name} of ${types.name}: another item of the same batch already has the same value for ${f.name}')
|
|
1694
|
+
}`
|
|
1695
|
+
: ''}
|
|
1696
|
+
}`);
|
|
1593
1697
|
if (f.isRequired) {
|
|
1594
1698
|
result.setCode.push(`this.uniqueIds.${f.name}.set(item.${f.name}, item)`);
|
|
1595
1699
|
result.removeCode.push(`this.uniqueIds.${f.name}.delete(item.${f.name})`);
|
|
@@ -1598,22 +1702,34 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1598
1702
|
result.setCode.push(`if (item.${f.name} !== null) { this.uniqueIds.${f.name}.set(item.${f.name}, item) }`);
|
|
1599
1703
|
result.removeCode.push(`if (item.${f.name} !== null) { this.uniqueIds.${f.name}.delete(item.${f.name}) }`);
|
|
1600
1704
|
}
|
|
1705
|
+
if (isInMemory) {
|
|
1706
|
+
result.claimedTypeEntries.push(`${f.name}: Set<string>`);
|
|
1707
|
+
result.claimedInitEntries.push(`${f.name}: new Set<string>()`);
|
|
1708
|
+
result.claimCode.push(f.isRequired
|
|
1709
|
+
? `claimed.uniqueIds.${f.name}.add(item.${f.name})`
|
|
1710
|
+
: `if (item.${f.name} !== null) { claimed.uniqueIds.${f.name}.add(item.${f.name}) }`);
|
|
1711
|
+
}
|
|
1601
1712
|
}
|
|
1602
1713
|
if (fields.length > 1) {
|
|
1603
1714
|
result.verifyFunctionComment = `In case a value of the fields ${fields
|
|
1604
1715
|
.map((f) => f.name)
|
|
1605
|
-
.join(', ')} is
|
|
1716
|
+
.join(', ')} is already taken, an error is thrown.\n`;
|
|
1606
1717
|
}
|
|
1607
1718
|
else if (fields.length === 1) {
|
|
1608
|
-
result.verifyFunctionComment = `In case the value of the field ${fields[0].name} is
|
|
1719
|
+
result.verifyFunctionComment = `In case the value of the field ${fields[0].name} is already taken, an error is thrown.\n`;
|
|
1609
1720
|
}
|
|
1610
1721
|
return result;
|
|
1611
1722
|
}
|
|
1612
1723
|
/**
|
|
1613
1724
|
* Generates code chunks that enforce the uniqueness of a given field.
|
|
1725
|
+
*
|
|
1726
|
+
* A value that another row already holds is rejected (issue #943). It used to be
|
|
1727
|
+
* rewritten to `"<value> (2)"`, so the caller's write silently stored a value it
|
|
1728
|
+
* never sent. The check runs before the write for a readable error; the `@unique`
|
|
1729
|
+
* constraint in the database still catches a concurrent write that slips past it.
|
|
1614
1730
|
*/
|
|
1615
1731
|
function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
1616
|
-
const { types, repository } = model;
|
|
1732
|
+
const { types, repository, idField } = model;
|
|
1617
1733
|
const fields = [];
|
|
1618
1734
|
for (const field of model.fields.values()) {
|
|
1619
1735
|
if (isUniqueField(field)) {
|
|
@@ -1621,6 +1737,7 @@ function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
|
1621
1737
|
}
|
|
1622
1738
|
}
|
|
1623
1739
|
const result = initUniqueIds();
|
|
1740
|
+
const checkedFields = [];
|
|
1624
1741
|
for (const f of fields) {
|
|
1625
1742
|
const returnType = `string${f.isRequired ? '' : ' | null'}`;
|
|
1626
1743
|
result.getByFunctions.push(`
|
|
@@ -1634,38 +1751,39 @@ function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
|
1634
1751
|
}
|
|
1635
1752
|
return ${model.decoder.flattened.decoder.parseFunction.name}(result)
|
|
1636
1753
|
}`);
|
|
1754
|
+
// The primary key already rejects a taken id, and an id cannot hold "another row's" value.
|
|
1755
|
+
if (f.kind === 'id') {
|
|
1756
|
+
continue;
|
|
1757
|
+
}
|
|
1758
|
+
checkedFields.push(f);
|
|
1637
1759
|
result.verifyCode.push(`await this.${getEnsureUniqueFnName(f)}(item)`);
|
|
1638
1760
|
result.updateCode.push(`
|
|
1639
1761
|
if (item.${f.name} !== undefined && existingItem.${f.name} !== item.${f.name}) {
|
|
1640
1762
|
await this.${getEnsureUniqueFnName(f)}(item)
|
|
1641
1763
|
}`);
|
|
1764
|
+
// A row holding the item's own id is the one an update replaces, which keeping its own value does not conflict with.
|
|
1642
1765
|
result.ensureUniqueFunctions.push(`
|
|
1643
1766
|
/**
|
|
1644
|
-
*
|
|
1645
|
-
*/
|
|
1646
|
-
private async ${getEnsureUniqueFnName(f)}(item: { ${f.name}
|
|
1647
|
-
if (item.${f.name} === undefined) { return }
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
${f.name} = \`\${source${(0, utils_1.toPascalCase)(f.name)}} (\${++counter})\`
|
|
1655
|
-
}
|
|
1656
|
-
if (counter !== 1) {
|
|
1657
|
-
this.logger.log(\`${types.name} ${f.name} "\${item.${f.name}}" already exists. Renaming to "\${${f.name}}")\`)
|
|
1658
|
-
item.${f.name} = ${f.name}
|
|
1767
|
+
* Throws if another ${model.userFriendlyName} already has the given value for ${f.name}.
|
|
1768
|
+
*/
|
|
1769
|
+
private async ${getEnsureUniqueFnName(f)}(item: { ${idField.name}?: ${types.id.name} | null; ${f.name}?: ${returnType} }): Promise<void> {
|
|
1770
|
+
if (item.${f.name} === undefined || item.${f.name} === null) { return }
|
|
1771
|
+
const existing = await this.db.${repository.prismaClientName}.findUnique({
|
|
1772
|
+
where: { ${f.databaseName}: item.${f.name} },
|
|
1773
|
+
select: { ${idField.databaseName}: true },
|
|
1774
|
+
})
|
|
1775
|
+
if (existing !== null && existing.${idField.databaseName} !== item.${idField.name}) {
|
|
1776
|
+
throw new Error(\`Uniqueness violation on field ${f.name} of ${types.name}: another item (id=\${existing.${idField.databaseName}}) already has the same value for ${f.name}\`)
|
|
1659
1777
|
}
|
|
1660
1778
|
}`);
|
|
1661
1779
|
}
|
|
1662
|
-
if (
|
|
1663
|
-
result.verifyFunctionComment = `In case a value of the fields ${
|
|
1780
|
+
if (checkedFields.length > 1) {
|
|
1781
|
+
result.verifyFunctionComment = `In case a value of the fields ${checkedFields
|
|
1664
1782
|
.map((f) => f.name)
|
|
1665
|
-
.join(', ')} is
|
|
1783
|
+
.join(', ')} is already taken, an error is thrown.\n`;
|
|
1666
1784
|
}
|
|
1667
|
-
else if (
|
|
1668
|
-
result.verifyFunctionComment = `In case the value of the field ${
|
|
1785
|
+
else if (checkedFields.length === 1) {
|
|
1786
|
+
result.verifyFunctionComment = `In case the value of the field ${checkedFields[0].name} is already taken, an error is thrown.\n`;
|
|
1669
1787
|
}
|
|
1670
1788
|
return result;
|
|
1671
1789
|
}
|
|
@@ -1759,8 +1877,26 @@ function initIndexBlockOptions() {
|
|
|
1759
1877
|
getterFunctions: [],
|
|
1760
1878
|
setCode: [],
|
|
1761
1879
|
removeCode: [],
|
|
1880
|
+
assertFunction: '',
|
|
1881
|
+
claimedTypeEntries: [],
|
|
1882
|
+
claimedInitEntries: [],
|
|
1883
|
+
claimCode: [],
|
|
1762
1884
|
};
|
|
1763
1885
|
}
|
|
1886
|
+
/**
|
|
1887
|
+
* The call that checks every unique index for `item`, preceded by `comment` -
|
|
1888
|
+
* empty when the model has no unique index.
|
|
1889
|
+
*/
|
|
1890
|
+
function assertUniqueIndexesCall({ indexBlocks, item, claimed, comment = [], }) {
|
|
1891
|
+
if (indexBlocks.assertFunction === '') {
|
|
1892
|
+
return '';
|
|
1893
|
+
}
|
|
1894
|
+
return [
|
|
1895
|
+
...comment.map((line) => `// ${line}`),
|
|
1896
|
+
`this.${ASSERT_UNIQUE_INDEXES_FN}(${item}${claimed ? `, ${claimed}` : ''})`,
|
|
1897
|
+
].join('\n');
|
|
1898
|
+
}
|
|
1899
|
+
const ASSERT_UNIQUE_INDEXES_FN = 'assertUniqueIndexes';
|
|
1764
1900
|
function generateIndexBlocks_Database({ model, context, imports, }) {
|
|
1765
1901
|
const { types, repository } = model;
|
|
1766
1902
|
const result = initIndexBlockOptions();
|
|
@@ -1797,6 +1933,16 @@ function generateIndexBlocks_Database({ model, context, imports, }) {
|
|
|
1797
1933
|
}
|
|
1798
1934
|
return result;
|
|
1799
1935
|
}
|
|
1936
|
+
/**
|
|
1937
|
+
* Generates the in-memory lookup maps for the model's unique indexes, and the
|
|
1938
|
+
* checks that enforce them.
|
|
1939
|
+
*
|
|
1940
|
+
* The checks live in `assertUniqueIndexes`, separate from `set()`, so that they
|
|
1941
|
+
* run before any state is touched (issue #922): `set()` calls it first, and
|
|
1942
|
+
* `update()` calls it before `remove()`-ing the row it replaces. Checking inside
|
|
1943
|
+
* the write instead left a half-stored row behind on a violation, or - on update -
|
|
1944
|
+
* a row that had already been removed.
|
|
1945
|
+
*/
|
|
1800
1946
|
function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
1801
1947
|
const result = initIndexBlockOptions();
|
|
1802
1948
|
// Only unique indexes get an in-memory lookup map and uniqueness enforcement;
|
|
@@ -1806,6 +1952,7 @@ function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
|
1806
1952
|
return result;
|
|
1807
1953
|
}
|
|
1808
1954
|
const isInMemory = model.repository.kind === 'InMemory';
|
|
1955
|
+
const assertCode = [];
|
|
1809
1956
|
for (const index of indexes) {
|
|
1810
1957
|
const i = getIndexDefinition({ index, model });
|
|
1811
1958
|
registerIndexFieldTypeImports({ fields: i.fields, context, imports });
|
|
@@ -1832,16 +1979,34 @@ function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
|
1832
1979
|
await this.mutex.waitForUnlock()
|
|
1833
1980
|
return Promise.resolve(this.${i.name}.get(this.${keyFnName}(${keyArgFromFields})) ?? null) // NOSONAR
|
|
1834
1981
|
}`);
|
|
1835
|
-
|
|
1982
|
+
// A stored entry holding the item's own id is the row an update replaces,
|
|
1983
|
+
// which keeping its own values does not conflict with.
|
|
1984
|
+
assertCode.push(`{
|
|
1836
1985
|
const ${i.name}Key = this.${keyFnName}(item)
|
|
1837
|
-
const ${existingVar} = this.${i.name}.get(${i.name}Key)
|
|
1838
|
-
|
|
1986
|
+
const ${existingVar} = [this.${i.name}.get(${i.name}Key), claimed?.${i.name}.get(${i.name}Key)].find(
|
|
1987
|
+
(existing) => existing !== undefined && existing.id !== item.id,
|
|
1988
|
+
)
|
|
1989
|
+
if (${existingVar}) {
|
|
1839
1990
|
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}]\`)
|
|
1840
1991
|
}
|
|
1841
|
-
this.${i.name}.set(${i.name}Key, item)
|
|
1842
1992
|
}`);
|
|
1993
|
+
result.setCode.push(`this.${i.name}.set(this.${keyFnName}(item), item)`);
|
|
1843
1994
|
result.removeCode.push(`this.${i.name}.delete(this.${keyFnName}(item))`);
|
|
1995
|
+
result.claimedTypeEntries.push(`${i.name}: Map<string, ${model.types.name}>`);
|
|
1996
|
+
result.claimedInitEntries.push(`${i.name}: new Map<string, ${model.types.name}>()`);
|
|
1997
|
+
result.claimCode.push(`claimed.indexes.${i.name}.set(this.${keyFnName}(item), item)`);
|
|
1844
1998
|
}
|
|
1999
|
+
result.assertFunction = `${Generator.toJsDocComment([
|
|
2000
|
+
`Throws if storing the given ${model.userFriendlyName} would violate one of its unique indexes.`,
|
|
2001
|
+
'',
|
|
2002
|
+
'Every mutation calls this before it touches any in-memory state, so a',
|
|
2003
|
+
'rejected write leaves the in-memory data and indexes exactly as they were.',
|
|
2004
|
+
'',
|
|
2005
|
+
'@param claimed - index keys claimed by earlier items of the same batch, which are not stored yet',
|
|
2006
|
+
])}
|
|
2007
|
+
private ${ASSERT_UNIQUE_INDEXES_FN}(item: ${model.types.name}, claimed?: { ${result.claimedTypeEntries.join('; ')} }): void {
|
|
2008
|
+
${assertCode.join('\n')}
|
|
2009
|
+
}`;
|
|
1845
2010
|
return result;
|
|
1846
2011
|
}
|
|
1847
2012
|
function getIndexDefinition({ index, model, }) {
|
|
@@ -1995,7 +2160,9 @@ function updateJsDoc(model) {
|
|
|
1995
2160
|
* Generates `updateMany` / `upsertMany`, whose bodies differ only in which
|
|
1996
2161
|
* single-item method they drive.
|
|
1997
2162
|
*
|
|
1998
|
-
* A per-item failure is skipped so one bad row does not abort the batch
|
|
2163
|
+
* A per-item failure is skipped so one bad row does not abort the batch - with a
|
|
2164
|
+
* warning, since a skipped item is otherwise invisible: since #946 that includes
|
|
2165
|
+
* a taken `isUnique` value, which used to be renamed and stored. A
|
|
1999
2166
|
* `RowConflictError` is rethrown: the caller only ever sees a shorter result
|
|
2000
2167
|
* array, which cannot distinguish "that row was not in the batch" from "your
|
|
2001
2168
|
* write lost a race and did not commit" - the one signal compare-and-set
|
|
@@ -2009,8 +2176,9 @@ function generateBatchMutation(model, context, mutation) {
|
|
|
2009
2176
|
return `${Generator.toJsDocComment([
|
|
2010
2177
|
summary,
|
|
2011
2178
|
'',
|
|
2012
|
-
'Per-item failures are skipped
|
|
2013
|
-
'rethrown so a lost compare-and-set can never
|
|
2179
|
+
'Per-item failures are skipped and logged as a warning, except a',
|
|
2180
|
+
'`RowConflictError`, which is rethrown so a lost compare-and-set can never',
|
|
2181
|
+
'be mistaken for success.',
|
|
2014
2182
|
])}
|
|
2015
2183
|
public async ${mutation}Many(
|
|
2016
2184
|
{ items, execution }: { items: ${dto.name}[], execution: ${context.actions.execution.interface.name} }
|
|
@@ -2024,6 +2192,7 @@ function generateBatchMutation(model, context, mutation) {
|
|
|
2024
2192
|
if (${context.repositories.rowConflict.isRowConflictError}(error)) {
|
|
2025
2193
|
throw error
|
|
2026
2194
|
}
|
|
2195
|
+
this.logger.warn(\`${mutation}Many skipped ${model.types.name} \${item.${model.idField.name} ?? '(new)'}: \${error instanceof Error ? error.message : String(error)}\`)
|
|
2027
2196
|
}
|
|
2028
2197
|
}
|
|
2029
2198
|
return result
|
|
@@ -2252,7 +2421,9 @@ function generateGetByKeyMethod_Database({ model }) {
|
|
|
2252
2421
|
*/
|
|
2253
2422
|
public async getByKey(key: string): Promise<${model.types.name} | null> {
|
|
2254
2423
|
// TODO: Implement proper scoped lookup. See method documentation for details.
|
|
2255
|
-
|
|
2424
|
+
await this.mutex.waitForUnlock()
|
|
2425
|
+
const result = await this.db.${model.repository.prismaClientName}.findFirst({ where: { ${keyFieldDatabaseName}: key } })
|
|
2426
|
+
return result ? ${model.decoder.flattened.decoder.parseFunction.name}(result) : null
|
|
2256
2427
|
}`;
|
|
2257
2428
|
}
|
|
2258
2429
|
/**
|