From 63a72012b4894ae497eee579cd065c4e42a778cc Mon Sep 17 00:00:00 2001 From: WhyAsh5114 Date: Wed, 8 Jan 2025 17:37:02 +0530 Subject: [PATCH 1/6] fix: DateTime update null handling --- .../idb-utils/updateHandlers/DateTimeHandler.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/generator/src/fileCreators/idb-utils/updateHandlers/DateTimeHandler.ts b/packages/generator/src/fileCreators/idb-utils/updateHandlers/DateTimeHandler.ts index bd50f80..00130f1 100644 --- a/packages/generator/src/fileCreators/idb-utils/updateHandlers/DateTimeHandler.ts +++ b/packages/generator/src/fileCreators/idb-utils/updateHandlers/DateTimeHandler.ts @@ -38,10 +38,14 @@ export function addDateTimeUpdateHandler(utilsFile: SourceFile, models: readonly .conditionalWrite(nullableDateTimeFieldPresent, ` || dateTimeUpdate === null`) .writeLine(`)`) .block(() => { - writer.writeLine(`(record[fieldName] as ${fieldType}) = new Date(dateTimeUpdate);`); + writer.writeLine( + `(record[fieldName] as ${fieldType}) = dateTimeUpdate === null ? null : new Date(dateTimeUpdate);`, + ); }); writer.writeLine(`else if (dateTimeUpdate.set !== undefined)`).block(() => { - writer.writeLine(`(record[fieldName] as ${fieldType}) = new Date(dateTimeUpdate.set);`); + writer.writeLine( + `(record[fieldName] as ${fieldType}) = dateTimeUpdate.set === null ? null : new Date(dateTimeUpdate.set);`, + ); }); }, }); From 469194d5a776ae80fafaf8cc636fd7ea50dc6fc4 Mon Sep 17 00:00:00 2001 From: WhyAsh5114 Date: Wed, 8 Jan 2025 17:37:16 +0530 Subject: [PATCH 2/6] fix: prevent duplicate unique identifiers in getUniqueIdentifiers function --- packages/generator/src/helpers/utils.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/generator/src/helpers/utils.ts b/packages/generator/src/helpers/utils.ts index c67fa7d..9f3225e 100644 --- a/packages/generator/src/helpers/utils.ts +++ b/packages/generator/src/helpers/utils.ts @@ -38,6 +38,7 @@ export function getUniqueIdentifiers(model: Model) { const uniqueField = model.fields.filter(({ isUnique }) => isUnique); uniqueField.forEach((uniqueField) => { + if (uniqueIdentifiers.some((identifier) => identifier.name === uniqueField.name)) return; uniqueIdentifiers.push({ name: uniqueField.name, keyPath: JSON.stringify([uniqueField.name]), @@ -48,6 +49,7 @@ export function getUniqueIdentifiers(model: Model) { const compositeUniqueFields = model.uniqueIndexes; compositeUniqueFields.forEach(({ name, fields }) => { name = name ?? fields.join("_"); + if (uniqueIdentifiers.some((identifier) => identifier.name === name)) return; uniqueIdentifiers.push({ name, keyPath: JSON.stringify(fields), From f535358bd7801be66f91bacb731d319bdcce0ae6 Mon Sep 17 00:00:00 2001 From: WhyAsh5114 Date: Wed, 8 Jan 2025 17:53:44 +0530 Subject: [PATCH 3/6] fix: force types for unique input --- .../prisma-idb-client/classes/models/api/update.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/update.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/update.ts index e2d8a79..39f3b92 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/update.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/update.ts @@ -375,13 +375,13 @@ function handleOneToOneRelationMetaOnCurrentUpdate(writer: CodeBlockWriter, fiel writer .writeLine(`const updateData = query.data.${field.name}.update.data ?? query.data.${field.name}.update;`) .writeLine( - `await this.client.${toCamelCase(field.type)}.update({ where: { ...query.data.${field.name}.update.where, ${uniqueInput} }, data: updateData }, tx);`, + `await this.client.${toCamelCase(field.type)}.update({ where: { ...query.data.${field.name}.update.where, ${uniqueInput} } as Prisma.${field.type}WhereUniqueInput, data: updateData }, tx);`, ); }) .writeLine(`if (query.data.${field.name}.upsert)`) .block(() => { writer.writeLine( - `await this.client.${toCamelCase(field.type)}.upsert({ where: { ...query.data.${field.name}.upsert.where, ${uniqueInput} }, create: { ...query.data.${field.name}.upsert.create, ${fkFields} } as Prisma.Args['create'], update: query.data.${field.name}.upsert.update, }, tx);`, + `await this.client.${toCamelCase(field.type)}.upsert({ where: { ...query.data.${field.name}.upsert.where, ${uniqueInput} } as Prisma.${field.type}WhereUniqueInput, create: { ...query.data.${field.name}.upsert.create, ${fkFields} } as Prisma.Args['create'], update: query.data.${field.name}.upsert.update, }, tx);`, ); }) .writeLine(`if (query.data.${field.name}.connectOrCreate)`) From 874dd7d8c6a605c493ff18c12a647808e750851f Mon Sep 17 00:00:00 2001 From: WhyAsh5114 Date: Wed, 8 Jan 2025 17:54:16 +0530 Subject: [PATCH 4/6] fix: add proper type conversion and value handling for aggregate function --- .../classes/models/api/aggregate.ts | 154 +++++++++++++++--- 1 file changed, 130 insertions(+), 24 deletions(-) diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/aggregate.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/aggregate.ts index 3158bd2..287f6c3 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/aggregate.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/aggregate.ts @@ -14,10 +14,22 @@ export function addAggregateMethod(modelClass: ClassDeclaration, model: Model) { statements: (writer) => { addTxAndRecordSetup(writer, model); addCountHandling(writer); - addAvgHandling(writer, model); - addSumHandling(writer, model); - addMinHandling(writer, model); - addMaxHandling(writer, model); + + const hasAvgOrSum = model.fields.some( + (field) => field.type === "Float" || field.type === "Int" || field.type === "Decimal", + ); + const hasMinMax = + hasAvgOrSum || model.fields.some((field) => field.type === "DateTime" || field.type === "String"); + + if (hasMinMax) { + addMinHandling(writer, model); + addMaxHandling(writer, model); + } + + if (hasAvgOrSum) { + addAvgHandling(writer, model); + addSumHandling(writer, model); + } writer.writeLine(`return result as unknown as Prisma.Result;`); }, }); @@ -89,31 +101,125 @@ function addSumHandling(writer: CodeBlockWriter, model: Model) { } function addMinHandling(writer: CodeBlockWriter, model: Model) { + const numericFields = model.fields + .filter((field) => field.type === "Float" || field.type === "Int" || field.type === "Decimal") + .map((field) => field.name); + const dateTimeFields = model.fields.filter((field) => field.type === "DateTime").map((field) => field.name); + const stringFields = model.fields.filter((field) => field.type === "String").map((field) => field.name); + const booleanFields = model.fields.filter((field) => field.type === "Boolean").map((field) => field.name); + writer.writeLine(`if (query?._min)`).block(() => { - writer - .writeLine(`const minResult = {} as Prisma.Result["_min"];`) - .writeLine(`for (const untypedField of Object.keys(query._min))`) - .block(() => { - writer - .writeLine(`const field = untypedField as keyof (typeof records)[number];`) - .writeLine(`const values = records.map((record) => record[field] as number);`) - .writeLine(`(minResult[field as keyof typeof minResult] as number) = Math.min(...values);`); - }) - .writeLine(`result._min = minResult;`); + writer.writeLine(`const minResult = {} as Prisma.Result["_min"];`); + if (numericFields.length) { + writer + .writeLine(`const numericFields = ${JSON.stringify(numericFields)} as const;`) + .writeLine(`for (const field of numericFields)`) + .block(() => { + writer + .writeLine( + `const values = records.map((record) => record[field] as number).filter((value) => value !== undefined);`, + ) + .writeLine(`(minResult[field as keyof typeof minResult] as number) = Math.min(...values);`); + }); + } + if (dateTimeFields.length) { + writer + .writeLine(`const dateTimeFields = ${JSON.stringify(dateTimeFields)} as const;`) + .writeLine(`for (const field of dateTimeFields)`) + .block(() => { + writer + .writeLine( + `const values = records.map((record) => record[field]?.getTime()).filter((value) => value !== undefined);`, + ) + .writeLine(`(minResult[field as keyof typeof minResult] as Date) = new Date(Math.min(...values));`); + }); + } + if (stringFields.length) { + writer + .writeLine(`const stringFields = ${JSON.stringify(stringFields)} as const;`) + .writeLine(`for (const field of stringFields)`) + .block(() => { + writer + .writeLine( + `const values = records.map((record) => record[field] as string).filter((value) => value !== undefined);`, + ) + .writeLine(`(minResult[field as keyof typeof minResult] as string) = values.sort()[0];`); + }); + } + if (booleanFields.length) { + writer + .writeLine(`const booleanFields = ${JSON.stringify(booleanFields)} as const;`) + .writeLine(`for (const field of booleanFields)`) + .block(() => { + writer + .writeLine( + `const values = records.map((record) => record[field] as boolean).filter((value) => value !== undefined);`, + ) + .writeLine(`(minResult[field as keyof typeof minResult] as boolean) = values.includes(true);`); + }); + } + writer.writeLine(`result._min = minResult;`); }); } function addMaxHandling(writer: CodeBlockWriter, model: Model) { + const numericFields = model.fields + .filter((field) => field.type === "Float" || field.type === "Int" || field.type === "Decimal") + .map((field) => field.name); + const dateTimeFields = model.fields.filter((field) => field.type === "DateTime").map((field) => field.name); + const stringFields = model.fields.filter((field) => field.type === "String").map((field) => field.name); + const booleanFields = model.fields.filter((field) => field.type === "Boolean").map((field) => field.name); + writer.writeLine(`if (query?._max)`).block(() => { - writer - .writeLine(`const maxResult = {} as Prisma.Result["_max"];`) - .writeLine(`for (const untypedField of Object.keys(query._max))`) - .block(() => { - writer - .writeLine(`const field = untypedField as keyof (typeof records)[number];`) - .writeLine(`const values = records.map((record) => record[field] as number);`) - .writeLine(`(maxResult[field as keyof typeof maxResult] as number) = Math.max(...values);`); - }) - .writeLine(`result._max = maxResult;`); + writer.writeLine(`const maxResult = {} as Prisma.Result["_max"];`); + if (numericFields.length) { + writer + .writeLine(`const numericFields = ${JSON.stringify(numericFields)} as const;`) + .writeLine(`for (const field of numericFields)`) + .block(() => { + writer + .writeLine( + `const values = records.map((record) => record[field] as number).filter((value) => value !== undefined);`, + ) + .writeLine(`(maxResult[field as keyof typeof maxResult] as number) = Math.max(...values);`); + }); + } + if (dateTimeFields.length) { + writer + .writeLine(`const dateTimeFields = ${JSON.stringify(dateTimeFields)} as const;`) + .writeLine(`for (const field of dateTimeFields)`) + .block(() => { + writer + .writeLine( + `const values = records.map((record) => record[field]?.getTime()).filter((value) => value !== undefined);`, + ) + .writeLine(`(maxResult[field as keyof typeof maxResult] as Date) = new Date(Math.max(...values));`); + }); + } + if (stringFields.length) { + writer + .writeLine(`const stringFields = ${JSON.stringify(stringFields)} as const;`) + .writeLine(`for (const field of stringFields)`) + .block(() => { + writer + .writeLine( + `const values = records.map((record) => record[field] as string).filter((value) => value !== undefined);`, + ) + .writeLine(`(maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0];`); + }); + } + if (booleanFields.length) { + writer + .writeLine(`const booleanFields = ${JSON.stringify(booleanFields)} as const;`) + .writeLine(`for (const field of booleanFields)`) + .block(() => { + writer + .writeLine( + `const values = records.map((record) => record[field] as boolean).filter((value) => value !== undefined);`, + ) + .writeLine(`(maxResult[field as keyof typeof maxResult] as boolean) = values.includes(true);`); + }) + .writeLine(`result._max = maxResult;`); + } }); } From 894d1eee5a4db6db38a2761925b31a1dfddddc2c Mon Sep 17 00:00:00 2001 From: WhyAsh5114 Date: Wed, 8 Jan 2025 18:16:17 +0530 Subject: [PATCH 5/6] fix: enum types in default value assignment --- .../prisma-idb-client/classes/models/utils/_fillDefaults.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_fillDefaults.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_fillDefaults.ts index f6981d6..b97863a 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_fillDefaults.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_fillDefaults.ts @@ -77,7 +77,7 @@ function addAutoincrementDefault(writer: CodeBlockWriter, model: Model, field: F function addDefaultValue(writer: CodeBlockWriter, field: Field) { if (field.isList) { writer.write(`data.${field.name} = ${JSON.stringify(field.default)};`); - } else if (field.type === "String") { + } else if (field.type === "String" || field.kind === "enum") { writer.write(`data.${field.name} = '${field.default}';`); } else { writer.write(`data.${field.name} = ${field.default};`); From ca34904f3042b0bee1b57517ee63d9d57dc71efe Mon Sep 17 00:00:00 2001 From: WhyAsh5114 Date: Thu, 9 Jan 2025 15:09:21 +0530 Subject: [PATCH 6/6] fix: correct composite key ordering and minor bugfixes --- .../updateHandlers/DateTimeHandler.ts | 14 +- .../classes/models/api/aggregate.ts | 41 +- .../classes/models/api/create.ts | 44 +- .../classes/models/api/update.ts | 39 +- .../classes/models/utils/_applyRelations.ts | 30 +- .../classes/models/utils/_applyWhereClause.ts | 49 +- .../models/utils/_resolveOrderByKey.ts | 10 +- .../prisma/prisma-idb/prisma-idb-client.ts | 809 ++++++++++++------ packages/usage/src/prisma/schema.prisma | 2 +- 9 files changed, 676 insertions(+), 362 deletions(-) diff --git a/packages/generator/src/fileCreators/idb-utils/updateHandlers/DateTimeHandler.ts b/packages/generator/src/fileCreators/idb-utils/updateHandlers/DateTimeHandler.ts index 00130f1..113826d 100644 --- a/packages/generator/src/fileCreators/idb-utils/updateHandlers/DateTimeHandler.ts +++ b/packages/generator/src/fileCreators/idb-utils/updateHandlers/DateTimeHandler.ts @@ -38,14 +38,16 @@ export function addDateTimeUpdateHandler(utilsFile: SourceFile, models: readonly .conditionalWrite(nullableDateTimeFieldPresent, ` || dateTimeUpdate === null`) .writeLine(`)`) .block(() => { - writer.writeLine( - `(record[fieldName] as ${fieldType}) = dateTimeUpdate === null ? null : new Date(dateTimeUpdate);`, - ); + writer + .writeLine(`(record[fieldName] as ${fieldType}) = `) + .conditionalWrite(nullableDateTimeFieldPresent, () => `dateTimeUpdate === null ? null : `) + .write(`new Date(dateTimeUpdate);`); }); writer.writeLine(`else if (dateTimeUpdate.set !== undefined)`).block(() => { - writer.writeLine( - `(record[fieldName] as ${fieldType}) = dateTimeUpdate.set === null ? null : new Date(dateTimeUpdate.set);`, - ); + writer + .writeLine(`(record[fieldName] as ${fieldType}) = `) + .conditionalWrite(nullableDateTimeFieldPresent, () => `dateTimeUpdate.set === null ? null : `) + .write(`new Date(dateTimeUpdate.set);`); }); }, }); diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/aggregate.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/aggregate.ts index 287f6c3..5a7d043 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/aggregate.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/aggregate.ts @@ -15,11 +15,14 @@ export function addAggregateMethod(modelClass: ClassDeclaration, model: Model) { addTxAndRecordSetup(writer, model); addCountHandling(writer); - const hasAvgOrSum = model.fields.some( - (field) => field.type === "Float" || field.type === "Int" || field.type === "Decimal", - ); + const hasAvgOrSum = model.fields + .filter(({ isList }) => !isList) + .some((field) => field.type === "Float" || field.type === "Int" || field.type === "Decimal"); const hasMinMax = - hasAvgOrSum || model.fields.some((field) => field.type === "DateTime" || field.type === "String"); + hasAvgOrSum || + model.fields + .filter(({ isList }) => !isList) + .some((field) => field.type === "DateTime" || field.type === "String"); if (hasMinMax) { addMinHandling(writer, model); @@ -101,12 +104,15 @@ function addSumHandling(writer: CodeBlockWriter, model: Model) { } function addMinHandling(writer: CodeBlockWriter, model: Model) { - const numericFields = model.fields + const nonListFields = model.fields.filter(({ isList }) => !isList); + + const numericFields = nonListFields + .filter(({ isList }) => !isList) .filter((field) => field.type === "Float" || field.type === "Int" || field.type === "Decimal") .map((field) => field.name); - const dateTimeFields = model.fields.filter((field) => field.type === "DateTime").map((field) => field.name); - const stringFields = model.fields.filter((field) => field.type === "String").map((field) => field.name); - const booleanFields = model.fields.filter((field) => field.type === "Boolean").map((field) => field.name); + const dateTimeFields = nonListFields.filter((field) => field.type === "DateTime").map((field) => field.name); + const stringFields = nonListFields.filter((field) => field.type === "String").map((field) => field.name); + const booleanFields = nonListFields.filter((field) => field.type === "Boolean").map((field) => field.name); writer.writeLine(`if (query?._min)`).block(() => { writer.writeLine(`const minResult = {} as Prisma.Result["_min"];`); @@ -116,6 +122,7 @@ function addMinHandling(writer: CodeBlockWriter, model: Model) { .writeLine(`for (const field of numericFields)`) .block(() => { writer + .writeLine(`if (!query._min[field]) continue;`) .writeLine( `const values = records.map((record) => record[field] as number).filter((value) => value !== undefined);`, ) @@ -128,6 +135,7 @@ function addMinHandling(writer: CodeBlockWriter, model: Model) { .writeLine(`for (const field of dateTimeFields)`) .block(() => { writer + .writeLine(`if (!query._min[field]) continue;`) .writeLine( `const values = records.map((record) => record[field]?.getTime()).filter((value) => value !== undefined);`, ) @@ -140,6 +148,7 @@ function addMinHandling(writer: CodeBlockWriter, model: Model) { .writeLine(`for (const field of stringFields)`) .block(() => { writer + .writeLine(`if (!query._min[field]) continue;`) .writeLine( `const values = records.map((record) => record[field] as string).filter((value) => value !== undefined);`, ) @@ -152,6 +161,7 @@ function addMinHandling(writer: CodeBlockWriter, model: Model) { .writeLine(`for (const field of booleanFields)`) .block(() => { writer + .writeLine(`if (!query._min[field]) continue;`) .writeLine( `const values = records.map((record) => record[field] as boolean).filter((value) => value !== undefined);`, ) @@ -163,12 +173,14 @@ function addMinHandling(writer: CodeBlockWriter, model: Model) { } function addMaxHandling(writer: CodeBlockWriter, model: Model) { - const numericFields = model.fields + const nonListFields = model.fields.filter(({ isList }) => !isList); + + const numericFields = nonListFields .filter((field) => field.type === "Float" || field.type === "Int" || field.type === "Decimal") .map((field) => field.name); - const dateTimeFields = model.fields.filter((field) => field.type === "DateTime").map((field) => field.name); - const stringFields = model.fields.filter((field) => field.type === "String").map((field) => field.name); - const booleanFields = model.fields.filter((field) => field.type === "Boolean").map((field) => field.name); + const dateTimeFields = nonListFields.filter((field) => field.type === "DateTime").map((field) => field.name); + const stringFields = nonListFields.filter((field) => field.type === "String").map((field) => field.name); + const booleanFields = nonListFields.filter((field) => field.type === "Boolean").map((field) => field.name); writer.writeLine(`if (query?._max)`).block(() => { writer.writeLine(`const maxResult = {} as Prisma.Result["_max"];`); @@ -178,6 +190,7 @@ function addMaxHandling(writer: CodeBlockWriter, model: Model) { .writeLine(`for (const field of numericFields)`) .block(() => { writer + .writeLine(`if (!query._max[field]) continue;`) .writeLine( `const values = records.map((record) => record[field] as number).filter((value) => value !== undefined);`, ) @@ -190,6 +203,7 @@ function addMaxHandling(writer: CodeBlockWriter, model: Model) { .writeLine(`for (const field of dateTimeFields)`) .block(() => { writer + .writeLine(`if (!query._max[field]) continue;`) .writeLine( `const values = records.map((record) => record[field]?.getTime()).filter((value) => value !== undefined);`, ) @@ -202,6 +216,7 @@ function addMaxHandling(writer: CodeBlockWriter, model: Model) { .writeLine(`for (const field of stringFields)`) .block(() => { writer + .writeLine(`if (!query._max[field]) continue;`) .writeLine( `const values = records.map((record) => record[field] as string).filter((value) => value !== undefined);`, ) @@ -214,6 +229,7 @@ function addMaxHandling(writer: CodeBlockWriter, model: Model) { .writeLine(`for (const field of booleanFields)`) .block(() => { writer + .writeLine(`if (!query._max[field]) continue;`) .writeLine( `const values = records.map((record) => record[field] as boolean).filter((value) => value !== undefined);`, ) @@ -221,5 +237,6 @@ function addMaxHandling(writer: CodeBlockWriter, model: Model) { }) .writeLine(`result._max = maxResult;`); } + writer.writeLine(`result._max = maxResult;`); }); } diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/create.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/create.ts index 2b2ab4c..360c85a 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/create.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/create.ts @@ -45,7 +45,7 @@ function createDependencies(writer: CodeBlockWriter, model: Model, models: reado const foreignKeyField = model.fields.find((fkField) => fkField.name === field.relationFromFields?.at(0))!; writer.writeLine(`if (query.data.${field.name})`).block(() => { - addOneToOneMetaOnFieldRelation(writer, field); + addOneToOneMetaOnFieldRelation(writer, field, models); }); handleForeignKeyValidation(writer, field, foreignKeyField, models); }); @@ -79,7 +79,7 @@ function createDependents(writer: CodeBlockWriter, model: Model, models: readonl )!; if (!field.isList) { - addOneToOneMetaOnOtherFieldRelation(writer, field, otherField); + addOneToOneMetaOnOtherFieldRelation(writer, field, otherField, model); } else { const dependentModel = models.find(({ name }) => name === field.type)!; const fks = dependentModel.fields.filter( @@ -101,7 +101,10 @@ function applyClausesAndReturnRecords(writer: CodeBlockWriter, model: Model) { .writeLine(`return recordsWithRelations as Prisma.Result;`); } -function addOneToOneMetaOnFieldRelation(writer: CodeBlockWriter, field: Field) { +function addOneToOneMetaOnFieldRelation(writer: CodeBlockWriter, field: Field, models: readonly Model[]) { + const otherModel = models.find(({ name }) => name === field.type)!; + const otherModelKeyPath = JSON.parse(getUniqueIdentifiers(otherModel)[0].keyPath) as string[]; + writer .writeLine(`const fk: Partial = [];`) .writeLine(`if (query.data.${field.name}?.create)`) @@ -109,8 +112,8 @@ function addOneToOneMetaOnFieldRelation(writer: CodeBlockWriter, field: Field) { writer.writeLine( `const record = await this.client.${toCamelCase(field.type)}.create({ data: query.data.${field.name}.create }, tx);`, ); - for (let i = 0; i < field.relationToFields!.length; i++) { - writer.writeLine(`fk[${i}] = record.${field.relationToFields?.at(i)}`); + for (let i = 0; i < otherModelKeyPath!.length; i++) { + writer.writeLine(`fk[${i}] = record.${otherModelKeyPath?.at(i)}`); } }); @@ -120,8 +123,8 @@ function addOneToOneMetaOnFieldRelation(writer: CodeBlockWriter, field: Field) { `const record = await this.client.${toCamelCase(field.type)}.findUniqueOrThrow({ where: query.data.${field.name}.connect }, tx);`, ) .writeLine(`delete query.data.${field.name}.connect;`); - for (let i = 0; i < field.relationToFields!.length; i++) { - writer.writeLine(`fk[${i}] = record.${field.relationToFields?.at(i)};`); + for (let i = 0; i < otherModelKeyPath!.length; i++) { + writer.writeLine(`fk[${i}] = record.${otherModelKeyPath?.at(i)};`); } }); @@ -132,20 +135,26 @@ function addOneToOneMetaOnFieldRelation(writer: CodeBlockWriter, field: Field) { .writeLine(`create: query.data.${field.name}.connectOrCreate.create,`) .writeLine(`update: {},`) .writeLine(`}, tx);`); - for (let i = 0; i < field.relationToFields!.length; i++) { - writer.writeLine(`fk[${i}] = record.${field.relationToFields?.at(i)};`); + for (let i = 0; i < otherModelKeyPath!.length; i++) { + writer.writeLine(`fk[${i}] = record.${otherModelKeyPath?.at(i)};`); } }); writer.writeLine(`const unsafeData = query.data as Record;`); field.relationFromFields!.forEach((fromField, idx) => { - writer.writeLine(`unsafeData.${fromField} = fk[${idx}];`); + writer.writeLine(`unsafeData.${fromField} = fk[${otherModelKeyPath.indexOf(field.relationToFields![idx])}];`); }); writer.writeLine(`delete unsafeData.${field.name};`); } -function addOneToOneMetaOnOtherFieldRelation(writer: CodeBlockWriter, field: Field, otherField: Field) { - const keyPathMapping = otherField.relationFromFields!.map((field, idx) => `${field}: keyPath[${idx}]`).join(", "); +function addOneToOneMetaOnOtherFieldRelation(writer: CodeBlockWriter, field: Field, otherField: Field, model: Model) { + const modelKeyPath = JSON.parse(getUniqueIdentifiers(model)[0].keyPath) as string[]; + + const keyPathMapping = otherField + .relationFromFields!.map( + (field, idx) => `${field}: keyPath[${modelKeyPath.indexOf(otherField.relationToFields![idx])}]`, + ) + .join(", "); writer.writeLine(`if (query.data.${field.name}?.create)`).block(() => { writer @@ -159,7 +168,7 @@ function addOneToOneMetaOnOtherFieldRelation(writer: CodeBlockWriter, field: Fie }); writer.writeLine(`if (query.data.${field.name}?.connect)`).block(() => { writer.writeLine( - `await this.client.${toCamelCase(field.type)}.update({ where: query.data.${field.name}.connect, data: { ${otherField.relationFromFields?.at(0)}: keyPath[0] } }, tx);`, + `await this.client.${toCamelCase(field.type)}.update({ where: query.data.${field.name}.connect, data: { ${keyPathMapping} } }, tx);`, ); }); writer.writeLine(`if (query.data.${field.name}?.connectOrCreate)`).block(() => { @@ -188,14 +197,19 @@ function addOneToManyRelation( const modelPk = getUniqueIdentifiers(model)[0]; const modelPkFields = JSON.parse(modelPk.keyPath) as string[]; - const fields = `{ ${otherField.relationToFields!.map((field, idx) => `${field}: keyPath[${idx}]`).join(", ")} }`; + const fields = `{ ${modelPkFields.map((field, idx) => `${field}: keyPath[${idx}]`).join(", ")} }`; let nestedConnectLine = `${otherField.name}: { connect: `; if (modelPkFields.length === 1) nestedConnectLine += `${fields}`; else nestedConnectLine += `{ ${modelPk.name}: ${fields} }`; nestedConnectLine += ` }`; - const nestedDirectLine = otherField.relationFromFields!.map((field, idx) => `${field}: keyPath[${idx}]`).join(", "); + const nestedDirectLine = otherField + .relationFromFields!.map( + (field, idx) => + `${field}: keyPath[${JSON.parse(getUniqueIdentifiers(model)[0].keyPath).indexOf(otherField.relationToFields?.at(idx))}]`, + ) + .join(", "); const connectQuery = getCreateQuery(nestedConnectLine); writer.writeLine(`if (query.data?.${field.name}?.create)`).block(() => { diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/update.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/update.ts index 39f3b92..dd52a3f 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/update.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/api/update.ts @@ -24,7 +24,7 @@ export function addUpdateMethod(modelClass: ClassDeclaration, model: Model, mode // TODO: decimal, json addScalarListUpdateHandling(writer, model); addRelationUpdateHandling(writer, model, models); - addFkValidation(writer, model); + addFkValidation(writer, model, models); addPutAndReturn(writer, model, models); }, }); @@ -191,7 +191,7 @@ function addRelationUpdateHandling(writer: CodeBlockWriter, model: Model, models handleOneToManyRelationUpdate(writer, field, otherField); } else { if (field.relationFromFields?.length) { - handleOneToOneRelationMetaOnCurrentUpdate(writer, field); + handleOneToOneRelationMetaOnCurrentUpdate(writer, field, models); } else { handleOneToOneRelationMetaOnOtherUpdate(writer, field, otherField); } @@ -341,14 +341,16 @@ function handleOneToManyRelationUpdate(writer: CodeBlockWriter, field: Field, ot }); } -function handleOneToOneRelationMetaOnCurrentUpdate(writer: CodeBlockWriter, field: Field) { +function handleOneToOneRelationMetaOnCurrentUpdate(writer: CodeBlockWriter, field: Field, models: readonly Model[]) { const fkFields = `${field.relationToFields!.map((_field, idx) => `${_field}: record.${field.relationFromFields?.at(idx)}!`).join(", ")}`; let uniqueInput; if (field.relationFromFields!.length === 1) { uniqueInput = `${field.relationToFields!.map((_field, idx) => `${_field}: record.${field.relationFromFields?.at(idx)}!`).join(", ")}`; } else { - uniqueInput = `${field.relationToFields?.join("_")} : { ${field.relationToFields?.map((_field, idx) => `${_field}: record.${field.relationFromFields?.at(idx)}`).join(", ")} }`; + const otherModel = models.find((model) => model.name === field.type)!; + const otherModelKeyPath = JSON.parse(getUniqueIdentifiers(otherModel)[0].keyPath) as string[]; + uniqueInput = `${otherModelKeyPath.join("_")} : { ${field.relationToFields?.map((_field, idx) => `${_field}: record.${field.relationFromFields?.at(idx)}`).join(", ")} }`; } writer @@ -483,6 +485,9 @@ function handleOneToOneRelationMetaOnOtherUpdate(writer: CodeBlockWriter, field: // NoAction is the same as Restrict for this package function addReferentialUpdateHandling(writer: CodeBlockWriter, model: Model, models: readonly Model[]) { + const modelKeyPath = JSON.parse(getUniqueIdentifiers(model)[0].keyPath) as string[]; + const getIndexOfKeyPart = (fieldName: string) => modelKeyPath.indexOf(fieldName); + const referencingModels = models.filter((m) => m.fields.some((field) => field.kind === "object" && field.type === model.name && field.relationFromFields?.length), ); @@ -493,10 +498,14 @@ function addReferentialUpdateHandling(writer: CodeBlockWriter, model: Model, mod const objectField = referencingModel.fields.find((field) => field.type === model.name)!; const whereClause = objectField - .relationFromFields!.map((field, idx) => `${field}: startKeyPath[${idx}]`) + .relationFromFields!.map( + (field, idx) => `${field}: startKeyPath[${getIndexOfKeyPart(objectField.relationToFields![idx])}]`, + ) .join(", "); const dataClause = objectField - .relationFromFields!.map((field, idx) => `${field}: endKeyPath[${idx}]`) + .relationFromFields!.map( + (field, idx) => `${field}: endKeyPath[${getIndexOfKeyPart(objectField.relationToFields![idx])}]`, + ) .join(", "); writer @@ -511,19 +520,25 @@ function addReferentialUpdateHandling(writer: CodeBlockWriter, model: Model, mod }); } -function addFkValidation(writer: CodeBlockWriter, model: Model) { +function addFkValidation(writer: CodeBlockWriter, model: Model, models: readonly Model[]) { const dependentModelFields = model.fields.filter( (field) => field.kind === "object" && field.relationFromFields?.length, ); + for (const dependentModelField of dependentModelFields) { - let whereUnique = `{ ${dependentModelField.relationToFields?.at(0)}: record.${dependentModelField.relationFromFields?.at(0)} }`; - if (dependentModelField.relationFromFields!.length > 1) { - whereUnique = `{ ${dependentModelField.relationToFields?.join("_")}: { ${dependentModelField.relationToFields?.map((_field, idx) => `${_field}: record.${dependentModelField.relationFromFields?.at(idx)}`).join(", ")} } }`; + const dependentModel = models.find(({ name }) => name === dependentModelField.type)!; + const dependentModelKeyPath = JSON.parse(getUniqueIdentifiers(dependentModel)[0].keyPath) as string[]; + + let whereUnique = `{ ${dependentModelKeyPath.at(0)}: record.${dependentModelField.relationFromFields?.at(dependentModelField.relationToFields!.indexOf(dependentModelKeyPath[0]))} }`; + if (dependentModelKeyPath.length > 1) { + whereUnique = `{ ${dependentModelKeyPath.join("_")}: { ${dependentModelKeyPath.map((_field, idx) => `${_field}: record.${dependentModelField.relationFromFields?.at(dependentModelField.relationToFields!.indexOf(dependentModelKeyPath[idx]))}`).join(", ")} } }`; } - let condition = `query.data.${dependentModelField.relationFromFields?.at(0)} !== undefined`; + let condition = dependentModelField.relationFromFields + ?.map((field) => `query.data.${field} !== undefined`) + .join(" || "); if (!dependentModelField.isRequired) - condition += ` && record.${dependentModelField.relationFromFields?.at(0)} !== null`; + condition += ` && record.${dependentModelField.relationFromFields?.at(dependentModelField.relationToFields!.indexOf(dependentModelKeyPath[0]))} !== null`; writer.writeLine(`if (${condition})`).block(() => { writer.writeLine( diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_applyRelations.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_applyRelations.ts index 7f47521..cec9e6f 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_applyRelations.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_applyRelations.ts @@ -1,5 +1,5 @@ import { ClassDeclaration, CodeBlockWriter, Scope } from "ts-morph"; -import { toCamelCase } from "../../../../../helpers/utils"; +import { getUniqueIdentifiers, toCamelCase } from "../../../../../helpers/utils"; import { Field, Model } from "../../../../types"; export function addApplyRelations(modelClass: ClassDeclaration, model: Model, models: readonly Model[]) { @@ -48,7 +48,7 @@ function addRelationProcessing(writer: CodeBlockWriter, model: Model, models: re const otherFieldOfRelation = allFields.find( (_field) => _field.relationName === field.relationName && field !== _field, )!; - handleVariousRelationships(writer, field, otherFieldOfRelation); + handleVariousRelationships(writer, field, otherFieldOfRelation, models); }); }); writer.writeLine("return unsafeRecord;"); @@ -56,10 +56,15 @@ function addRelationProcessing(writer: CodeBlockWriter, model: Model, models: re .writeLine(");"); } -function handleVariousRelationships(writer: CodeBlockWriter, field: Field, otherField: Field) { +function handleVariousRelationships( + writer: CodeBlockWriter, + field: Field, + otherField: Field, + models: readonly Model[], +) { if (!field.isList) { if (field.relationFromFields?.length) { - addOneToOneMetaOnFieldRelation(writer, field); + addOneToOneMetaOnFieldRelation(writer, field, models); } else { addOneToOneMetaOnOtherFieldRelation(writer, field, otherField); } @@ -68,10 +73,13 @@ function handleVariousRelationships(writer: CodeBlockWriter, field: Field, other } } -function addOneToOneMetaOnFieldRelation(writer: CodeBlockWriter, field: Field) { - const compositeKeyName = field.relationToFields!.join("_"); - const compositeKey = field - .relationToFields!.map((toField, idx) => `${toField}: record.${field.relationFromFields?.at(idx)}`) +function addOneToOneMetaOnFieldRelation(writer: CodeBlockWriter, field: Field, models: readonly Model[]) { + const otherModel = models.find(({ name }) => name === field.type)!; + const otherModelKeyPath = JSON.parse(getUniqueIdentifiers(otherModel)[0].keyPath) as string[]; + + const compositeKeyName = otherModelKeyPath.join("_"); + const compositeKey = otherModelKeyPath + .map((toField) => `${toField}: record.${field.relationFromFields?.at(field.relationToFields!.indexOf(toField))}!`) .join(", "); writer @@ -109,12 +117,16 @@ function addOneToOneMetaOnOtherFieldRelation(writer: CodeBlockWriter, field: Fie } function addOneToManyRelation(writer: CodeBlockWriter, field: Field, otherField: Field) { + const fkMapping = otherField + .relationFromFields!.map((fromField, idx) => `${fromField}: record.${otherField.relationToFields?.at(idx)}!`) + .join(", "); + writer .writeLine(`unsafeRecord['${field.name}'] = await this.client.${toCamelCase(field.type)}.findMany(`) .block(() => { writer .writeLine(`...(attach_${field.name} === true ? {} : attach_${field.name}),`) - .writeLine(`where: { ${otherField.relationFromFields?.at(0)}: record.${otherField.relationToFields?.at(0)} }`); + .writeLine(`where: { ${fkMapping} }`); }) .writeLine(`, tx)`); } diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_applyWhereClause.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_applyWhereClause.ts index d318c2b..bbf1a51 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_applyWhereClause.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_applyWhereClause.ts @@ -2,6 +2,10 @@ import type { Field, Model } from "src/fileCreators/types"; import { toCamelCase } from "../../../../../helpers/utils"; import { ClassDeclaration, CodeBlockWriter, Scope } from "ts-morph"; +// TODO: composite key handling in _applyWhereClause, _resolveOrderByKey, _applyRelations +// TODO: update (fk validation should be of all key parts instead of just the first one) +// * see working tree changes in prisma-idb-client.ts for more details + export function addApplyWhereClause(modelClass: ClassDeclaration, model: Model, models: readonly Model[]) { modelClass.addMethod({ name: "_applyWhereClause", @@ -217,7 +221,9 @@ function addRelationFiltering(writer: CodeBlockWriter, model: Model, models: rea function addOneToOneMetaOnFieldFiltering(writer: CodeBlockWriter, field: Field) { const fkName = field.relationFromFields?.at(0); - const relationPk = field.relationToFields?.at(0); + const fkMapping = field.relationToFields + ?.map((fk, idx) => `${fk}: record.${field.relationFromFields?.at(idx)}`) + .join(", "); if (!field.isRequired) { writer.writeLine(`if (whereClause.${field.name} === null)`).block(() => { @@ -236,7 +242,7 @@ function addOneToOneMetaOnFieldFiltering(writer: CodeBlockWriter, field: Field) writer .conditionalWriteLine(!field.isRequired, () => `if (record.${fkName} === null) return null;`) .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...is, ${relationPk}: record.${fkName} } }, tx)`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...is, ${fkMapping} } }, tx)`, ) .writeLine(`if (!relatedRecord) return null;`); }); @@ -250,7 +256,7 @@ function addOneToOneMetaOnFieldFiltering(writer: CodeBlockWriter, field: Field) writer .conditionalWriteLine(!field.isRequired, () => `if (record.${fkName} === null) return null;`) .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...isNot, ${relationPk}: record.${fkName} } }, tx)`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...isNot, ${fkMapping} } }, tx)`, ) .writeLine(`if (relatedRecord) return null;`); }); @@ -259,7 +265,7 @@ function addOneToOneMetaOnFieldFiltering(writer: CodeBlockWriter, field: Field) writer .conditionalWriteLine(!field.isRequired, () => `if (record.${fkName} === null) return null;`) .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...whereClause.${field.name}, ${relationPk}: record.${fkName} } }, tx);`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...whereClause.${field.name}, ${fkMapping} } }, tx);`, ) .writeLine(`if (!relatedRecord) return null;`); }); @@ -267,14 +273,15 @@ function addOneToOneMetaOnFieldFiltering(writer: CodeBlockWriter, field: Field) } function addOneToOneMetaOnOtherFieldFiltering(writer: CodeBlockWriter, field: Field, otherField: Field) { - const fkName = otherField.relationFromFields?.at(0); - const relationPk = otherField.relationToFields?.at(0); + const fkMapping = otherField.relationFromFields + ?.map((fk, idx) => `${fk}: record.${otherField.relationToFields?.at(idx)}`) + .join(", "); if (!field.isRequired) { writer.writeLine(`if (whereClause.${field.name} === null)`).block(() => { writer .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ${fkName}: record.${relationPk} } }, tx)`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ${fkMapping} } }, tx)`, ) .writeLine(`if (relatedRecord) return null;`); }); @@ -286,7 +293,7 @@ function addOneToOneMetaOnOtherFieldFiltering(writer: CodeBlockWriter, field: Fi writer.writeLine(`if (is === null)`).block(() => { writer .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ${fkName}: record.${relationPk} } }, tx)`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ${fkMapping} } }, tx)`, ) .writeLine(`if (relatedRecord) return null;`); }); @@ -294,7 +301,7 @@ function addOneToOneMetaOnOtherFieldFiltering(writer: CodeBlockWriter, field: Fi writer.writeLine(`if (is !== null && is !== undefined)`).block(() => { writer .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...is, ${fkName}: record.${relationPk} } }, tx)`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...is, ${fkMapping} } }, tx)`, ) .writeLine(`if (!relatedRecord) return null;`); }); @@ -303,7 +310,7 @@ function addOneToOneMetaOnOtherFieldFiltering(writer: CodeBlockWriter, field: Fi writer.writeLine(`if (isNot === null)`).block(() => { writer .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ${fkName}: record.${relationPk} } }, tx)`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ${fkMapping} } }, tx)`, ) .writeLine(`if (!relatedRecord) return null;`); }); @@ -311,16 +318,19 @@ function addOneToOneMetaOnOtherFieldFiltering(writer: CodeBlockWriter, field: Fi writer.writeLine(`if (isNot !== null && isNot !== undefined)`).block(() => { writer .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...isNot, ${fkName}: record.${relationPk} } }, tx)`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...isNot, ${fkMapping} } }, tx)`, ) .writeLine(`if (relatedRecord) return null;`); }); writer.writeLine(`if (Object.keys(rest).length)`).block(() => { writer - .conditionalWriteLine(!field.isRequired, () => `if (record.${relationPk} === null) return null;`) + .conditionalWriteLine( + !field.isRequired, + () => `if (record.${otherField.relationToFields?.at(0)} === null) return null;`, + ) .writeLine( - `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...whereClause.${field.name}, ${fkName}: record.${relationPk} } }, tx);`, + `const relatedRecord = await this.client.${toCamelCase(field.type)}.findFirst({ where: { ...whereClause.${field.name}, ${fkMapping} } }, tx);`, ) .writeLine(`if (!relatedRecord) return null;`); }); @@ -328,8 +338,9 @@ function addOneToOneMetaOnOtherFieldFiltering(writer: CodeBlockWriter, field: Fi } function addOneToManyFiltering(writer: CodeBlockWriter, field: Field, otherField: Field) { - const fkName = otherField.relationFromFields?.at(0); - const relationPk = otherField.relationToFields?.at(0); + const fkMapping = otherField.relationFromFields + ?.map((fk, idx) => `${fk}: record.${otherField.relationToFields?.at(idx)}`) + .join(", "); writer.writeLine(`if (whereClause.${field.name})`).block(() => { writer @@ -338,9 +349,7 @@ function addOneToManyFiltering(writer: CodeBlockWriter, field: Field, otherField writer .writeLine(`const violatingRecord = await this.client.${toCamelCase(field.type)}.findFirst(`) .block(() => { - writer.writeLine( - `where: { NOT: { ...whereClause.${field.name}.every }, ${fkName}: record.${relationPk} }, tx`, - ); + writer.writeLine(`where: { NOT: { ...whereClause.${field.name}.every }, ${fkMapping} }, tx`); }) .writeLine(`);`) .writeLine(`if (violatingRecord !== null) return null;`); @@ -350,7 +359,7 @@ function addOneToManyFiltering(writer: CodeBlockWriter, field: Field, otherField writer .writeLine(`const relatedRecords = await this.client.${toCamelCase(field.type)}.findMany(`) .block(() => { - writer.writeLine(`where: { ...whereClause.${field.name}.some, ${fkName}: record.${relationPk} }, tx`); + writer.writeLine(`where: { ...whereClause.${field.name}.some, ${fkMapping} }, tx`); }) .writeLine(`);`) .writeLine(`if (relatedRecords.length === 0) return null;`); @@ -360,7 +369,7 @@ function addOneToManyFiltering(writer: CodeBlockWriter, field: Field, otherField writer .writeLine(`const violatingRecord = await this.client.${toCamelCase(field.type)}.findFirst(`) .block(() => { - writer.writeLine(`where: { ...whereClause.${field.name}.none, ${fkName}: record.${relationPk} }, tx`); + writer.writeLine(`where: { ...whereClause.${field.name}.none, ${fkMapping} }, tx`); }) .writeLine(`);`) .writeLine(`if (violatingRecord !== null) return null;`); diff --git a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_resolveOrderByKey.ts b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_resolveOrderByKey.ts index 7174eed..67bdd62 100644 --- a/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_resolveOrderByKey.ts +++ b/packages/generator/src/fileCreators/prisma-idb-client/classes/models/utils/_resolveOrderByKey.ts @@ -62,13 +62,13 @@ function addOneToManyResolution(writer: CodeBlockWriter, model: Model, models: r const otherField = models .flatMap(({ fields }) => fields) .find((_field) => _field !== field && _field.relationName === field.relationName)!; - const pkOfOther = otherField.relationFromFields!.at(0)!; - const fkToOther = otherField.relationToFields!.at(0)!; + + const fkMapping = otherField + .relationFromFields!.map((field, idx) => `${field}: record.${otherField.relationToFields?.at(idx)}`) + .join(", "); writer.writeLine(`if (orderByInput.${field.name})`).block(() => { - writer.writeLine( - `return await this.client.${toCamelCase(field.type)}.count({ where: { ${pkOfOther}: record.${fkToOther} } }, tx);`, - ); + writer.writeLine(`return await this.client.${toCamelCase(field.type)}.count({ where: { ${fkMapping} } }, tx);`); }); } } diff --git a/packages/usage/src/prisma/prisma-idb/prisma-idb-client.ts b/packages/usage/src/prisma/prisma-idb/prisma-idb-client.ts index 2942eae..2f46717 100644 --- a/packages/usage/src/prisma/prisma-idb/prisma-idb-client.ts +++ b/packages/usage/src/prisma/prisma-idb/prisma-idb-client.ts @@ -355,7 +355,7 @@ class UserIDBClass extends BaseIDBModelClass<"User"> { unsafeRecord["posts"] = await this.client.post.findMany( { ...(attach_posts === true ? {} : attach_posts), - where: { authorId: record.id }, + where: { authorId: record.id! }, }, tx, ); @@ -365,7 +365,7 @@ class UserIDBClass extends BaseIDBModelClass<"User"> { unsafeRecord["comments"] = await this.client.comment.findMany( { ...(attach_comments === true ? {} : attach_comments), - where: { userId: record.id }, + where: { userId: record.id! }, }, tx, ); @@ -375,7 +375,7 @@ class UserIDBClass extends BaseIDBModelClass<"User"> { unsafeRecord["Child"] = await this.client.child.findMany( { ...(attach_Child === true ? {} : attach_Child), - where: { userId: record.id }, + where: { userId: record.id! }, }, tx, ); @@ -385,7 +385,7 @@ class UserIDBClass extends BaseIDBModelClass<"User"> { unsafeRecord["Father"] = await this.client.father.findMany( { ...(attach_Father === true ? {} : attach_Father), - where: { userId: record.id }, + where: { userId: record.id! }, }, tx, ); @@ -395,7 +395,7 @@ class UserIDBClass extends BaseIDBModelClass<"User"> { unsafeRecord["Mother"] = await this.client.mother.findMany( { ...(attach_Mother === true ? {} : attach_Mother), - where: { userId: record.id }, + where: { userId: record.id! }, }, tx, ); @@ -405,7 +405,7 @@ class UserIDBClass extends BaseIDBModelClass<"User"> { unsafeRecord["groups"] = await this.client.userGroup.findMany( { ...(attach_groups === true ? {} : attach_groups), - where: { userId: record.id }, + where: { userId: record.id! }, }, tx, ); @@ -2471,6 +2471,38 @@ class UserIDBClass extends BaseIDBModelClass<"User"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["id"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const stringFields = ["name"] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["id"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const stringFields = ["name"] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -2489,24 +2521,6 @@ class UserIDBClass extends BaseIDBModelClass<"User"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -2594,7 +2608,7 @@ class GroupIDBClass extends BaseIDBModelClass<"Group"> { unsafeRecord["userGroups"] = await this.client.userGroup.findMany( { ...(attach_userGroups === true ? {} : attach_userGroups), - where: { groupId: record.id }, + where: { groupId: record.id! }, }, tx, ); @@ -3240,6 +3254,38 @@ class GroupIDBClass extends BaseIDBModelClass<"Group"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["id"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const stringFields = ["name"] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["id"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const stringFields = ["name"] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -3258,24 +3304,6 @@ class GroupIDBClass extends BaseIDBModelClass<"Group"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -3376,7 +3404,7 @@ class UserGroupIDBClass extends BaseIDBModelClass<"UserGroup"> { unsafeRecord["group"] = await this.client.group.findUnique( { ...(attach_group === true ? {} : attach_group), - where: { id: record.groupId }, + where: { id: record.groupId! }, }, tx, ); @@ -3386,7 +3414,7 @@ class UserGroupIDBClass extends BaseIDBModelClass<"UserGroup"> { unsafeRecord["user"] = await this.client.user.findUnique( { ...(attach_user === true ? {} : attach_user), - where: { id: record.userId }, + where: { id: record.userId! }, }, tx, ); @@ -3942,14 +3970,17 @@ class UserGroupIDBClass extends BaseIDBModelClass<"UserGroup"> { if (query.data.group.update) { const updateData = query.data.group.update.data ?? query.data.group.update; await this.client.group.update( - { where: { ...query.data.group.update.where, id: record.groupId! }, data: updateData }, + { + where: { ...query.data.group.update.where, id: record.groupId! } as Prisma.GroupWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.group.upsert) { await this.client.group.upsert( { - where: { ...query.data.group.upsert.where, id: record.groupId! }, + where: { ...query.data.group.upsert.where, id: record.groupId! } as Prisma.GroupWhereUniqueInput, create: { ...query.data.group.upsert.create, id: record.groupId! } as Prisma.Args< Prisma.GroupDelegate, "upsert" @@ -3985,14 +4016,17 @@ class UserGroupIDBClass extends BaseIDBModelClass<"UserGroup"> { if (query.data.user.update) { const updateData = query.data.user.update.data ?? query.data.user.update; await this.client.user.update( - { where: { ...query.data.user.update.where, id: record.userId! }, data: updateData }, + { + where: { ...query.data.user.update.where, id: record.userId! } as Prisma.UserWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.user.upsert) { await this.client.user.upsert( { - where: { ...query.data.user.upsert.where, id: record.userId! }, + where: { ...query.data.user.upsert.where, id: record.userId! } as Prisma.UserWhereUniqueInput, create: { ...query.data.user.upsert.create, id: record.userId! } as Prisma.Args< Prisma.UserDelegate, "upsert" @@ -4113,6 +4147,38 @@ class UserGroupIDBClass extends BaseIDBModelClass<"UserGroup"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["groupId", "userId"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const dateTimeFields = ["joinedOn"] as const; + for (const field of dateTimeFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field]?.getTime()).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as Date) = new Date(Math.min(...values)); + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["groupId", "userId"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const dateTimeFields = ["joinedOn"] as const; + for (const field of dateTimeFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field]?.getTime()).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as Date) = new Date(Math.max(...values)); + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -4131,24 +4197,6 @@ class UserGroupIDBClass extends BaseIDBModelClass<"UserGroup"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -4231,7 +4279,7 @@ class ProfileIDBClass extends BaseIDBModelClass<"Profile"> { unsafeRecord["user"] = await this.client.user.findUnique( { ...(attach_user === true ? {} : attach_user), - where: { id: record.userId }, + where: { id: record.userId! }, }, tx, ); @@ -4676,14 +4724,17 @@ class ProfileIDBClass extends BaseIDBModelClass<"Profile"> { if (query.data.user.update) { const updateData = query.data.user.update.data ?? query.data.user.update; await this.client.user.update( - { where: { ...query.data.user.update.where, id: record.userId! }, data: updateData }, + { + where: { ...query.data.user.update.where, id: record.userId! } as Prisma.UserWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.user.upsert) { await this.client.user.upsert( { - where: { ...query.data.user.upsert.where, id: record.userId! }, + where: { ...query.data.user.upsert.where, id: record.userId! } as Prisma.UserWhereUniqueInput, create: { ...query.data.user.upsert.create, id: record.userId! } as Prisma.Args< Prisma.UserDelegate, "upsert" @@ -4793,6 +4844,38 @@ class ProfileIDBClass extends BaseIDBModelClass<"Profile"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["id", "userId"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const stringFields = ["bio"] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["id", "userId"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const stringFields = ["bio"] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -4811,24 +4894,6 @@ class ProfileIDBClass extends BaseIDBModelClass<"Profile"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -4957,7 +5022,7 @@ class PostIDBClass extends BaseIDBModelClass<"Post"> { : await this.client.user.findUnique( { ...(attach_author === true ? {} : attach_author), - where: { id: record.authorId }, + where: { id: record.authorId! }, }, tx, ); @@ -4967,7 +5032,7 @@ class PostIDBClass extends BaseIDBModelClass<"Post"> { unsafeRecord["comments"] = await this.client.comment.findMany( { ...(attach_comments === true ? {} : attach_comments), - where: { postId: record.id }, + where: { postId: record.id! }, }, tx, ); @@ -5596,14 +5661,17 @@ class PostIDBClass extends BaseIDBModelClass<"Post"> { if (query.data.author.update) { const updateData = query.data.author.update.data ?? query.data.author.update; await this.client.user.update( - { where: { ...query.data.author.update.where, id: record.authorId! }, data: updateData }, + { + where: { ...query.data.author.update.where, id: record.authorId! } as Prisma.UserWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.author.upsert) { await this.client.user.upsert( { - where: { ...query.data.author.upsert.where, id: record.authorId! }, + where: { ...query.data.author.upsert.where, id: record.authorId! } as Prisma.UserWhereUniqueInput, create: { ...query.data.author.upsert.create, id: record.authorId! } as Prisma.Args< Prisma.UserDelegate, "upsert" @@ -5814,6 +5882,38 @@ class PostIDBClass extends BaseIDBModelClass<"Post"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["id", "authorId", "views"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const stringFields = ["title"] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["id", "authorId", "views"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const stringFields = ["title"] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -5832,24 +5932,6 @@ class PostIDBClass extends BaseIDBModelClass<"Post"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -5950,7 +6032,7 @@ class CommentIDBClass extends BaseIDBModelClass<"Comment"> { unsafeRecord["post"] = await this.client.post.findUnique( { ...(attach_post === true ? {} : attach_post), - where: { id: record.postId }, + where: { id: record.postId! }, }, tx, ); @@ -5960,7 +6042,7 @@ class CommentIDBClass extends BaseIDBModelClass<"Comment"> { unsafeRecord["user"] = await this.client.user.findUnique( { ...(attach_user === true ? {} : attach_user), - where: { id: record.userId }, + where: { id: record.userId! }, }, tx, ); @@ -6506,14 +6588,17 @@ class CommentIDBClass extends BaseIDBModelClass<"Comment"> { if (query.data.post.update) { const updateData = query.data.post.update.data ?? query.data.post.update; await this.client.post.update( - { where: { ...query.data.post.update.where, id: record.postId! }, data: updateData }, + { + where: { ...query.data.post.update.where, id: record.postId! } as Prisma.PostWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.post.upsert) { await this.client.post.upsert( { - where: { ...query.data.post.upsert.where, id: record.postId! }, + where: { ...query.data.post.upsert.where, id: record.postId! } as Prisma.PostWhereUniqueInput, create: { ...query.data.post.upsert.create, id: record.postId! } as Prisma.Args< Prisma.PostDelegate, "upsert" @@ -6549,14 +6634,17 @@ class CommentIDBClass extends BaseIDBModelClass<"Comment"> { if (query.data.user.update) { const updateData = query.data.user.update.data ?? query.data.user.update; await this.client.user.update( - { where: { ...query.data.user.update.where, id: record.userId! }, data: updateData }, + { + where: { ...query.data.user.update.where, id: record.userId! } as Prisma.UserWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.user.upsert) { await this.client.user.upsert( { - where: { ...query.data.user.upsert.where, id: record.userId! }, + where: { ...query.data.user.upsert.where, id: record.userId! } as Prisma.UserWhereUniqueInput, create: { ...query.data.user.upsert.create, id: record.userId! } as Prisma.Args< Prisma.UserDelegate, "upsert" @@ -6670,6 +6758,38 @@ class CommentIDBClass extends BaseIDBModelClass<"Comment"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["postId", "userId"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const stringFields = ["id", "text"] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["postId", "userId"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const stringFields = ["id", "text"] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -6688,24 +6808,6 @@ class CommentIDBClass extends BaseIDBModelClass<"Comment"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -7317,6 +7419,63 @@ class AllFieldScalarTypesIDBClass extends BaseIDBModelClass<"AllFieldScalarTypes } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["id", "float", "decimal"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const dateTimeFields = ["dateTime"] as const; + for (const field of dateTimeFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field]?.getTime()).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as Date) = new Date(Math.min(...values)); + } + const stringFields = ["string"] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + const booleanFields = ["boolean"] as const; + for (const field of booleanFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as boolean).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as boolean) = values.includes(true); + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["id", "float", "decimal"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const dateTimeFields = ["dateTime"] as const; + for (const field of dateTimeFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field]?.getTime()).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as Date) = new Date(Math.max(...values)); + } + const stringFields = ["string"] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + const booleanFields = ["boolean"] as const; + for (const field of booleanFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as boolean).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as boolean) = values.includes(true); + } + result._max = maxResult; + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -7335,24 +7494,6 @@ class AllFieldScalarTypesIDBClass extends BaseIDBModelClass<"AllFieldScalarTypes } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -7384,21 +7525,33 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { if (whereClause.children) { if (whereClause.children.every) { const violatingRecord = await this.client.child.findFirst({ - where: { NOT: { ...whereClause.children.every }, fatherFirstName: record.firstName }, + where: { + NOT: { ...whereClause.children.every }, + fatherLastName: record.lastName, + fatherFirstName: record.firstName, + }, tx, }); if (violatingRecord !== null) return null; } if (whereClause.children.some) { const relatedRecords = await this.client.child.findMany({ - where: { ...whereClause.children.some, fatherFirstName: record.firstName }, + where: { + ...whereClause.children.some, + fatherLastName: record.lastName, + fatherFirstName: record.firstName, + }, tx, }); if (relatedRecords.length === 0) return null; } if (whereClause.children.none) { const violatingRecord = await this.client.child.findFirst({ - where: { ...whereClause.children.none, fatherFirstName: record.firstName }, + where: { + ...whereClause.children.none, + fatherLastName: record.lastName, + fatherFirstName: record.firstName, + }, tx, }); if (violatingRecord !== null) return null; @@ -7408,21 +7561,21 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { const { is, isNot, ...rest } = whereClause.wife; if (is !== null && is !== undefined) { const relatedRecord = await this.client.mother.findFirst( - { where: { ...is, firstName: record.motherFirstName } }, + { where: { ...is, firstName: record.motherFirstName, lastName: record.motherLastName } }, tx, ); if (!relatedRecord) return null; } if (isNot !== null && isNot !== undefined) { const relatedRecord = await this.client.mother.findFirst( - { where: { ...isNot, firstName: record.motherFirstName } }, + { where: { ...isNot, firstName: record.motherFirstName, lastName: record.motherLastName } }, tx, ); if (relatedRecord) return null; } if (Object.keys(rest).length) { const relatedRecord = await this.client.mother.findFirst( - { where: { ...whereClause.wife, firstName: record.motherFirstName } }, + { where: { ...whereClause.wife, firstName: record.motherFirstName, lastName: record.motherLastName } }, tx, ); if (!relatedRecord) return null; @@ -7503,7 +7656,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { unsafeRecord["children"] = await this.client.child.findMany( { ...(attach_children === true ? {} : attach_children), - where: { fatherFirstName: record.firstName }, + where: { fatherLastName: record.lastName!, fatherFirstName: record.firstName! }, }, tx, ); @@ -7513,7 +7666,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { unsafeRecord["wife"] = await this.client.mother.findUnique( { ...(attach_wife === true ? {} : attach_wife), - where: { firstName_lastName: { firstName: record.motherFirstName, lastName: record.motherLastName } }, + where: { firstName_lastName: { firstName: record.motherFirstName!, lastName: record.motherLastName! } }, }, tx, ); @@ -7526,7 +7679,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { : await this.client.user.findUnique( { ...(attach_user === true ? {} : attach_user), - where: { id: record.userId }, + where: { id: record.userId! }, }, tx, ); @@ -7587,7 +7740,10 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { ); } if (orderByInput.children) { - return await this.client.child.count({ where: { fatherFirstName: record.firstName } }, tx); + return await this.client.child.count( + { where: { fatherLastName: record.lastName, fatherFirstName: record.firstName } }, + tx, + ); } } @@ -8116,7 +8272,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { await Promise.all( IDBUtils.convertToArray(query.data.children.connect).map(async (connectWhere) => { await this.client.child.update( - { where: connectWhere, data: { fatherFirstName: keyPath[0], fatherLastName: keyPath[1] } }, + { where: connectWhere, data: { fatherLastName: keyPath[1], fatherFirstName: keyPath[0] } }, tx, ); }), @@ -8130,10 +8286,10 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { where: connectOrCreate.where, create: { ...connectOrCreate.create, - fatherFirstName: keyPath[0], fatherLastName: keyPath[1], + fatherFirstName: keyPath[0], } as Prisma.Args["data"], - update: { fatherFirstName: keyPath[0], fatherLastName: keyPath[1] }, + update: { fatherLastName: keyPath[1], fatherFirstName: keyPath[0] }, }, tx, ); @@ -8145,8 +8301,8 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { { data: IDBUtils.convertToArray(query.data.children.createMany.data).map((createData) => ({ ...createData, - fatherFirstName: keyPath[0], fatherLastName: keyPath[1], + fatherFirstName: keyPath[0], })), }, tx, @@ -8203,7 +8359,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { const record = await this.findUnique(query, tx); if (!record) throw new Error("Record not found"); const relatedChild = await this.client.child.findMany( - { where: { fatherFirstName: record.firstName, fatherLastName: record.lastName } }, + { where: { fatherLastName: record.lastName, fatherFirstName: record.firstName } }, tx, ); if (relatedChild.length) throw new Error("Cannot delete record, other records depend on it"); @@ -8253,7 +8409,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { await Promise.all( IDBUtils.convertToArray(query.data.children.connect).map(async (connectWhere) => { await this.client.child.update( - { where: connectWhere, data: { fatherFirstName: record.firstName, fatherLastName: record.lastName } }, + { where: connectWhere, data: { fatherLastName: record.lastName, fatherFirstName: record.firstName } }, tx, ); }), @@ -8269,7 +8425,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { for (const elem of createData) { await this.client.child.create( { - data: { ...elem, fatherFirstName: record.firstName, fatherLastName: record.lastName } as Prisma.Args< + data: { ...elem, fatherLastName: record.lastName, fatherFirstName: record.firstName } as Prisma.Args< Prisma.ChildDelegate, "create" >["data"], @@ -8282,7 +8438,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { await Promise.all( IDBUtils.convertToArray(query.data.children.createMany.data).map(async (createData) => { await this.client.child.create( - { data: { ...createData, fatherFirstName: record.firstName, fatherLastName: record.lastName } }, + { data: { ...createData, fatherLastName: record.lastName, fatherFirstName: record.firstName } }, tx, ); }), @@ -8308,11 +8464,11 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { await this.client.child.upsert( { ...upsertData, - where: { ...upsertData.where, fatherFirstName: record.firstName, fatherLastName: record.lastName }, + where: { ...upsertData.where, fatherLastName: record.lastName, fatherFirstName: record.firstName }, create: { ...upsertData.create, - fatherFirstName: record.firstName, fatherLastName: record.lastName, + fatherFirstName: record.firstName, } as Prisma.Args["create"], }, tx, @@ -8324,7 +8480,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { await Promise.all( IDBUtils.convertToArray(query.data.children.delete).map(async (deleteData) => { await this.client.child.delete( - { where: { ...deleteData, fatherFirstName: record.firstName, fatherLastName: record.lastName } }, + { where: { ...deleteData, fatherLastName: record.lastName, fatherFirstName: record.firstName } }, tx, ); }), @@ -8334,7 +8490,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { await Promise.all( IDBUtils.convertToArray(query.data.children.deleteMany).map(async (deleteData) => { await this.client.child.deleteMany( - { where: { ...deleteData, fatherFirstName: record.firstName, fatherLastName: record.lastName } }, + { where: { ...deleteData, fatherLastName: record.lastName, fatherFirstName: record.firstName } }, tx, ); }), @@ -8342,7 +8498,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { } if (query.data.children.set) { const existing = await this.client.child.findMany( - { where: { fatherFirstName: record.firstName, fatherLastName: record.lastName } }, + { where: { fatherLastName: record.lastName, fatherFirstName: record.firstName } }, tx, ); if (existing.length > 0) { @@ -8351,7 +8507,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { await Promise.all( IDBUtils.convertToArray(query.data.children.set).map(async (setData) => { await this.client.child.update( - { where: setData, data: { fatherFirstName: record.firstName, fatherLastName: record.lastName } }, + { where: setData, data: { fatherLastName: record.lastName, fatherFirstName: record.firstName } }, tx, ); }), @@ -8376,7 +8532,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { where: { ...query.data.wife.update.where, firstName_lastName: { firstName: record.motherFirstName, lastName: record.motherLastName }, - }, + } as Prisma.MotherWhereUniqueInput, data: updateData, }, tx, @@ -8388,7 +8544,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { where: { ...query.data.wife.upsert.where, firstName_lastName: { firstName: record.motherFirstName, lastName: record.motherLastName }, - }, + } as Prisma.MotherWhereUniqueInput, create: { ...query.data.wife.upsert.create, firstName: record.motherFirstName!, @@ -8429,14 +8585,17 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { if (query.data.user.update) { const updateData = query.data.user.update.data ?? query.data.user.update; await this.client.user.update( - { where: { ...query.data.user.update.where, id: record.userId! }, data: updateData }, + { + where: { ...query.data.user.update.where, id: record.userId! } as Prisma.UserWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.user.upsert) { await this.client.user.upsert( { - where: { ...query.data.user.upsert.where, id: record.userId! }, + where: { ...query.data.user.upsert.where, id: record.userId! } as Prisma.UserWhereUniqueInput, create: { ...query.data.user.upsert.create, id: record.userId! } as Prisma.Args< Prisma.UserDelegate, "upsert" @@ -8468,7 +8627,7 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { record.userId = null; } } - if (query.data.motherFirstName !== undefined) { + if (query.data.motherFirstName !== undefined || query.data.motherLastName !== undefined) { const related = await this.client.mother.findUnique( { where: { firstName_lastName: { firstName: record.motherFirstName, lastName: record.motherLastName } } }, tx, @@ -8495,8 +8654,8 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { if (startKeyPath[i] !== endKeyPath[i]) { await this.client.child.updateMany( { - where: { fatherFirstName: startKeyPath[0], fatherLastName: startKeyPath[1] }, - data: { fatherFirstName: endKeyPath[0], fatherLastName: endKeyPath[1] }, + where: { fatherLastName: startKeyPath[1], fatherFirstName: startKeyPath[0] }, + data: { fatherLastName: endKeyPath[1], fatherFirstName: endKeyPath[0] }, }, tx, ); @@ -8578,6 +8737,38 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["userId"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const stringFields = ["firstName", "lastName", "motherFirstName", "motherLastName"] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["userId"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const stringFields = ["firstName", "lastName", "motherFirstName", "motherLastName"] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -8596,24 +8787,6 @@ class FatherIDBClass extends BaseIDBModelClass<"Father"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -8645,21 +8818,33 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { if (whereClause.children) { if (whereClause.children.every) { const violatingRecord = await this.client.child.findFirst({ - where: { NOT: { ...whereClause.children.every }, motherFirstName: record.firstName }, + where: { + NOT: { ...whereClause.children.every }, + motherFirstName: record.firstName, + motherLastName: record.lastName, + }, tx, }); if (violatingRecord !== null) return null; } if (whereClause.children.some) { const relatedRecords = await this.client.child.findMany({ - where: { ...whereClause.children.some, motherFirstName: record.firstName }, + where: { + ...whereClause.children.some, + motherFirstName: record.firstName, + motherLastName: record.lastName, + }, tx, }); if (relatedRecords.length === 0) return null; } if (whereClause.children.none) { const violatingRecord = await this.client.child.findFirst({ - where: { ...whereClause.children.none, motherFirstName: record.firstName }, + where: { + ...whereClause.children.none, + motherFirstName: record.firstName, + motherLastName: record.lastName, + }, tx, }); if (violatingRecord !== null) return null; @@ -8667,7 +8852,7 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { } if (whereClause.husband === null) { const relatedRecord = await this.client.father.findFirst( - { where: { motherFirstName: record.firstName } }, + { where: { motherFirstName: record.firstName, motherLastName: record.lastName } }, tx, ); if (relatedRecord) return null; @@ -8676,28 +8861,28 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { const { is, isNot, ...rest } = whereClause.husband; if (is === null) { const relatedRecord = await this.client.father.findFirst( - { where: { motherFirstName: record.firstName } }, + { where: { motherFirstName: record.firstName, motherLastName: record.lastName } }, tx, ); if (relatedRecord) return null; } if (is !== null && is !== undefined) { const relatedRecord = await this.client.father.findFirst( - { where: { ...is, motherFirstName: record.firstName } }, + { where: { ...is, motherFirstName: record.firstName, motherLastName: record.lastName } }, tx, ); if (!relatedRecord) return null; } if (isNot === null) { const relatedRecord = await this.client.father.findFirst( - { where: { motherFirstName: record.firstName } }, + { where: { motherFirstName: record.firstName, motherLastName: record.lastName } }, tx, ); if (!relatedRecord) return null; } if (isNot !== null && isNot !== undefined) { const relatedRecord = await this.client.father.findFirst( - { where: { ...isNot, motherFirstName: record.firstName } }, + { where: { ...isNot, motherFirstName: record.firstName, motherLastName: record.lastName } }, tx, ); if (relatedRecord) return null; @@ -8705,7 +8890,9 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { if (Object.keys(rest).length) { if (record.firstName === null) return null; const relatedRecord = await this.client.father.findFirst( - { where: { ...whereClause.husband, motherFirstName: record.firstName } }, + { + where: { ...whereClause.husband, motherFirstName: record.firstName, motherLastName: record.lastName }, + }, tx, ); if (!relatedRecord) return null; @@ -8777,7 +8964,7 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { unsafeRecord["children"] = await this.client.child.findMany( { ...(attach_children === true ? {} : attach_children), - where: { motherFirstName: record.firstName }, + where: { motherFirstName: record.firstName!, motherLastName: record.lastName! }, }, tx, ); @@ -8802,7 +8989,7 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { : await this.client.user.findUnique( { ...(attach_user === true ? {} : attach_user), - where: { id: record.userId }, + where: { id: record.userId! }, }, tx, ); @@ -8865,7 +9052,10 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { ); } if (orderByInput.children) { - return await this.client.child.count({ where: { motherFirstName: record.firstName } }, tx); + return await this.client.child.count( + { where: { motherFirstName: record.firstName, motherLastName: record.lastName } }, + tx, + ); } } @@ -9352,7 +9542,10 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { ); } if (query.data.husband?.connect) { - await this.client.father.update({ where: query.data.husband.connect, data: { motherFirstName: keyPath[0] } }, tx); + await this.client.father.update( + { where: query.data.husband.connect, data: { motherFirstName: keyPath[0], motherLastName: keyPath[1] } }, + tx, + ); } if (query.data.husband?.connectOrCreate) { if (query.data.husband?.connectOrCreate) { @@ -9738,14 +9931,17 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { if (query.data.user.update) { const updateData = query.data.user.update.data ?? query.data.user.update; await this.client.user.update( - { where: { ...query.data.user.update.where, id: record.userId! }, data: updateData }, + { + where: { ...query.data.user.update.where, id: record.userId! } as Prisma.UserWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.user.upsert) { await this.client.user.upsert( { - where: { ...query.data.user.upsert.where, id: record.userId! }, + where: { ...query.data.user.upsert.where, id: record.userId! } as Prisma.UserWhereUniqueInput, create: { ...query.data.user.upsert.create, id: record.userId! } as Prisma.Args< Prisma.UserDelegate, "upsert" @@ -9887,6 +10083,38 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["userId"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const stringFields = ["firstName", "lastName"] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["userId"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const stringFields = ["firstName", "lastName"] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -9905,24 +10133,6 @@ class MotherIDBClass extends BaseIDBModelClass<"Mother"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } @@ -9992,21 +10202,23 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { const { is, isNot, ...rest } = whereClause.father; if (is !== null && is !== undefined) { const relatedRecord = await this.client.father.findFirst( - { where: { ...is, firstName: record.fatherFirstName } }, + { where: { ...is, lastName: record.fatherLastName, firstName: record.fatherFirstName } }, tx, ); if (!relatedRecord) return null; } if (isNot !== null && isNot !== undefined) { const relatedRecord = await this.client.father.findFirst( - { where: { ...isNot, firstName: record.fatherFirstName } }, + { where: { ...isNot, lastName: record.fatherLastName, firstName: record.fatherFirstName } }, tx, ); if (relatedRecord) return null; } if (Object.keys(rest).length) { const relatedRecord = await this.client.father.findFirst( - { where: { ...whereClause.father, firstName: record.fatherFirstName } }, + { + where: { ...whereClause.father, lastName: record.fatherLastName, firstName: record.fatherFirstName }, + }, tx, ); if (!relatedRecord) return null; @@ -10016,21 +10228,23 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { const { is, isNot, ...rest } = whereClause.mother; if (is !== null && is !== undefined) { const relatedRecord = await this.client.mother.findFirst( - { where: { ...is, firstName: record.motherFirstName } }, + { where: { ...is, firstName: record.motherFirstName, lastName: record.motherLastName } }, tx, ); if (!relatedRecord) return null; } if (isNot !== null && isNot !== undefined) { const relatedRecord = await this.client.mother.findFirst( - { where: { ...isNot, firstName: record.motherFirstName } }, + { where: { ...isNot, firstName: record.motherFirstName, lastName: record.motherLastName } }, tx, ); if (relatedRecord) return null; } if (Object.keys(rest).length) { const relatedRecord = await this.client.mother.findFirst( - { where: { ...whereClause.mother, firstName: record.motherFirstName } }, + { + where: { ...whereClause.mother, firstName: record.motherFirstName, lastName: record.motherLastName }, + }, tx, ); if (!relatedRecord) return null; @@ -10086,7 +10300,7 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { : await this.client.user.findUnique( { ...(attach_user === true ? {} : attach_user), - where: { id: record.userId }, + where: { id: record.userId! }, }, tx, ); @@ -10096,7 +10310,7 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { unsafeRecord["father"] = await this.client.father.findUnique( { ...(attach_father === true ? {} : attach_father), - where: { firstName_lastName: { firstName: record.fatherFirstName, lastName: record.fatherLastName } }, + where: { firstName_lastName: { firstName: record.fatherFirstName!, lastName: record.fatherLastName! } }, }, tx, ); @@ -10106,7 +10320,7 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { unsafeRecord["mother"] = await this.client.mother.findUnique( { ...(attach_mother === true ? {} : attach_mother), - where: { firstName_lastName: { firstName: record.motherFirstName, lastName: record.motherLastName } }, + where: { firstName_lastName: { firstName: record.motherFirstName!, lastName: record.motherLastName! } }, }, tx, ); @@ -10169,7 +10383,7 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { } if (orderByInput.father) { return await this.client.father._resolveOrderByKey( - await this.client.father.findFirstOrThrow({ where: { firstName: record.fatherFirstName } }), + await this.client.father.findFirstOrThrow({ where: { lastName: record.fatherLastName } }), orderByInput.father, tx, ); @@ -10350,7 +10564,7 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { ); } } - if (data.fatherFirstName !== undefined) { + if (data.fatherLastName !== undefined) { neededStores.add("Father"); } if (data?.mother) { @@ -10692,13 +10906,13 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { fk[1] = record.lastName; } const unsafeData = query.data as Record; - unsafeData.fatherFirstName = fk[0]; unsafeData.fatherLastName = fk[1]; + unsafeData.fatherFirstName = fk[0]; delete unsafeData.father; - } else if (query.data?.fatherFirstName !== undefined && query.data.fatherFirstName !== null) { + } else if (query.data?.fatherLastName !== undefined && query.data.fatherLastName !== null) { await this.client.father.findUniqueOrThrow( { - where: { firstName_lastName: { firstName: query.data.fatherFirstName, lastName: query.data.fatherLastName } }, + where: { firstName_lastName: { lastName: query.data.fatherLastName, firstName: query.data.fatherFirstName } }, }, tx, ); @@ -10822,14 +11036,17 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { if (query.data.user.update) { const updateData = query.data.user.update.data ?? query.data.user.update; await this.client.user.update( - { where: { ...query.data.user.update.where, id: record.userId! }, data: updateData }, + { + where: { ...query.data.user.update.where, id: record.userId! } as Prisma.UserWhereUniqueInput, + data: updateData, + }, tx, ); } if (query.data.user.upsert) { await this.client.user.upsert( { - where: { ...query.data.user.upsert.where, id: record.userId! }, + where: { ...query.data.user.upsert.where, id: record.userId! } as Prisma.UserWhereUniqueInput, create: { ...query.data.user.upsert.create, id: record.userId! } as Prisma.Args< Prisma.UserDelegate, "upsert" @@ -10864,13 +11081,13 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { if (query.data.father) { if (query.data.father.connect) { const other = await this.client.father.findUniqueOrThrow({ where: query.data.father.connect }, tx); - record.fatherFirstName = other.firstName; record.fatherLastName = other.lastName; + record.fatherFirstName = other.firstName; } if (query.data.father.create) { const other = await this.client.father.create({ data: query.data.father.create }, tx); - record.fatherFirstName = other.firstName; record.fatherLastName = other.lastName; + record.fatherFirstName = other.firstName; } if (query.data.father.update) { const updateData = query.data.father.update.data ?? query.data.father.update; @@ -10878,8 +11095,8 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { { where: { ...query.data.father.update.where, - firstName_lastName: { firstName: record.fatherFirstName, lastName: record.fatherLastName }, - }, + firstName_lastName: { lastName: record.fatherLastName, firstName: record.fatherFirstName }, + } as Prisma.FatherWhereUniqueInput, data: updateData, }, tx, @@ -10890,12 +11107,12 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { { where: { ...query.data.father.upsert.where, - firstName_lastName: { firstName: record.fatherFirstName, lastName: record.fatherLastName }, - }, + firstName_lastName: { lastName: record.fatherLastName, firstName: record.fatherFirstName }, + } as Prisma.FatherWhereUniqueInput, create: { ...query.data.father.upsert.create, - firstName: record.fatherFirstName!, lastName: record.fatherLastName!, + firstName: record.fatherFirstName!, } as Prisma.Args["create"], update: query.data.father.upsert.update, }, @@ -10907,14 +11124,14 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { { where: { ...query.data.father.connectOrCreate.where, - firstName_lastName: { firstName: record.fatherFirstName, lastName: record.fatherLastName }, + firstName_lastName: { lastName: record.fatherLastName, firstName: record.fatherFirstName }, }, create: { ...query.data.father.connectOrCreate.create, - firstName: record.fatherFirstName!, lastName: record.fatherLastName!, + firstName: record.fatherFirstName!, } as Prisma.Args["create"], - update: { firstName: record.fatherFirstName!, lastName: record.fatherLastName! }, + update: { lastName: record.fatherLastName!, firstName: record.fatherFirstName! }, }, tx, ); @@ -10938,7 +11155,7 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { where: { ...query.data.mother.update.where, firstName_lastName: { firstName: record.motherFirstName, lastName: record.motherLastName }, - }, + } as Prisma.MotherWhereUniqueInput, data: updateData, }, tx, @@ -10950,7 +11167,7 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { where: { ...query.data.mother.upsert.where, firstName_lastName: { firstName: record.motherFirstName, lastName: record.motherLastName }, - }, + } as Prisma.MotherWhereUniqueInput, create: { ...query.data.mother.upsert.create, firstName: record.motherFirstName!, @@ -10983,14 +11200,14 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { const related = await this.client.user.findUnique({ where: { id: record.userId } }, tx); if (!related) throw new Error("Related record not found"); } - if (query.data.fatherFirstName !== undefined) { + if (query.data.fatherLastName !== undefined || query.data.fatherFirstName !== undefined) { const related = await this.client.father.findUnique( { where: { firstName_lastName: { firstName: record.fatherFirstName, lastName: record.fatherLastName } } }, tx, ); if (!related) throw new Error("Related record not found"); } - if (query.data.motherFirstName !== undefined) { + if (query.data.motherFirstName !== undefined || query.data.motherLastName !== undefined) { const related = await this.client.mother.findUnique( { where: { firstName_lastName: { firstName: record.motherFirstName, lastName: record.motherLastName } } }, tx, @@ -11096,6 +11313,52 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { } } } + if (query?._min) { + const minResult = {} as Prisma.Result["_min"]; + const numericFields = ["userId"] as const; + for (const field of numericFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as number) = Math.min(...values); + } + const stringFields = [ + "childFirstName", + "childLastName", + "fatherFirstName", + "fatherLastName", + "motherFirstName", + "motherLastName", + ] as const; + for (const field of stringFields) { + if (!query._min[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (minResult[field as keyof typeof minResult] as string) = values.sort()[0]; + } + result._min = minResult; + } + if (query?._max) { + const maxResult = {} as Prisma.Result["_max"]; + const numericFields = ["userId"] as const; + for (const field of numericFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as number).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); + } + const stringFields = [ + "childFirstName", + "childLastName", + "fatherFirstName", + "fatherLastName", + "motherFirstName", + "motherLastName", + ] as const; + for (const field of stringFields) { + if (!query._max[field]) continue; + const values = records.map((record) => record[field] as string).filter((value) => value !== undefined); + (maxResult[field as keyof typeof maxResult] as string) = values.sort().reverse()[0]; + } + result._max = maxResult; + } if (query?._avg) { const avgResult = {} as Prisma.Result["_avg"]; for (const untypedField of Object.keys(query._avg)) { @@ -11114,24 +11377,6 @@ class ChildIDBClass extends BaseIDBModelClass<"Child"> { } result._sum = sumResult; } - if (query?._min) { - const minResult = {} as Prisma.Result["_min"]; - for (const untypedField of Object.keys(query._min)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (minResult[field as keyof typeof minResult] as number) = Math.min(...values); - } - result._min = minResult; - } - if (query?._max) { - const maxResult = {} as Prisma.Result["_max"]; - for (const untypedField of Object.keys(query._max)) { - const field = untypedField as keyof (typeof records)[number]; - const values = records.map((record) => record[field] as number); - (maxResult[field as keyof typeof maxResult] as number) = Math.max(...values); - } - result._max = maxResult; - } return result as unknown as Prisma.Result; } } diff --git a/packages/usage/src/prisma/schema.prisma b/packages/usage/src/prisma/schema.prisma index cf3f045..f74af1a 100644 --- a/packages/usage/src/prisma/schema.prisma +++ b/packages/usage/src/prisma/schema.prisma @@ -120,7 +120,7 @@ model Child { motherLastName String user User? @relation(fields: [userId], references: [id]) - father Father @relation(fields: [fatherFirstName, fatherLastName], references: [firstName, lastName]) + father Father @relation(fields: [fatherLastName, fatherFirstName], references: [lastName, firstName]) mother Mother @relation(fields: [motherFirstName, motherLastName], references: [firstName, lastName]) userId Int?