@postxl/generators 6.0.1 → 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 +234 -68
- 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
|
|
|
@@ -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
|
}
|
|
@@ -1536,10 +1609,23 @@ function initUniqueIds() {
|
|
|
1536
1609
|
ensureUniqueFunctions: [],
|
|
1537
1610
|
setCode: [],
|
|
1538
1611
|
removeCode: [],
|
|
1612
|
+
claimedTypeEntries: [],
|
|
1613
|
+
claimedInitEntries: [],
|
|
1614
|
+
claimCode: [],
|
|
1539
1615
|
};
|
|
1540
1616
|
}
|
|
1541
1617
|
/**
|
|
1542
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.
|
|
1543
1629
|
*/
|
|
1544
1630
|
function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
1545
1631
|
const fields = [];
|
|
@@ -1548,13 +1634,25 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1548
1634
|
fields.push(field);
|
|
1549
1635
|
}
|
|
1550
1636
|
}
|
|
1637
|
+
const { types, idField } = model;
|
|
1638
|
+
const isInMemory = model.repository.kind === 'InMemory';
|
|
1551
1639
|
const result = initUniqueIds();
|
|
1552
1640
|
for (const f of fields) {
|
|
1553
1641
|
const returnType = `string${f.isRequired ? '' : ' | null'}`;
|
|
1554
|
-
|
|
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}>()`);
|
|
1555
1653
|
result.getByFunctions.push(`
|
|
1556
1654
|
|
|
1557
|
-
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> {
|
|
1558
1656
|
${f.isRequired
|
|
1559
1657
|
? ''
|
|
1560
1658
|
: `if (${f.name} === null) {
|
|
@@ -1564,32 +1662,33 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1564
1662
|
return Promise.resolve(this.uniqueIds.${f.name}.get(${f.name})) // NOSONAR
|
|
1565
1663
|
}`);
|
|
1566
1664
|
result.clearCode.push(`this.uniqueIds.${f.name}.clear()`);
|
|
1567
|
-
result.verifyCode.push(`this.${getEnsureUniqueFnName(f)}(item)`);
|
|
1568
|
-
|
|
1665
|
+
result.verifyCode.push(`this.${getEnsureUniqueFnName(f)}(item${isInMemory ? `, claimed?.${f.name}` : ''})`);
|
|
1666
|
+
if (!isId) {
|
|
1667
|
+
result.updateCode.push(`
|
|
1569
1668
|
if (item.${f.name} !== undefined && existingItem.${f.name} !== item.${f.name}) {
|
|
1570
1669
|
this.${getEnsureUniqueFnName(f)}(item)
|
|
1571
1670
|
}`);
|
|
1671
|
+
}
|
|
1572
1672
|
result.ensureUniqueFunctions.push(`
|
|
1573
1673
|
/**
|
|
1574
|
-
*
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
}`);
|
|
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
|
+
}`);
|
|
1593
1692
|
if (f.isRequired) {
|
|
1594
1693
|
result.setCode.push(`this.uniqueIds.${f.name}.set(item.${f.name}, item)`);
|
|
1595
1694
|
result.removeCode.push(`this.uniqueIds.${f.name}.delete(item.${f.name})`);
|
|
@@ -1598,22 +1697,34 @@ function generateUniqueFieldsBlocks_Cached({ model }) {
|
|
|
1598
1697
|
result.setCode.push(`if (item.${f.name} !== null) { this.uniqueIds.${f.name}.set(item.${f.name}, item) }`);
|
|
1599
1698
|
result.removeCode.push(`if (item.${f.name} !== null) { this.uniqueIds.${f.name}.delete(item.${f.name}) }`);
|
|
1600
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
|
+
}
|
|
1601
1707
|
}
|
|
1602
1708
|
if (fields.length > 1) {
|
|
1603
1709
|
result.verifyFunctionComment = `In case a value of the fields ${fields
|
|
1604
1710
|
.map((f) => f.name)
|
|
1605
|
-
.join(', ')} is
|
|
1711
|
+
.join(', ')} is already taken, an error is thrown.\n`;
|
|
1606
1712
|
}
|
|
1607
1713
|
else if (fields.length === 1) {
|
|
1608
|
-
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`;
|
|
1609
1715
|
}
|
|
1610
1716
|
return result;
|
|
1611
1717
|
}
|
|
1612
1718
|
/**
|
|
1613
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.
|
|
1614
1725
|
*/
|
|
1615
1726
|
function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
1616
|
-
const { types, repository } = model;
|
|
1727
|
+
const { types, repository, idField } = model;
|
|
1617
1728
|
const fields = [];
|
|
1618
1729
|
for (const field of model.fields.values()) {
|
|
1619
1730
|
if (isUniqueField(field)) {
|
|
@@ -1621,6 +1732,7 @@ function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
|
1621
1732
|
}
|
|
1622
1733
|
}
|
|
1623
1734
|
const result = initUniqueIds();
|
|
1735
|
+
const checkedFields = [];
|
|
1624
1736
|
for (const f of fields) {
|
|
1625
1737
|
const returnType = `string${f.isRequired ? '' : ' | null'}`;
|
|
1626
1738
|
result.getByFunctions.push(`
|
|
@@ -1634,38 +1746,39 @@ function generateUniqueFieldsBlocks_Database({ model, }) {
|
|
|
1634
1746
|
}
|
|
1635
1747
|
return ${model.decoder.flattened.decoder.parseFunction.name}(result)
|
|
1636
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);
|
|
1637
1754
|
result.verifyCode.push(`await this.${getEnsureUniqueFnName(f)}(item)`);
|
|
1638
1755
|
result.updateCode.push(`
|
|
1639
1756
|
if (item.${f.name} !== undefined && existingItem.${f.name} !== item.${f.name}) {
|
|
1640
1757
|
await this.${getEnsureUniqueFnName(f)}(item)
|
|
1641
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.
|
|
1642
1760
|
result.ensureUniqueFunctions.push(`
|
|
1643
1761
|
/**
|
|
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}
|
|
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}\`)
|
|
1659
1772
|
}
|
|
1660
1773
|
}`);
|
|
1661
1774
|
}
|
|
1662
|
-
if (
|
|
1663
|
-
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
|
|
1664
1777
|
.map((f) => f.name)
|
|
1665
|
-
.join(', ')} is
|
|
1778
|
+
.join(', ')} is already taken, an error is thrown.\n`;
|
|
1666
1779
|
}
|
|
1667
|
-
else if (
|
|
1668
|
-
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`;
|
|
1669
1782
|
}
|
|
1670
1783
|
return result;
|
|
1671
1784
|
}
|
|
@@ -1759,8 +1872,26 @@ function initIndexBlockOptions() {
|
|
|
1759
1872
|
getterFunctions: [],
|
|
1760
1873
|
setCode: [],
|
|
1761
1874
|
removeCode: [],
|
|
1875
|
+
assertFunction: '',
|
|
1876
|
+
claimedTypeEntries: [],
|
|
1877
|
+
claimedInitEntries: [],
|
|
1878
|
+
claimCode: [],
|
|
1762
1879
|
};
|
|
1763
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';
|
|
1764
1895
|
function generateIndexBlocks_Database({ model, context, imports, }) {
|
|
1765
1896
|
const { types, repository } = model;
|
|
1766
1897
|
const result = initIndexBlockOptions();
|
|
@@ -1797,6 +1928,16 @@ function generateIndexBlocks_Database({ model, context, imports, }) {
|
|
|
1797
1928
|
}
|
|
1798
1929
|
return result;
|
|
1799
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
|
+
*/
|
|
1800
1941
|
function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
1801
1942
|
const result = initIndexBlockOptions();
|
|
1802
1943
|
// Only unique indexes get an in-memory lookup map and uniqueness enforcement;
|
|
@@ -1806,6 +1947,7 @@ function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
|
1806
1947
|
return result;
|
|
1807
1948
|
}
|
|
1808
1949
|
const isInMemory = model.repository.kind === 'InMemory';
|
|
1950
|
+
const assertCode = [];
|
|
1809
1951
|
for (const index of indexes) {
|
|
1810
1952
|
const i = getIndexDefinition({ index, model });
|
|
1811
1953
|
registerIndexFieldTypeImports({ fields: i.fields, context, imports });
|
|
@@ -1832,16 +1974,34 @@ function generateIndexBlocks_Cached({ model, context, imports }) {
|
|
|
1832
1974
|
await this.mutex.waitForUnlock()
|
|
1833
1975
|
return Promise.resolve(this.${i.name}.get(this.${keyFnName}(${keyArgFromFields})) ?? null) // NOSONAR
|
|
1834
1976
|
}`);
|
|
1835
|
-
|
|
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(`{
|
|
1836
1980
|
const ${i.name}Key = this.${keyFnName}(item)
|
|
1837
|
-
const ${existingVar} = this.${i.name}.get(${i.name}Key)
|
|
1838
|
-
|
|
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}) {
|
|
1839
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}]\`)
|
|
1840
1986
|
}
|
|
1841
|
-
this.${i.name}.set(${i.name}Key, item)
|
|
1842
1987
|
}`);
|
|
1988
|
+
result.setCode.push(`this.${i.name}.set(this.${keyFnName}(item), item)`);
|
|
1843
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)`);
|
|
1844
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
|
+
}`;
|
|
1845
2005
|
return result;
|
|
1846
2006
|
}
|
|
1847
2007
|
function getIndexDefinition({ index, model, }) {
|
|
@@ -1995,7 +2155,9 @@ function updateJsDoc(model) {
|
|
|
1995
2155
|
* Generates `updateMany` / `upsertMany`, whose bodies differ only in which
|
|
1996
2156
|
* single-item method they drive.
|
|
1997
2157
|
*
|
|
1998
|
-
* 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
|
|
1999
2161
|
* `RowConflictError` is rethrown: the caller only ever sees a shorter result
|
|
2000
2162
|
* array, which cannot distinguish "that row was not in the batch" from "your
|
|
2001
2163
|
* write lost a race and did not commit" - the one signal compare-and-set
|
|
@@ -2009,8 +2171,9 @@ function generateBatchMutation(model, context, mutation) {
|
|
|
2009
2171
|
return `${Generator.toJsDocComment([
|
|
2010
2172
|
summary,
|
|
2011
2173
|
'',
|
|
2012
|
-
'Per-item failures are skipped
|
|
2013
|
-
'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.',
|
|
2014
2177
|
])}
|
|
2015
2178
|
public async ${mutation}Many(
|
|
2016
2179
|
{ items, execution }: { items: ${dto.name}[], execution: ${context.actions.execution.interface.name} }
|
|
@@ -2024,6 +2187,7 @@ function generateBatchMutation(model, context, mutation) {
|
|
|
2024
2187
|
if (${context.repositories.rowConflict.isRowConflictError}(error)) {
|
|
2025
2188
|
throw error
|
|
2026
2189
|
}
|
|
2190
|
+
this.logger.warn(\`${mutation}Many skipped ${model.types.name} \${item.${model.idField.name} ?? '(new)'}: \${error instanceof Error ? error.message : String(error)}\`)
|
|
2027
2191
|
}
|
|
2028
2192
|
}
|
|
2029
2193
|
return result
|
|
@@ -2252,7 +2416,9 @@ function generateGetByKeyMethod_Database({ model }) {
|
|
|
2252
2416
|
*/
|
|
2253
2417
|
public async getByKey(key: string): Promise<${model.types.name} | null> {
|
|
2254
2418
|
// TODO: Implement proper scoped lookup. See method documentation for details.
|
|
2255
|
-
|
|
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
|
|
2256
2422
|
}`;
|
|
2257
2423
|
}
|
|
2258
2424
|
/**
|