@postxl/generators 6.0.0 → 6.1.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-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-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-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 +236 -71
- 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/generators/claudemd.generator.js +1 -0
- package/dist/base/generators/claudemd.generator.js.map +1 -1
- 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/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/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 +42 -54
- package/dist/frontend-admin/generators/model-admin-page.generator.js.map +1 -1
- package/dist/frontend-core/frontend.generator.js +10 -0
- package/dist/frontend-core/frontend.generator.js.map +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-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 +5 -5
|
@@ -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} {
|
|
@@ -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
|
|
|
@@ -687,14 +711,13 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
687
711
|
)
|
|
688
712
|
|
|
689
713
|
${hasSetFunction ? 'this.set(newItem)' : ''}
|
|
690
|
-
${skipIf(skipExecutionLogging, `await execution.${context.actions.execution.mutations.create.finish}({ actionOperationId, createdObject: newItem, entityId: newItem.id })`)}
|
|
691
|
-
|
|
692
714
|
release()
|
|
693
715
|
|
|
716
|
+
${skipIf(skipExecutionLogging, `await execution.${context.actions.execution.mutations.create.finish}({ actionOperationId, createdObject: newItem, entityId: newItem.id })`)}
|
|
694
717
|
return newItem
|
|
695
718
|
} catch (error) {
|
|
696
|
-
${skipIf(skipExecutionLogging, `await execution.${context.actions.execution.errorOperation}({ actionOperationId, error })`)}
|
|
697
719
|
release()
|
|
720
|
+
${skipIf(skipExecutionLogging, `await execution.${context.actions.execution.errorOperation}({ actionOperationId, error })`)}
|
|
698
721
|
throw error
|
|
699
722
|
}
|
|
700
723
|
}
|
|
@@ -911,6 +934,22 @@ const generateRepository_InMemory = (model, context) => {
|
|
|
911
934
|
const indexBlocks = generateIndexBlocks_Cached(params);
|
|
912
935
|
const relationsBlocks = generateRelationsBlocks_Cached(params);
|
|
913
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
|
+
: '';
|
|
914
953
|
const idField = model.idField;
|
|
915
954
|
return `
|
|
916
955
|
import { Injectable, Logger } from '@nestjs/common'
|
|
@@ -1011,9 +1050,9 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
1011
1050
|
`In case none exists, ${idBlocks.verifyFunctionComment}`,
|
|
1012
1051
|
uniqueStringFieldsBlocks.verifyFunctionComment,
|
|
1013
1052
|
maxLengthBlocks.verifyFunctionComment,
|
|
1014
|
-
])}
|
|
1053
|
+
].filter((line) => line !== ''))}
|
|
1015
1054
|
private verifyItem(
|
|
1016
|
-
item: ${idBlocks.verifyFunctionParameterType}
|
|
1055
|
+
item: ${idBlocks.verifyFunctionParameterType}${claimedUniqueIdsParam}
|
|
1017
1056
|
): ${idBlocks.createFunctionParameterType} {
|
|
1018
1057
|
${idBlocks.verifyCode}
|
|
1019
1058
|
|
|
@@ -1041,19 +1080,37 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
1041
1080
|
}
|
|
1042
1081
|
}
|
|
1043
1082
|
|
|
1044
|
-
${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
|
+
])}
|
|
1045
1090
|
public async createMany(
|
|
1046
1091
|
{items}: { items: ${model.types.dto.create.name}[], execution: ${context.actions.execution.interface.name} }
|
|
1047
1092
|
): Promise<${model.types.name}[]> {
|
|
1048
1093
|
const result: ${model.types.name}[] = []
|
|
1049
1094
|
const release = await this.mutex.acquire()
|
|
1050
1095
|
try {
|
|
1096
|
+
${createManyClaimedDeclaration}
|
|
1051
1097
|
for (const item of items) {
|
|
1052
|
-
this.verifyItem(item)
|
|
1053
|
-
|
|
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}`}
|
|
1054
1107
|
result.push(item)
|
|
1055
1108
|
}
|
|
1056
1109
|
|
|
1110
|
+
for (const item of result) {
|
|
1111
|
+
this.set(item)
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1057
1114
|
release()
|
|
1058
1115
|
return Promise.resolve(result) // NOSONAR - keep all validations async to adhere to the same interface
|
|
1059
1116
|
} catch (error) {
|
|
@@ -1099,6 +1156,14 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
1099
1156
|
) as Partial<${model.types.dto.update.name}>
|
|
1100
1157
|
const newItem = { ...existingItem, ...definedUpdates }
|
|
1101
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
|
+
})}
|
|
1102
1167
|
this.remove(existingItem)
|
|
1103
1168
|
this.set(newItem)
|
|
1104
1169
|
|
|
@@ -1189,10 +1254,14 @@ export class ${repository.name} implements Repository<${model.types.name}, ${idF
|
|
|
1189
1254
|
|
|
1190
1255
|
${uniqueStringFieldsBlocks.ensureUniqueFunctions.join('\n\n')}
|
|
1191
1256
|
|
|
1257
|
+
${indexBlocks.assertFunction}
|
|
1258
|
+
|
|
1192
1259
|
/**
|
|
1193
1260
|
* Function that adds/updates a given item to the internal data store, indexes, etc.
|
|
1194
1261
|
*/
|
|
1195
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
|
+
|
|
1196
1265
|
${idBlocks.setCode}
|
|
1197
1266
|
|
|
1198
1267
|
this.data.set(item.id, item)
|
|
@@ -1296,7 +1365,7 @@ function generateUserRepositorySpecificBlocks_InMemory({ model, context, imports
|
|
|
1296
1365
|
/**
|
|
1297
1366
|
* The literal the root user is seeded from.
|
|
1298
1367
|
*
|
|
1299
|
-
* 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
|
|
1300
1369
|
* on the database path the seed row gets it whether or not it is in the payload.
|
|
1301
1370
|
* The in-memory path has no column to fall back on - it stores this literal as
|
|
1302
1371
|
* the row - so a non-nullable field with a default that `systemUser` does not
|
|
@@ -1310,6 +1379,9 @@ function generateSharedRootUserBlocks({ model, context }) {
|
|
|
1310
1379
|
if (field.kind === 'scalar' && field.defaultValue !== undefined && !field.isCreatedAt && !field.isUpdatedAt) {
|
|
1311
1380
|
declaredDefaults[field.name] = field.defaultValue;
|
|
1312
1381
|
}
|
|
1382
|
+
if (field.kind === 'enum' && field.defaultValue !== undefined) {
|
|
1383
|
+
declaredDefaults[field.name] = field.defaultValue;
|
|
1384
|
+
}
|
|
1313
1385
|
}
|
|
1314
1386
|
return JSON.stringify({ ...declaredDefaults, ...context.schema.systemUser });
|
|
1315
1387
|
}
|
|
@@ -1537,10 +1609,23 @@ function initUniqueIds() {
|
|
|
1537
1609
|
ensureUniqueFunctions: [],
|
|
1538
1610
|
setCode: [],
|
|
1539
1611
|
removeCode: [],
|
|
1612
|
+
claimedTypeEntries: [],
|
|
1613
|
+
claimedInitEntries: [],
|
|
1614
|
+
claimCode: [],
|
|
1540
1615
|
};
|
|
1541
1616
|
}
|
|
1542
1617
|
/**
|
|
1543
1618
|
* Generates code chunks that enforce the uniqueness of a given field.
|
|
1619
|
+
*
|
|
1620
|
+
* A value that another item already holds is rejected (issue #946), as on the
|
|
1621
|
+
* `DatabaseDirect` repository (#943). It used to be rewritten to `"<value> (2)"`,
|
|
1622
|
+
* so the caller's write silently stored a value it never sent. The check runs
|
|
1623
|
+
* before any state is touched, so a rejected write leaves the maps unchanged.
|
|
1624
|
+
*
|
|
1625
|
+
* On the in-memory repository, `ensureUnique…` additionally takes the values that
|
|
1626
|
+
* earlier items of the same `createMany` batch have claimed: the batch is verified
|
|
1627
|
+
* in full before any of it is stored (issue #922), so the stored-value maps alone
|
|
1628
|
+
* no longer see those earlier items.
|
|
1544
1629
|
*/
|
|
1545
1630
|
function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
1546
1631
|
const fields = [];
|
|
@@ -1549,13 +1634,25 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1549
1634
|
fields.push(field);
|
|
1550
1635
|
}
|
|
1551
1636
|
}
|
|
1637
|
+
const { types, idField } = model;
|
|
1638
|
+
const isInMemory = model.repository.kind === 'InMemory';
|
|
1552
1639
|
const result = initUniqueIds();
|
|
1553
1640
|
for (const f of fields) {
|
|
1554
1641
|
const returnType = `string${f.isRequired ? '' : ' | null'}`;
|
|
1555
|
-
|
|
1642
|
+
const isId = f.kind === 'id';
|
|
1643
|
+
const claimedParam = isInMemory ? ', claimed?: Set<string>' : '';
|
|
1644
|
+
// An id is never changed by an update, so any stored item holding it is a conflict. For any
|
|
1645
|
+
// other field, the stored item holding the item's own id is the one an update replaces.
|
|
1646
|
+
const itemType = isId
|
|
1647
|
+
? `{ ${f.name}?: ${returnType} }`
|
|
1648
|
+
: `{ ${idField.name}?: ${types.id.name} | null; ${f.name}?: ${returnType} }`;
|
|
1649
|
+
const conflictCondition = isId
|
|
1650
|
+
? 'existing !== undefined'
|
|
1651
|
+
: `existing !== undefined && existing.${idField.name} !== item.${idField.name}`;
|
|
1652
|
+
result.mapDeclarations.push(`'${f.name}': new Map<string, ${types.name}>()`);
|
|
1556
1653
|
result.getByFunctions.push(`
|
|
1557
1654
|
|
|
1558
|
-
public async getBy${(0, utils_1.toPascalCase)(f.name)}(${f.name}: ${returnType}): Promise<${
|
|
1655
|
+
public async getBy${(0, utils_1.toPascalCase)(f.name)}(${f.name}: ${returnType}): Promise<${types.name} | undefined> {
|
|
1559
1656
|
${f.isRequired
|
|
1560
1657
|
? ''
|
|
1561
1658
|
: `if (${f.name} === null) {
|
|
@@ -1565,32 +1662,33 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1565
1662
|
return Promise.resolve(this.uniqueIds.${f.name}.get(${f.name})) // NOSONAR
|
|
1566
1663
|
}`);
|
|
1567
1664
|
result.clearCode.push(`this.uniqueIds.${f.name}.clear()`);
|
|
1568
|
-
result.verifyCode.push(`this.${getEnsureUniqueFnName(f)}(item)`);
|
|
1569
|
-
|
|
1665
|
+
result.verifyCode.push(`this.${getEnsureUniqueFnName(f)}(item${isInMemory ? `, claimed?.${f.name}` : ''})`);
|
|
1666
|
+
if (!isId) {
|
|
1667
|
+
result.updateCode.push(`
|
|
1570
1668
|
if (item.${f.name} !== undefined && existingItem.${f.name} !== item.${f.name}) {
|
|
1571
1669
|
this.${getEnsureUniqueFnName(f)}(item)
|
|
1572
1670
|
}`);
|
|
1671
|
+
}
|
|
1573
1672
|
result.ensureUniqueFunctions.push(`
|
|
1574
1673
|
/**
|
|
1575
|
-
*
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
}`);
|
|
1674
|
+
* Throws if another ${model.userFriendlyName} already has the given value for ${f.name}.${isInMemory
|
|
1675
|
+
? `
|
|
1676
|
+
*
|
|
1677
|
+
* @param claimed - values claimed by earlier items of the same batch, which are not stored yet`
|
|
1678
|
+
: ''}
|
|
1679
|
+
*/
|
|
1680
|
+
private ${getEnsureUniqueFnName(f)}(item: ${itemType}${claimedParam}): void {
|
|
1681
|
+
if (item.${f.name} === null || item.${f.name} === undefined) { return }
|
|
1682
|
+
const existing = this.uniqueIds.${f.name}.get(item.${f.name})
|
|
1683
|
+
if (${conflictCondition}) {
|
|
1684
|
+
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}\`)
|
|
1685
|
+
}${isInMemory
|
|
1686
|
+
? `
|
|
1687
|
+
if (claimed?.has(item.${f.name}) === true) {
|
|
1688
|
+
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}')
|
|
1689
|
+
}`
|
|
1690
|
+
: ''}
|
|
1691
|
+
}`);
|
|
1594
1692
|
if (f.isRequired) {
|
|
1595
1693
|
result.setCode.push(`this.uniqueIds.${f.name}.set(item.${f.name}, item)`);
|
|
1596
1694
|
result.removeCode.push(`this.uniqueIds.${f.name}.delete(item.${f.name})`);
|
|
@@ -1599,22 +1697,34 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1599
1697
|
result.setCode.push(`if (item.${f.name} !== null) { this.uniqueIds.${f.name}.set(item.${f.name}, item) }`);
|
|
1600
1698
|
result.removeCode.push(`if (item.${f.name} !== null) { this.uniqueIds.${f.name}.delete(item.${f.name}) }`);
|
|
1601
1699
|
}
|
|
1700
|
+
if (isInMemory) {
|
|
1701
|
+
result.claimedTypeEntries.push(`${f.name}: Set<string>`);
|
|
1702
|
+
result.claimedInitEntries.push(`${f.name}: new Set<string>()`);
|
|
1703
|
+
result.claimCode.push(f.isRequired
|
|
1704
|
+
? `claimed.uniqueIds.${f.name}.add(item.${f.name})`
|
|
1705
|
+
: `if (item.${f.name} !== null) { claimed.uniqueIds.${f.name}.add(item.${f.name}) }`);
|
|
1706
|
+
}
|
|
1602
1707
|
}
|
|
1603
1708
|
if (fields.length > 1) {
|
|
1604
1709
|
result.verifyFunctionComment = `In case a value of the fields ${fields
|
|
1605
1710
|
.map((f) => f.name)
|
|
1606
|
-
.join(', ')} is
|
|
1711
|
+
.join(', ')} is already taken, an error is thrown.\n`;
|
|
1607
1712
|
}
|
|
1608
1713
|
else if (fields.length === 1) {
|
|
1609
|
-
result.verifyFunctionComment = `In case the value of the field ${fields[0].name} is
|
|
1714
|
+
result.verifyFunctionComment = `In case the value of the field ${fields[0].name} is already taken, an error is thrown.\n`;
|
|
1610
1715
|
}
|
|
1611
1716
|
return result;
|
|
1612
1717
|
}
|
|
1613
1718
|
/**
|
|
1614
1719
|
* Generates code chunks that enforce the uniqueness of a given field.
|
|
1720
|
+
*
|
|
1721
|
+
* A value that another row already holds is rejected (issue #943). It used to be
|
|
1722
|
+
* rewritten to `"<value> (2)"`, so the caller's write silently stored a value it
|
|
1723
|
+
* never sent. The check runs before the write for a readable error; the `@unique`
|
|
1724
|
+
* constraint in the database still catches a concurrent write that slips past it.
|
|
1615
1725
|
*/
|
|
1616
1726
|
function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
1617
|
-
const { types, repository } = model;
|
|
1727
|
+
const { types, repository, idField } = model;
|
|
1618
1728
|
const fields = [];
|
|
1619
1729
|
for (const field of model.fields.values()) {
|
|
1620
1730
|
if (isUniqueField(field)) {
|
|
@@ -1622,6 +1732,7 @@ function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
|
1622
1732
|
}
|
|
1623
1733
|
}
|
|
1624
1734
|
const result = initUniqueIds();
|
|
1735
|
+
const checkedFields = [];
|
|
1625
1736
|
for (const f of fields) {
|
|
1626
1737
|
const returnType = `string${f.isRequired ? '' : ' | null'}`;
|
|
1627
1738
|
result.getByFunctions.push(`
|
|
@@ -1635,38 +1746,39 @@ function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
|
1635
1746
|
}
|
|
1636
1747
|
return ${model.decoder.flattened.decoder.parseFunction.name}(result)
|
|
1637
1748
|
}`);
|
|
1749
|
+
// The primary key already rejects a taken id, and an id cannot hold "another row's" value.
|
|
1750
|
+
if (f.kind === 'id') {
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
checkedFields.push(f);
|
|
1638
1754
|
result.verifyCode.push(`await this.${getEnsureUniqueFnName(f)}(item)`);
|
|
1639
1755
|
result.updateCode.push(`
|
|
1640
1756
|
if (item.${f.name} !== undefined && existingItem.${f.name} !== item.${f.name}) {
|
|
1641
1757
|
await this.${getEnsureUniqueFnName(f)}(item)
|
|
1642
1758
|
}`);
|
|
1759
|
+
// A row holding the item's own id is the one an update replaces, which keeping its own value does not conflict with.
|
|
1643
1760
|
result.ensureUniqueFunctions.push(`
|
|
1644
1761
|
/**
|
|
1645
|
-
*
|
|
1646
|
-
*/
|
|
1647
|
-
private async ${getEnsureUniqueFnName(f)}(item: { ${f.name}
|
|
1648
|
-
if (item.${f.name} === undefined) { return }
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
${f.name} = \`\${source${(0, utils_1.toPascalCase)(f.name)}} (\${++counter})\`
|
|
1656
|
-
}
|
|
1657
|
-
if (counter !== 1) {
|
|
1658
|
-
this.logger.log(\`${types.name} ${f.name} "\${item.${f.name}}" already exists. Renaming to "\${${f.name}}")\`)
|
|
1659
|
-
item.${f.name} = ${f.name}
|
|
1762
|
+
* Throws if another ${model.userFriendlyName} already has the given value for ${f.name}.
|
|
1763
|
+
*/
|
|
1764
|
+
private async ${getEnsureUniqueFnName(f)}(item: { ${idField.name}?: ${types.id.name} | null; ${f.name}?: ${returnType} }): Promise<void> {
|
|
1765
|
+
if (item.${f.name} === undefined || item.${f.name} === null) { return }
|
|
1766
|
+
const existing = await this.db.${repository.prismaClientName}.findUnique({
|
|
1767
|
+
where: { ${f.databaseName}: item.${f.name} },
|
|
1768
|
+
select: { ${idField.databaseName}: true },
|
|
1769
|
+
})
|
|
1770
|
+
if (existing !== null && existing.${idField.databaseName} !== item.${idField.name}) {
|
|
1771
|
+
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}\`)
|
|
1660
1772
|
}
|
|
1661
1773
|
}`);
|
|
1662
1774
|
}
|
|
1663
|
-
if (
|
|
1664
|
-
result.verifyFunctionComment = `In case a value of the fields ${
|
|
1775
|
+
if (checkedFields.length > 1) {
|
|
1776
|
+
result.verifyFunctionComment = `In case a value of the fields ${checkedFields
|
|
1665
1777
|
.map((f) => f.name)
|
|
1666
|
-
.join(', ')} is
|
|
1778
|
+
.join(', ')} is already taken, an error is thrown.\n`;
|
|
1667
1779
|
}
|
|
1668
|
-
else if (
|
|
1669
|
-
result.verifyFunctionComment = `In case the value of the field ${
|
|
1780
|
+
else if (checkedFields.length === 1) {
|
|
1781
|
+
result.verifyFunctionComment = `In case the value of the field ${checkedFields[0].name} is already taken, an error is thrown.\n`;
|
|
1670
1782
|
}
|
|
1671
1783
|
return result;
|
|
1672
1784
|
}
|
|
@@ -1760,8 +1872,26 @@ function initIndexBlockOptions() {
|
|
|
1760
1872
|
getterFunctions: [],
|
|
1761
1873
|
setCode: [],
|
|
1762
1874
|
removeCode: [],
|
|
1875
|
+
assertFunction: '',
|
|
1876
|
+
claimedTypeEntries: [],
|
|
1877
|
+
claimedInitEntries: [],
|
|
1878
|
+
claimCode: [],
|
|
1763
1879
|
};
|
|
1764
1880
|
}
|
|
1881
|
+
/**
|
|
1882
|
+
* The call that checks every unique index for `item`, preceded by `comment` -
|
|
1883
|
+
* empty when the model has no unique index.
|
|
1884
|
+
*/
|
|
1885
|
+
function assertUniqueIndexesCall({ indexBlocks, item, claimed, comment = [], }) {
|
|
1886
|
+
if (indexBlocks.assertFunction === '') {
|
|
1887
|
+
return '';
|
|
1888
|
+
}
|
|
1889
|
+
return [
|
|
1890
|
+
...comment.map((line) => `// ${line}`),
|
|
1891
|
+
`this.${ASSERT_UNIQUE_INDEXES_FN}(${item}${claimed ? `, ${claimed}` : ''})`,
|
|
1892
|
+
].join('\n');
|
|
1893
|
+
}
|
|
1894
|
+
const ASSERT_UNIQUE_INDEXES_FN = 'assertUniqueIndexes';
|
|
1765
1895
|
function generateIndexBlocks_Database({ model, context, imports, }) {
|
|
1766
1896
|
const { types, repository } = model;
|
|
1767
1897
|
const result = initIndexBlockOptions();
|
|
@@ -1798,6 +1928,16 @@ function generateIndexBlocks_Database({ model, context, imports, }) {
|
|
|
1798
1928
|
}
|
|
1799
1929
|
return result;
|
|
1800
1930
|
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Generates the in-memory lookup maps for the model's unique indexes, and the
|
|
1933
|
+
* checks that enforce them.
|
|
1934
|
+
*
|
|
1935
|
+
* The checks live in `assertUniqueIndexes`, separate from `set()`, so that they
|
|
1936
|
+
* run before any state is touched (issue #922): `set()` calls it first, and
|
|
1937
|
+
* `update()` calls it before `remove()`-ing the row it replaces. Checking inside
|
|
1938
|
+
* the write instead left a half-stored row behind on a violation, or - on update -
|
|
1939
|
+
* a row that had already been removed.
|
|
1940
|
+
*/
|
|
1801
1941
|
function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
1802
1942
|
const result = initIndexBlockOptions();
|
|
1803
1943
|
// Only unique indexes get an in-memory lookup map and uniqueness enforcement;
|
|
@@ -1807,6 +1947,7 @@ function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
|
1807
1947
|
return result;
|
|
1808
1948
|
}
|
|
1809
1949
|
const isInMemory = model.repository.kind === 'InMemory';
|
|
1950
|
+
const assertCode = [];
|
|
1810
1951
|
for (const index of indexes) {
|
|
1811
1952
|
const i = getIndexDefinition({ index, model });
|
|
1812
1953
|
registerIndexFieldTypeImports({ fields: i.fields, context, imports });
|
|
@@ -1833,16 +1974,34 @@ function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
|
1833
1974
|
await this.mutex.waitForUnlock()
|
|
1834
1975
|
return Promise.resolve(this.${i.name}.get(this.${keyFnName}(${keyArgFromFields})) ?? null) // NOSONAR
|
|
1835
1976
|
}`);
|
|
1836
|
-
|
|
1977
|
+
// A stored entry holding the item's own id is the row an update replaces,
|
|
1978
|
+
// which keeping its own values does not conflict with.
|
|
1979
|
+
assertCode.push(`{
|
|
1837
1980
|
const ${i.name}Key = this.${keyFnName}(item)
|
|
1838
|
-
const ${existingVar} = this.${i.name}.get(${i.name}Key)
|
|
1839
|
-
|
|
1981
|
+
const ${existingVar} = [this.${i.name}.get(${i.name}Key), claimed?.${i.name}.get(${i.name}Key)].find(
|
|
1982
|
+
(existing) => existing !== undefined && existing.id !== item.id,
|
|
1983
|
+
)
|
|
1984
|
+
if (${existingVar}) {
|
|
1840
1985
|
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}]\`)
|
|
1841
1986
|
}
|
|
1842
|
-
this.${i.name}.set(${i.name}Key, item)
|
|
1843
1987
|
}`);
|
|
1988
|
+
result.setCode.push(`this.${i.name}.set(this.${keyFnName}(item), item)`);
|
|
1844
1989
|
result.removeCode.push(`this.${i.name}.delete(this.${keyFnName}(item))`);
|
|
1990
|
+
result.claimedTypeEntries.push(`${i.name}: Map<string, ${model.types.name}>`);
|
|
1991
|
+
result.claimedInitEntries.push(`${i.name}: new Map<string, ${model.types.name}>()`);
|
|
1992
|
+
result.claimCode.push(`claimed.indexes.${i.name}.set(this.${keyFnName}(item), item)`);
|
|
1845
1993
|
}
|
|
1994
|
+
result.assertFunction = `${Generator.toJsDocComment([
|
|
1995
|
+
`Throws if storing the given ${model.userFriendlyName} would violate one of its unique indexes.`,
|
|
1996
|
+
'',
|
|
1997
|
+
'Every mutation calls this before it touches any in-memory state, so a',
|
|
1998
|
+
'rejected write leaves the in-memory data and indexes exactly as they were.',
|
|
1999
|
+
'',
|
|
2000
|
+
'@param claimed - index keys claimed by earlier items of the same batch, which are not stored yet',
|
|
2001
|
+
])}
|
|
2002
|
+
private ${ASSERT_UNIQUE_INDEXES_FN}(item: ${model.types.name}, claimed?: { ${result.claimedTypeEntries.join('; ')} }): void {
|
|
2003
|
+
${assertCode.join('\n')}
|
|
2004
|
+
}`;
|
|
1846
2005
|
return result;
|
|
1847
2006
|
}
|
|
1848
2007
|
function getIndexDefinition({ index, model, }) {
|
|
@@ -1996,7 +2155,9 @@ function updateJsDoc(model) {
|
|
|
1996
2155
|
* Generates `updateMany` / `upsertMany`, whose bodies differ only in which
|
|
1997
2156
|
* single-item method they drive.
|
|
1998
2157
|
*
|
|
1999
|
-
* A per-item failure is skipped so one bad row does not abort the batch
|
|
2158
|
+
* A per-item failure is skipped so one bad row does not abort the batch - with a
|
|
2159
|
+
* warning, since a skipped item is otherwise invisible: since #946 that includes
|
|
2160
|
+
* a taken `isUnique` value, which used to be renamed and stored. A
|
|
2000
2161
|
* `RowConflictError` is rethrown: the caller only ever sees a shorter result
|
|
2001
2162
|
* array, which cannot distinguish "that row was not in the batch" from "your
|
|
2002
2163
|
* write lost a race and did not commit" - the one signal compare-and-set
|
|
@@ -2010,8 +2171,9 @@ function generateBatchMutation(model, context, mutation) {
|
|
|
2010
2171
|
return `${Generator.toJsDocComment([
|
|
2011
2172
|
summary,
|
|
2012
2173
|
'',
|
|
2013
|
-
'Per-item failures are skipped
|
|
2014
|
-
'rethrown so a lost compare-and-set can never
|
|
2174
|
+
'Per-item failures are skipped and logged as a warning, except a',
|
|
2175
|
+
'`RowConflictError`, which is rethrown so a lost compare-and-set can never',
|
|
2176
|
+
'be mistaken for success.',
|
|
2015
2177
|
])}
|
|
2016
2178
|
public async ${mutation}Many(
|
|
2017
2179
|
{ items, execution }: { items: ${dto.name}[], execution: ${context.actions.execution.interface.name} }
|
|
@@ -2025,6 +2187,7 @@ function generateBatchMutation(model, context, mutation) {
|
|
|
2025
2187
|
if (${context.repositories.rowConflict.isRowConflictError}(error)) {
|
|
2026
2188
|
throw error
|
|
2027
2189
|
}
|
|
2190
|
+
this.logger.warn(\`${mutation}Many skipped ${model.types.name} \${item.${model.idField.name} ?? '(new)'}: \${error instanceof Error ? error.message : String(error)}\`)
|
|
2028
2191
|
}
|
|
2029
2192
|
}
|
|
2030
2193
|
return result
|
|
@@ -2253,7 +2416,9 @@ function generateGetByKeyMethod_Database({ model }) {
|
|
|
2253
2416
|
*/
|
|
2254
2417
|
public async getByKey(key: string): Promise<${model.types.name} | null> {
|
|
2255
2418
|
// TODO: Implement proper scoped lookup. See method documentation for details.
|
|
2256
|
-
|
|
2419
|
+
await this.mutex.waitForUnlock()
|
|
2420
|
+
const result = await this.db.${model.repository.prismaClientName}.findFirst({ where: { ${keyFieldDatabaseName}: key } })
|
|
2421
|
+
return result ? ${model.decoder.flattened.decoder.parseFunction.name}(result) : null
|
|
2257
2422
|
}`;
|
|
2258
2423
|
}
|
|
2259
2424
|
/**
|