@prisma/orm-family-sql 8.0.0-rc.22-dev.9 → 8.0.0-rc.22-dev.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ast-1JRQY-dP.d.mts → ast-BopvCTVF.d.mts} +2 -2
- package/dist/{ast-1JRQY-dP.d.mts.map → ast-BopvCTVF.d.mts.map} +1 -1
- package/dist/builder.d.mts +3 -3
- package/dist/builder__runtime.d.mts +7 -7
- package/dist/builder__types.d.mts +5 -5
- package/dist/{collection-methods-D9CYfePl-BGvD1h9Z.d.mts → collection-methods-B82cPkgc-DY10b2Cq.d.mts} +3 -3
- package/dist/{collection-methods-D9CYfePl-BGvD1h9Z.d.mts.map → collection-methods-B82cPkgc-DY10b2Cq.d.mts.map} +1 -1
- package/dist/collection-methods-Bmr-a58b.d.mts +1 -0
- package/dist/{control-CyJM0mMS.d.mts → control-DBsrhNV2.d.mts} +5 -5
- package/dist/{control-CyJM0mMS.d.mts.map → control-DBsrhNV2.d.mts.map} +1 -1
- package/dist/{control-adapter-BfyLe7rh-CiGzw3dq.d.mts → control-adapter-BfyLe7rh-DSiEx96z.d.mts} +3 -3
- package/dist/{control-adapter-BfyLe7rh-CiGzw3dq.d.mts.map → control-adapter-BfyLe7rh-DSiEx96z.d.mts.map} +1 -1
- package/dist/{control-adapter-BlBhW0pc.d.mts → control-adapter-xJwgaSsO.d.mts} +2 -2
- package/dist/{control-adapter-BlBhW0pc.d.mts.map → control-adapter-xJwgaSsO.d.mts.map} +1 -1
- package/dist/{db-D1d75IvM-C1lqD6a2.d.mts → db-D1d75IvM-C88quYVJ.d.mts} +7 -7
- package/dist/{db-D1d75IvM-C1lqD6a2.d.mts.map → db-D1d75IvM-C88quYVJ.d.mts.map} +1 -1
- package/dist/{diff-BlX_rfVG.d.mts → diff-bSfcDUpu.d.mts} +2 -2
- package/dist/{diff-BlX_rfVG.d.mts.map → diff-bSfcDUpu.d.mts.map} +1 -1
- package/dist/{driver-types-DRsYeq3j-BimeCnUk.d.mts → driver-types-Bobm0hWv-B9rTP8XQ.d.mts} +6 -2
- package/dist/driver-types-Bobm0hWv-B9rTP8XQ.d.mts.map +1 -0
- package/dist/{expression-C3F6gxZH-EOb5cRCY.d.mts → expression-4Y1d1hJ_-p9KkcaqT.d.mts} +3 -3
- package/dist/{expression-C3F6gxZH-EOb5cRCY.d.mts.map → expression-4Y1d1hJ_-p9KkcaqT.d.mts.map} +1 -1
- package/dist/expression-BV_SJGPu.d.mts +2 -0
- package/dist/{expression-BWRsWR6O-HbWL9x9D.d.mts → expression-DGu7PRyk-Do_Q7JGF.d.mts} +3 -3
- package/dist/expression-DGu7PRyk-Do_Q7JGF.d.mts.map +1 -0
- package/dist/family.d.mts +6 -6
- package/dist/family__control-adapter.d.mts +2 -2
- package/dist/family__control.d.mts +2 -2
- package/dist/family__diff.d.mts +1 -1
- package/dist/family__migration.d.mts +1 -1
- package/dist/{functions-PBSwFhni.d.mts → functions-LZT-hFcE.d.mts} +2 -2
- package/dist/{functions-PBSwFhni.d.mts.map → functions-LZT-hFcE.d.mts.map} +1 -1
- package/dist/{index-DIgcTq1L.d.mts → index-2YUqocwr.d.mts} +12 -12
- package/dist/{index-DIgcTq1L.d.mts.map → index-2YUqocwr.d.mts.map} +1 -1
- package/dist/{index-reference-YHvh6wAL-BupQRpkE.d.mts → index-reference--2lpz6Um-CtLxcswa.d.mts} +3 -3
- package/dist/{index-reference-YHvh6wAL-BupQRpkE.d.mts.map → index-reference--2lpz6Um-CtLxcswa.d.mts.map} +1 -1
- package/dist/index-reference-BPcC09GP.d.mts +1 -0
- package/dist/{migration-B35kGD-7.d.mts → migration-OXM3LDdT.d.mts} +2 -2
- package/dist/{migration-B35kGD-7.d.mts.map → migration-OXM3LDdT.d.mts.map} +1 -1
- package/dist/orm-client.d.mts +14 -14
- package/dist/orm-client.mjs +387 -44
- package/dist/orm-client.mjs.map +1 -1
- package/dist/query-lane-context-D0Yc3E72.d.mts +1 -0
- package/dist/{query-lane-context-DLSXDsDK-CGSahS15.d.mts → query-lane-context-vp4wQJQD-DNtizzS5.d.mts} +4 -4
- package/dist/{query-lane-context-DLSXDsDK-CGSahS15.d.mts.map → query-lane-context-vp4wQJQD-DNtizzS5.d.mts.map} +1 -1
- package/dist/relational-core.d.mts +7 -7
- package/dist/relational-core__aggregate-descriptor-registry.d.mts +1 -1
- package/dist/relational-core__ast.d.mts +2 -2
- package/dist/relational-core__codec-descriptor-registry.d.mts +1 -1
- package/dist/relational-core__collection-methods.d.mts +2 -2
- package/dist/relational-core__expression.d.mts +3 -3
- package/dist/relational-core__functions.d.mts +1 -1
- package/dist/relational-core__index-reference.d.mts +2 -2
- package/dist/relational-core__query-lane-context.d.mts +2 -2
- package/dist/relational-core__types.d.mts +2 -2
- package/dist/runtime.d.mts +4 -4
- package/dist/runtime__internal__prepared-query.d.mts +1 -1
- package/dist/{transaction-state-DR3nKTmH-C3wq6dCB.d.mts → transaction-state-DR3nKTmH-Bs2EUG8r.d.mts} +7 -7
- package/dist/{transaction-state-DR3nKTmH-C3wq6dCB.d.mts.map → transaction-state-DR3nKTmH-Bs2EUG8r.d.mts.map} +1 -1
- package/dist/types-B62vy44g.d.mts +1 -0
- package/dist/{types-COXfSNOP-D9vt9QDL.d.mts → types-COXfSNOP-BKkP-EG1.d.mts} +2 -2
- package/dist/{types-COXfSNOP-D9vt9QDL.d.mts.map → types-COXfSNOP-BKkP-EG1.d.mts.map} +1 -1
- package/dist/{types-NgqqVAo5-CJG02ILZ.d.mts → types-DiPbLKXV-BFa2YXa4.d.mts} +4 -4
- package/dist/{types-NgqqVAo5-CJG02ILZ.d.mts.map → types-DiPbLKXV-BFa2YXa4.d.mts.map} +1 -1
- package/package.json +18 -18
- package/dist/collection-methods-mo-2RjdX.d.mts +0 -1
- package/dist/driver-types-DRsYeq3j-BimeCnUk.d.mts.map +0 -1
- package/dist/expression-BWRsWR6O-HbWL9x9D.d.mts.map +0 -1
- package/dist/expression-OVCWlXHm.d.mts +0 -2
- package/dist/index-reference-D3p5ziNG.d.mts +0 -1
- package/dist/query-lane-context-DL6bwl6k.d.mts +0 -1
- package/dist/types-DIoM5Ft3.d.mts +0 -1
package/dist/orm-client.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as resolveStorageTable } from "./resolve-storage-table-BHLQsOza.mjs";
|
|
2
2
|
import { i as isUniqueConstraintViolation } from "./dist-CB2NpcCs.mjs";
|
|
3
|
-
import { A as ParamRef, C as LiteralExpr, E as NullCheckExpr, F as SelectAst, G as isOrderByNulls, I as SubqueryExpr, L as TableSource, M as ProjectionItem, O as OrExpr, R as UpdateAst, S as ListExpression, T as NotExpr, U as isAggregateFn, V as checkLimitOffset, W as isOrderByDirection, _ as InsertAst, b as JsonArrayAggExpr, c as DeleteAst, f as EqColJoinOn, k as OrderByItem, l as DerivedTableSource, n as AndExpr, o as ColumnRef, p as ExistsExpr, q as isWhereExpr, r as BinaryExpr, s as DefaultValueExpr, t as AggregateExpr, v as InsertOnConflict, w as LockingClause, x as JsonObjectExpr, y as JoinAst, z as WindowFuncExpr } from "./types-BkTuhW3Z-BJfTjcxS.mjs";
|
|
3
|
+
import { A as ParamRef, C as LiteralExpr, E as NullCheckExpr, F as SelectAst, G as isOrderByNulls, I as SubqueryExpr, L as TableSource, M as ProjectionItem, O as OrExpr, R as UpdateAst, S as ListExpression, T as NotExpr, U as isAggregateFn, V as checkLimitOffset, W as isOrderByDirection, _ as InsertAst, b as JsonArrayAggExpr, c as DeleteAst, f as EqColJoinOn, i as CaseExpr, k as OrderByItem, l as DerivedTableSource, n as AndExpr, o as ColumnRef, p as ExistsExpr, q as isWhereExpr, r as BinaryExpr, s as DefaultValueExpr, t as AggregateExpr, v as InsertOnConflict, w as LockingClause, x as JsonObjectExpr, y as JoinAst, z as WindowFuncExpr } from "./types-BkTuhW3Z-BJfTjcxS.mjs";
|
|
4
4
|
import { t as collectOrderedParamRefs } from "./util-DixeJBri-Cad7x5ec.mjs";
|
|
5
5
|
import { D as lockWaitPolicyOf, E as lockStrengthCapabilities, O as missingCapability, T as lockOptionCapabilities, n as JsonDocumentProjection, r as NativeJsonValueProjection, t as CodecJsonValueProjection, w as lockIncompatible } from "./ast-C3itulLi.mjs";
|
|
6
6
|
import { a as isExpression, s as toExpr, t as ExpressionImpl } from "./expression-impl-DtbmFnnz-Dal0IYDE.mjs";
|
|
@@ -539,6 +539,11 @@ function hasCompleteUniqueKey(contract, namespaceId, modelName, criterion) {
|
|
|
539
539
|
}
|
|
540
540
|
return resolveUniqueKeyColumnSets(contract, namespaceId, tableName).some((columns) => columns.every((column) => columnsWithValue.has(column)));
|
|
541
541
|
}
|
|
542
|
+
/** Whether the contract gives the column an `autoincrement()` default, so the database numbers its value itself. */
|
|
543
|
+
function isAutoIncrementColumn(contract, namespaceId, tableName, column) {
|
|
544
|
+
const columnDefault = storageTableForContract(contract, namespaceId, tableName).columns[column]?.default;
|
|
545
|
+
return columnDefault?.kind === "function" && columnDefault.expression === "autoincrement()";
|
|
546
|
+
}
|
|
542
547
|
function assertReturningCapability(contract, action) {
|
|
543
548
|
if (hasContractCapability(contract, "returning")) return;
|
|
544
549
|
throw ormError("ORM.CAPABILITY_MISSING", `${action} requires contract capability "returning"`, { meta: {
|
|
@@ -548,7 +553,7 @@ function assertReturningCapability(contract, action) {
|
|
|
548
553
|
}
|
|
549
554
|
function assertInsertConflictSkipCapability(contract, action, targeted) {
|
|
550
555
|
requireCapability(contract, action, "insertOnConflictSkip");
|
|
551
|
-
|
|
556
|
+
requireCapability(contract, action, targeted ? "insertOnConflictTarget" : "insertOnConflictWithoutTarget");
|
|
552
557
|
}
|
|
553
558
|
function requireCapability(contract, action, capability) {
|
|
554
559
|
if (hasContractCapability(contract, capability)) return;
|
|
@@ -4362,6 +4367,57 @@ function isRelationMutationDescriptor(value) {
|
|
|
4362
4367
|
function isRelationMutationCallback(value) {
|
|
4363
4368
|
return typeof value === "function";
|
|
4364
4369
|
}
|
|
4370
|
+
/**
|
|
4371
|
+
* The key of each row an insert writes, for reading the rows back without `RETURNING`: the values the client supplies, and at most one auto-increment column, whose value the database reports only for a one-row insert. Refuses, before anything runs, an insert whose rows cannot be found this way.
|
|
4372
|
+
*/
|
|
4373
|
+
function writtenKeys(options) {
|
|
4374
|
+
const { context, namespaceId, tableName, modelName, rows, method } = options;
|
|
4375
|
+
const identity = readBackIdentity(context.contract, namespaceId, tableName, modelName, method);
|
|
4376
|
+
const supplied = identity.filter((column) => rows.every((row) => row[column] !== void 0));
|
|
4377
|
+
const keys = rows.map((row) => Object.fromEntries(supplied.map((column) => [column, row[column]])));
|
|
4378
|
+
const [column, ...others] = identity.filter((key) => !supplied.includes(key));
|
|
4379
|
+
if (column === void 0) return {
|
|
4380
|
+
keys,
|
|
4381
|
+
generated: void 0
|
|
4382
|
+
};
|
|
4383
|
+
const refused = (problem) => ormError("ORM.CAPABILITY_MISSING", `${method} on model "${modelName}" ${problem}`, { meta: {
|
|
4384
|
+
capability: "returning",
|
|
4385
|
+
action: method
|
|
4386
|
+
} });
|
|
4387
|
+
if (others.length > 0 || !isAutoIncrementColumn(context.contract, namespaceId, tableName, column)) throw refused(`cannot find the row it inserts: key column "${[column, ...others].join("\", \"")}" gets no value from the client and is not an auto-increment column, and the contract does not report capability "returning" to read the value the database chose. Supply the key, or give the column a client-side default.`);
|
|
4388
|
+
if (rows.length > 1) throw refused(`cannot return the rows it inserts: their key column "${column}" is generated, and without capability "returning" the database reports a generated value only for a one-row insert. Use createAndCount(), or create() for each row.`);
|
|
4389
|
+
const codec = context.contractCodecs.forColumn(namespaceId, tableName, column);
|
|
4390
|
+
return {
|
|
4391
|
+
keys,
|
|
4392
|
+
generated: {
|
|
4393
|
+
column,
|
|
4394
|
+
decode: async (insertId) => codec === void 0 ? insertId : codec.fromWire(insertId, { column: {
|
|
4395
|
+
table: tableName,
|
|
4396
|
+
name: column
|
|
4397
|
+
} })
|
|
4398
|
+
}
|
|
4399
|
+
};
|
|
4400
|
+
}
|
|
4401
|
+
/** The columns a write without `RETURNING` reads its rows back by: the table's row identity, which it must have. */
|
|
4402
|
+
function readBackIdentity(contract, namespaceId, tableName, modelName, method) {
|
|
4403
|
+
const identity = resolveRowIdentityColumns(contract, namespaceId, tableName);
|
|
4404
|
+
if (identity.length > 0) return identity;
|
|
4405
|
+
throw ormError("ORM.ROW_IDENTITY_MISSING", `${method} on model "${modelName}" reads the rows it wrote back by key, since the contract does not report capability "returning", so table "${tableName}" needs a primary key or unique constraint`, { meta: {
|
|
4406
|
+
model: modelName,
|
|
4407
|
+
table: tableName
|
|
4408
|
+
} });
|
|
4409
|
+
}
|
|
4410
|
+
/** The `insertId` a one-row insert reported, or the error that it reported none, which a middleware answering the statement may cause. */
|
|
4411
|
+
function reportedInsertId(stats, generated, owner) {
|
|
4412
|
+
if (stats.affectedRows === 1 && stats.insertId !== void 0) return stats.insertId;
|
|
4413
|
+
throw ormError("ORM.MUTATION_ROW_MISSING", `${owner.operation}() for model "${owner.modelName}" cannot find the row it inserted: the insert's result carried no insert id for key column "${generated.column}". A middleware may have answered the statement in place of the database without one.`, { meta: {
|
|
4414
|
+
operation: owner.operation,
|
|
4415
|
+
model: owner.modelName,
|
|
4416
|
+
phase: "insert-id",
|
|
4417
|
+
column: generated.column,
|
|
4418
|
+
affectedRows: stats.affectedRows
|
|
4419
|
+
} });
|
|
4420
|
+
}
|
|
4365
4421
|
function hasThrough(relation) {
|
|
4366
4422
|
return relation.through !== void 0;
|
|
4367
4423
|
}
|
|
@@ -4374,11 +4430,56 @@ function hasNestedMutationCallbacks(contract, namespaceId, modelName, data) {
|
|
|
4374
4430
|
return false;
|
|
4375
4431
|
}
|
|
4376
4432
|
async function executeNestedCreateMutation(options) {
|
|
4433
|
+
refuseUnreadableCreate(options.context, options.namespaceId, options.modelName, options.data, []);
|
|
4377
4434
|
return withMutationScope(options.runtime, async (scope) => createGraph(scope, options.context, options.namespaceId, options.modelName, options.data));
|
|
4378
4435
|
}
|
|
4379
4436
|
async function executeNestedUpdateMutation(options) {
|
|
4437
|
+
const { context, namespaceId, modelName, data } = options;
|
|
4438
|
+
if (!hasContractCapability(context.contract, "returning")) refuseUnreadableRelatedCreates(context, parseMutationInput(context.contract, namespaceId, modelName, data).relationMutations);
|
|
4380
4439
|
return withMutationScope(options.runtime, async (scope) => updateFirstGraph$1(scope, options.context, options.namespaceId, options.modelName, options.tables, options.filters, options.data));
|
|
4381
4440
|
}
|
|
4441
|
+
/**
|
|
4442
|
+
* Without `RETURNING`, each row a nested create inserts is read back by its key. This refuses, before anything runs, a create whose rows could not be found that way: the key values each row gets from its input, a client-side default, or the row it relates to must leave out at most the table's auto-increment column.
|
|
4443
|
+
*/
|
|
4444
|
+
function refuseUnreadableCreate(context, namespaceId, modelName, input, suppliedColumns) {
|
|
4445
|
+
const contract = context.contract;
|
|
4446
|
+
if (hasContractCapability(contract, "returning")) return;
|
|
4447
|
+
const { scalarData, relationMutations } = parseMutationInput(contract, namespaceId, modelName, input);
|
|
4448
|
+
const tableName = resolveModelTableName(contract, namespaceId, modelName);
|
|
4449
|
+
const row = mapModelDataToStorageRow(contract, namespaceId, modelName, scalarData);
|
|
4450
|
+
const defaults = context.applyMutationDefaults({
|
|
4451
|
+
op: "create",
|
|
4452
|
+
entry: tableName,
|
|
4453
|
+
namespace: namespaceId,
|
|
4454
|
+
values: { ...row }
|
|
4455
|
+
});
|
|
4456
|
+
const supplied = [
|
|
4457
|
+
...suppliedColumns,
|
|
4458
|
+
...defaults.map((applied) => applied.field),
|
|
4459
|
+
...partitionByOwnership(relationMutations).parentOwned.flatMap(({ relation }) => relation.localColumns)
|
|
4460
|
+
];
|
|
4461
|
+
writtenKeys({
|
|
4462
|
+
context,
|
|
4463
|
+
namespaceId,
|
|
4464
|
+
tableName,
|
|
4465
|
+
modelName,
|
|
4466
|
+
rows: [{
|
|
4467
|
+
...Object.fromEntries(supplied.map((column) => [column, true])),
|
|
4468
|
+
...row
|
|
4469
|
+
}],
|
|
4470
|
+
method: "create()"
|
|
4471
|
+
});
|
|
4472
|
+
refuseUnreadableRelatedCreates(context, relationMutations);
|
|
4473
|
+
}
|
|
4474
|
+
function refuseUnreadableRelatedCreates(context, relationMutations) {
|
|
4475
|
+
const { parentOwned, childOwned } = partitionByOwnership(relationMutations);
|
|
4476
|
+
for (const { relation, mutation } of relationMutations) {
|
|
4477
|
+
if (mutation.kind !== "create") continue;
|
|
4478
|
+
const fromParent = childOwned.some((owned) => owned.relation === relation) ? relation.targetColumns : [];
|
|
4479
|
+
const createsOne = parentOwned.some((owned) => owned.relation === relation);
|
|
4480
|
+
for (const childInput of createsOne ? mutation.data.slice(0, 1) : mutation.data) refuseUnreadableCreate(context, relation.relatedNamespaceId, relation.relatedModelName, castAs(childInput), fromParent);
|
|
4481
|
+
}
|
|
4482
|
+
}
|
|
4382
4483
|
function buildRowIdentityFilterFromRow(contract, namespaceId, modelName, row) {
|
|
4383
4484
|
const tableName = resolveModelTableName(contract, namespaceId, modelName);
|
|
4384
4485
|
const identityColumns = resolveRowIdentityColumns(contract, namespaceId, tableName);
|
|
@@ -4474,10 +4575,18 @@ async function updateFirstGraph$1(scope, context, namespaceId, modelName, tables
|
|
|
4474
4575
|
values: mappedUpdateData
|
|
4475
4576
|
});
|
|
4476
4577
|
for (const def of appliedUpdateDefaults) mappedUpdateData[def.field] = def.value;
|
|
4477
|
-
const
|
|
4578
|
+
const identityFilter = buildRowIdentityFilterFromRow(contract, namespaceId, modelName, existingRow);
|
|
4579
|
+
const identityWhere = shorthandToWhereExpr(context, namespaceId, modelName, castAs(identityFilter), tables.root);
|
|
4478
4580
|
if (!identityWhere) throw new InternalError(`Failed to build row identity filter for model "${modelName}"`);
|
|
4479
|
-
|
|
4480
|
-
|
|
4581
|
+
if (hasContractCapability(contract, "returning")) {
|
|
4582
|
+
const updatedRaw = (await queryPlanRows(scope, compileUpdateReturning(contract, modelName, tables, mappedUpdateData, [identityWhere], void 0)).toArray())[0];
|
|
4583
|
+
if (updatedRaw) parentRow = mapStorageRowToModelFields(contract, namespaceId, modelName, updatedRaw);
|
|
4584
|
+
} else {
|
|
4585
|
+
await scope.execute(compileUpdateCount(contract, tables, mappedUpdateData, [identityWhere]));
|
|
4586
|
+
const updatedIdentity = { ...identityFilter };
|
|
4587
|
+
for (const column of readBackIdentity(contract, namespaceId, tableName, modelName, "update()")) if (Object.hasOwn(mappedUpdateData, column)) updatedIdentity[toFieldName(contract, namespaceId, modelName, column)] = mappedUpdateData[column];
|
|
4588
|
+
parentRow = await findRowByCriterion(scope, context, namespaceId, modelName, updatedIdentity) ?? parentRow;
|
|
4589
|
+
}
|
|
4481
4590
|
}
|
|
4482
4591
|
for (const relationMutation of childOwned) await applyChildOwnedMutation(scope, context, namespaceId, modelName, parentRow, relationMutation.relation, relationMutation.mutation);
|
|
4483
4592
|
for (const relationMutation of junctionOwned) await applyJunctionOwnedMutation(scope, context, namespaceId, modelName, parentRow, relationMutation.relation, relationMutation.mutation);
|
|
@@ -4810,6 +4919,7 @@ async function insertSingleRow(scope, context, namespaceId, modelName, data) {
|
|
|
4810
4919
|
values: mappedData
|
|
4811
4920
|
});
|
|
4812
4921
|
for (const def of applied) mappedData[def.field] = def.value;
|
|
4922
|
+
if (!hasContractCapability(contract, "returning")) return insertAndReadBack(scope, context, namespaceId, modelName, tableName, mappedData);
|
|
4813
4923
|
const firstRow = (await queryPlanRows(scope, compileInsertReturning(contract, namespaceId, modelName, tableName, [mappedData], void 0)).toArray())[0];
|
|
4814
4924
|
if (!firstRow) throw ormError("ORM.MUTATION_ROW_MISSING", `Nested create for model "${modelName}" did not return a row`, { meta: {
|
|
4815
4925
|
operation: "create",
|
|
@@ -4818,6 +4928,32 @@ async function insertSingleRow(scope, context, namespaceId, modelName, data) {
|
|
|
4818
4928
|
} });
|
|
4819
4929
|
return mapStorageRowToModelFields(contract, namespaceId, modelName, firstRow);
|
|
4820
4930
|
}
|
|
4931
|
+
async function insertAndReadBack(scope, context, namespaceId, modelName, tableName, row) {
|
|
4932
|
+
const contract = context.contract;
|
|
4933
|
+
const { keys: [suppliedKey = {}], generated } = writtenKeys({
|
|
4934
|
+
context,
|
|
4935
|
+
namespaceId,
|
|
4936
|
+
tableName,
|
|
4937
|
+
modelName,
|
|
4938
|
+
rows: [row],
|
|
4939
|
+
method: "create()"
|
|
4940
|
+
});
|
|
4941
|
+
const stats = await scope.execute(compileInsertCount(contract, namespaceId, tableName, [row]));
|
|
4942
|
+
const key = generated === void 0 ? suppliedKey : {
|
|
4943
|
+
...suppliedKey,
|
|
4944
|
+
[generated.column]: await generated.decode(reportedInsertId(stats, generated, {
|
|
4945
|
+
operation: "create",
|
|
4946
|
+
modelName
|
|
4947
|
+
}))
|
|
4948
|
+
};
|
|
4949
|
+
const created = await findRowByCriterion(scope, context, namespaceId, modelName, Object.fromEntries(Object.entries(key).map(([column, value]) => [toFieldName(contract, namespaceId, modelName, column), value])));
|
|
4950
|
+
if (!created) throw ormError("ORM.MUTATION_ROW_MISSING", `Nested create for model "${modelName}" did not find the row it inserted`, { meta: {
|
|
4951
|
+
operation: "create",
|
|
4952
|
+
model: modelName,
|
|
4953
|
+
phase: "nested"
|
|
4954
|
+
} });
|
|
4955
|
+
return created;
|
|
4956
|
+
}
|
|
4821
4957
|
async function findRowByCriterion(scope, context, namespaceId, modelName, criterion) {
|
|
4822
4958
|
const contract = context.contract;
|
|
4823
4959
|
const tables = createStatementTables({
|
|
@@ -4916,9 +5052,21 @@ function executeFiltered(ast, filter, run) {
|
|
|
4916
5052
|
const where = combineWhereExprs([...ast.where === void 0 ? [] : [ast.where], ...filter.map(anyOf)]);
|
|
4917
5053
|
return executeStatement$1(ast.withWhere(where), run);
|
|
4918
5054
|
}
|
|
5055
|
+
/** Any of the conditions: an `IN` list when each compares the same column with a parameter, else an `OR`. */
|
|
4919
5056
|
function anyOf(conditions) {
|
|
4920
5057
|
const [first, ...others] = conditions;
|
|
4921
|
-
|
|
5058
|
+
if (first !== void 0 && others.length === 0) return first;
|
|
5059
|
+
const column = sharedColumn(conditions);
|
|
5060
|
+
return column === void 0 ? OrExpr.of(conditions) : BinaryExpr.in(column, ListExpression.of(conditions.flatMap((condition) => isParamEq(condition) ? [condition.right] : [])));
|
|
5061
|
+
}
|
|
5062
|
+
function isParamEq(condition) {
|
|
5063
|
+
return condition.kind === "binary" && condition.op === "eq" && condition.left.kind === "column-ref" && condition.right.kind === "param-ref";
|
|
5064
|
+
}
|
|
5065
|
+
function sharedColumn(conditions) {
|
|
5066
|
+
const [first] = conditions;
|
|
5067
|
+
if (first === void 0 || !isParamEq(first)) return void 0;
|
|
5068
|
+
const { table, column } = first.left;
|
|
5069
|
+
return conditions.every((condition) => isParamEq(condition) && condition.left.table === table && condition.left.column === column) ? first.left : void 0;
|
|
4922
5070
|
}
|
|
4923
5071
|
function withColumns(returned, columns) {
|
|
4924
5072
|
const present = new Set(returned.map((item) => item.alias));
|
|
@@ -4950,18 +5098,28 @@ var Edge = class {
|
|
|
4950
5098
|
this.columns = Object.freeze([...columns]);
|
|
4951
5099
|
}
|
|
4952
5100
|
};
|
|
5101
|
+
/** The condition that matches the row whose source columns hold the values in `sourceRow`. */
|
|
5102
|
+
function keyCondition(columns, sourceRow) {
|
|
5103
|
+
const conditions = columns.map(([source, target]) => BinaryExpr.eq(target.expr, ParamRef.of(sourceRow[source.alias], {
|
|
5104
|
+
name: target.alias,
|
|
5105
|
+
...ifDefined("codec", target.codec)
|
|
5106
|
+
})));
|
|
5107
|
+
const [first, ...others] = conditions;
|
|
5108
|
+
return first !== void 0 && others.length === 0 ? first : AndExpr.of(conditions);
|
|
5109
|
+
}
|
|
5110
|
+
/** Matches each source row's row in the reading statement. `changed` holds new values, by source column, that a write between the two gave every row. */
|
|
4953
5111
|
var FilterData = class extends Edge {
|
|
4954
|
-
|
|
5112
|
+
changed;
|
|
5113
|
+
constructor(from, columns, changed = {}) {
|
|
4955
5114
|
super(from, columns);
|
|
5115
|
+
this.changed = changed;
|
|
4956
5116
|
Object.freeze(this);
|
|
4957
5117
|
}
|
|
4958
5118
|
output(sourceRow) {
|
|
4959
|
-
|
|
4960
|
-
|
|
4961
|
-
...
|
|
4962
|
-
})
|
|
4963
|
-
const [first, ...others] = conditions;
|
|
4964
|
-
return first !== void 0 && others.length === 0 ? first : AndExpr.of(conditions);
|
|
5119
|
+
return keyCondition(this.columns, {
|
|
5120
|
+
...sourceRow,
|
|
5121
|
+
...this.changed
|
|
5122
|
+
});
|
|
4965
5123
|
}
|
|
4966
5124
|
};
|
|
4967
5125
|
var Find = class Find extends StatementNode {
|
|
@@ -4981,6 +5139,59 @@ var Find = class Find extends StatementNode {
|
|
|
4981
5139
|
return new Find(this.ast.withProjection(withColumns(this.returns, columns)));
|
|
4982
5140
|
}
|
|
4983
5141
|
};
|
|
5142
|
+
/** Keys per read-back statement. The `ORDER BY CASE` costs the database the number of keys times the number of rows it returns, so the keys are read in chunks of this size. */
|
|
5143
|
+
const KEYS_PER_STATEMENT = 500;
|
|
5144
|
+
/**
|
|
5145
|
+
* Reads the rows an insert wrote back by their keys, for a database without `RETURNING`, in the order the insert wrote them, and fails when it finds fewer rows than keys, so the transaction rolls back. It reads at most 500 keys per statement.
|
|
5146
|
+
*
|
|
5147
|
+
* A `Find` with a `FilterData` edge cannot do this: the edge hands the `Find` conditions, not the key values, so the `Find` cannot order the rows by key or count the keys. The database does both comparisons, with its own rules for collation and precision: each key's condition both selects its row and, in an `ORDER BY CASE`, places it.
|
|
5148
|
+
*/
|
|
5149
|
+
var FindByKeys = class FindByKeys extends StatementNode {
|
|
5150
|
+
ast;
|
|
5151
|
+
keyColumns;
|
|
5152
|
+
owner;
|
|
5153
|
+
constructor(ast, keyColumns, owner) {
|
|
5154
|
+
super();
|
|
5155
|
+
this.ast = ast;
|
|
5156
|
+
this.keyColumns = Object.freeze([...keyColumns]);
|
|
5157
|
+
this.owner = owner;
|
|
5158
|
+
Object.freeze(this);
|
|
5159
|
+
}
|
|
5160
|
+
get returns() {
|
|
5161
|
+
return this.ast.projection;
|
|
5162
|
+
}
|
|
5163
|
+
execute(inputs, run) {
|
|
5164
|
+
const keys = inputs.keys;
|
|
5165
|
+
if (keys.length === 0) return rowsResult([]);
|
|
5166
|
+
const chunks = Array.from({ length: Math.ceil(keys.length / KEYS_PER_STATEMENT) }, (_, index) => keys.slice(index * KEYS_PER_STATEMENT, (index + 1) * KEYS_PER_STATEMENT));
|
|
5167
|
+
const { owner } = this;
|
|
5168
|
+
const statementFor = (chunk) => this.#statementFor(chunk);
|
|
5169
|
+
const generator = async function* () {
|
|
5170
|
+
for (const chunk of chunks) {
|
|
5171
|
+
const rows = await run.query(statementFor(chunk)).toArray();
|
|
5172
|
+
if (rows.length < chunk.length) throw ormError("ORM.MUTATION_ROW_MISSING", `${owner.operation}() for model "${owner.modelName}" did not find the row it wrote`, { meta: {
|
|
5173
|
+
operation: owner.operation,
|
|
5174
|
+
model: owner.modelName,
|
|
5175
|
+
phase: "read-back"
|
|
5176
|
+
} });
|
|
5177
|
+
yield* rows;
|
|
5178
|
+
}
|
|
5179
|
+
};
|
|
5180
|
+
return new AsyncIterableResult(generator());
|
|
5181
|
+
}
|
|
5182
|
+
#statementFor(keys) {
|
|
5183
|
+
const conditions = keys.map((key) => keyCondition(this.keyColumns, key));
|
|
5184
|
+
const existing = this.ast.where === void 0 ? [] : [this.ast.where];
|
|
5185
|
+
const found = this.ast.withWhere(combineWhereExprs([...existing, anyOf(conditions)]));
|
|
5186
|
+
return conditions.length === 1 ? found : found.withOrderBy([OrderByItem.asc(CaseExpr.of(conditions.map((condition, position) => ({
|
|
5187
|
+
condition,
|
|
5188
|
+
value: LiteralExpr.of(position)
|
|
5189
|
+
}))))]);
|
|
5190
|
+
}
|
|
5191
|
+
withReturning(columns) {
|
|
5192
|
+
return new FindByKeys(this.ast.withProjection(withColumns(this.returns, columns)), this.keyColumns, this.owner);
|
|
5193
|
+
}
|
|
5194
|
+
};
|
|
4984
5195
|
var Graph = class {
|
|
4985
5196
|
#ids = [];
|
|
4986
5197
|
#nodes = [];
|
|
@@ -5078,9 +5289,44 @@ var InsertChunked = class InsertChunked extends StatementNode {
|
|
|
5078
5289
|
return new InsertChunked(this.asts.map((ast) => ast.withReturning(withColumns(ast.returning ?? [], columns))));
|
|
5079
5290
|
}
|
|
5080
5291
|
async #sumOfCounts(run) {
|
|
5081
|
-
let
|
|
5082
|
-
for (const ast of this.asts)
|
|
5083
|
-
return
|
|
5292
|
+
let affectedRows = 0;
|
|
5293
|
+
for (const ast of this.asts) affectedRows += (await run.execute(ast)).affectedRows;
|
|
5294
|
+
return { affectedRows };
|
|
5295
|
+
}
|
|
5296
|
+
};
|
|
5297
|
+
/**
|
|
5298
|
+
* Inserts without `RETURNING` and reports the key of each row it inserted: the values the client wrote, and, for a one-row insert, the value the database generated, which the driver reports as `insertId`. When it reports none, the insert fails, so the transaction it runs in rolls back.
|
|
5299
|
+
*/
|
|
5300
|
+
var InsertReportingKeys = class extends Node {
|
|
5301
|
+
asts;
|
|
5302
|
+
keys;
|
|
5303
|
+
generated;
|
|
5304
|
+
owner;
|
|
5305
|
+
constructor(asts, keys, generated, owner) {
|
|
5306
|
+
super();
|
|
5307
|
+
this.asts = Object.freeze([...asts]);
|
|
5308
|
+
this.keys = Object.freeze([...keys]);
|
|
5309
|
+
this.generated = generated;
|
|
5310
|
+
this.owner = owner;
|
|
5311
|
+
Object.freeze(this);
|
|
5312
|
+
}
|
|
5313
|
+
execute(_inputs, run) {
|
|
5314
|
+
const { asts, keys, generated, owner } = this;
|
|
5315
|
+
const generator = async function* () {
|
|
5316
|
+
for (const ast of asts) {
|
|
5317
|
+
const stats = await run.execute(ast);
|
|
5318
|
+
if (generated !== void 0) {
|
|
5319
|
+
const insertId = reportedInsertId(stats, generated, owner);
|
|
5320
|
+
yield {
|
|
5321
|
+
...keys[0],
|
|
5322
|
+
[generated.column]: await generated.decode(insertId)
|
|
5323
|
+
};
|
|
5324
|
+
return;
|
|
5325
|
+
}
|
|
5326
|
+
}
|
|
5327
|
+
yield* keys;
|
|
5328
|
+
};
|
|
5329
|
+
return new AsyncIterableResult(generator());
|
|
5084
5330
|
}
|
|
5085
5331
|
};
|
|
5086
5332
|
var PayloadData = class extends Edge {
|
|
@@ -5130,7 +5376,7 @@ var Update = class Update extends StatementNode {
|
|
|
5130
5376
|
return new Update(this.ast.withReturning(withColumns(this.returns, columns)));
|
|
5131
5377
|
}
|
|
5132
5378
|
};
|
|
5133
|
-
function updateAllGraph(collection, set) {
|
|
5379
|
+
function updateAllGraph(collection, set, returns) {
|
|
5134
5380
|
const { context, state } = collection;
|
|
5135
5381
|
const graph = new Graph();
|
|
5136
5382
|
if (Object.keys(set).length === 0) {
|
|
@@ -5139,15 +5385,23 @@ function updateAllGraph(collection, set) {
|
|
|
5139
5385
|
}
|
|
5140
5386
|
requireIdentityColumnsForIncludes(collection);
|
|
5141
5387
|
const update = updateAst(context.contract, state.tables, set, whereOf(collection));
|
|
5388
|
+
if (readsBack(collection, returns)) {
|
|
5389
|
+
const { namespaceId, tableName } = state.tables.root.storage;
|
|
5390
|
+
readBackIdentity(context.contract, namespaceId, tableName, collection.modelName, "updateAll()");
|
|
5391
|
+
const found = graph.add(new Find(selectIdentityAst(collection, state)), { filter: [] });
|
|
5392
|
+
graph.add(new Update(update), { filter: [] });
|
|
5393
|
+
graph.setResult(addReadBack(graph, collection, found, keyOverrides(collection, set)));
|
|
5394
|
+
return graph;
|
|
5395
|
+
}
|
|
5142
5396
|
const updated = graph.add(new Update(update), { filter: [] });
|
|
5143
5397
|
graph.setResult(addWithIncludes(graph, collection, updated));
|
|
5144
5398
|
return graph;
|
|
5145
5399
|
}
|
|
5146
|
-
function deleteAllGraph(collection) {
|
|
5400
|
+
function deleteAllGraph(collection, returns) {
|
|
5147
5401
|
const { context, state } = collection;
|
|
5148
5402
|
const graph = new Graph();
|
|
5149
5403
|
const del = new Delete(deleteAst(context.contract, state.tables, whereOf(collection)));
|
|
5150
|
-
if (state.includes.length === 0) {
|
|
5404
|
+
if (state.includes.length === 0 && !readsBack(collection, returns)) {
|
|
5151
5405
|
graph.setResult(graph.add(del, { filter: [] }));
|
|
5152
5406
|
return graph;
|
|
5153
5407
|
}
|
|
@@ -5170,29 +5424,54 @@ function updateFirstGraph(collection, set) {
|
|
|
5170
5424
|
return graph;
|
|
5171
5425
|
}
|
|
5172
5426
|
const update = updateAst(context.contract, state.tables, set, void 0);
|
|
5427
|
+
if (readsBack(collection, "rows")) {
|
|
5428
|
+
graph.add(new Update(update), { filter: [sameRow(find, collection)] });
|
|
5429
|
+
graph.setResult(addReadBack(graph, collection, find, keyOverrides(collection, set)));
|
|
5430
|
+
return graph;
|
|
5431
|
+
}
|
|
5173
5432
|
const updated = graph.add(new Update(update), { filter: [sameRow(find, collection)] });
|
|
5174
5433
|
graph.setResult(addWithIncludes(graph, collection, updated));
|
|
5175
5434
|
return graph;
|
|
5176
5435
|
}
|
|
5177
5436
|
function deleteFirstGraph(collection) {
|
|
5178
5437
|
const { context, state } = collection;
|
|
5179
|
-
const
|
|
5438
|
+
const readsRowsFirst = state.includes.length > 0 || readsBack(collection, "rows");
|
|
5180
5439
|
const graph = new Graph();
|
|
5181
5440
|
requireIdentityColumns(collection);
|
|
5182
|
-
const find = addFindOfFirstRow(graph, collection,
|
|
5441
|
+
const find = addFindOfFirstRow(graph, collection, readsRowsFirst ? selectRowsAst : selectIdentityAst);
|
|
5183
5442
|
if (find === void 0) return graph;
|
|
5184
5443
|
const del = deleteAst(context.contract, state.tables, void 0);
|
|
5185
5444
|
const deleted = graph.add(new Delete(del), { filter: [sameRow(find, collection)] });
|
|
5186
|
-
graph.setResult(
|
|
5445
|
+
graph.setResult(readsRowsFirst ? find : deleted);
|
|
5187
5446
|
return graph;
|
|
5188
5447
|
}
|
|
5189
|
-
function createAllGraph(collection, rows, conflict) {
|
|
5448
|
+
function createAllGraph(collection, rows, conflict, returns) {
|
|
5190
5449
|
const { context, state } = collection;
|
|
5191
5450
|
const graph = new Graph();
|
|
5192
5451
|
if (rows.length === 0) return graph;
|
|
5193
5452
|
requireIdentityColumnsForIncludes(collection);
|
|
5194
5453
|
const { contract } = context;
|
|
5195
5454
|
const { root } = state.tables;
|
|
5455
|
+
if (readsBack(collection, returns)) {
|
|
5456
|
+
const method = rows.length === 1 ? "create()" : "createAll()";
|
|
5457
|
+
refuseSkipWithReadBack(collection, conflict, method);
|
|
5458
|
+
const { keys, generated } = writtenKeys({
|
|
5459
|
+
context,
|
|
5460
|
+
namespaceId: root.storage.namespaceId,
|
|
5461
|
+
tableName: root.storage.tableName,
|
|
5462
|
+
modelName: collection.modelName,
|
|
5463
|
+
rows,
|
|
5464
|
+
method
|
|
5465
|
+
});
|
|
5466
|
+
const asts = supportsDefaultInInsert(contract) ? [insertAst(contract, root, rows, void 0)] : groupRowsByColumnSignature(rows).map((group) => insertAst(contract, root, group, void 0));
|
|
5467
|
+
const owner = {
|
|
5468
|
+
operation: rows.length === 1 ? "create" : "createAll",
|
|
5469
|
+
modelName: collection.modelName
|
|
5470
|
+
};
|
|
5471
|
+
const inserted = graph.add(new InsertReportingKeys(asts, keys, generated, owner), {});
|
|
5472
|
+
graph.setResult(addFindOfWrittenRows(graph, collection, inserted, identityProjection(collection), owner));
|
|
5473
|
+
return graph;
|
|
5474
|
+
}
|
|
5196
5475
|
const inserted = supportsDefaultInInsert(contract) ? graph.add(new Insert(insertAst(contract, root, rows, conflict)), { payload: [] }) : graph.add(new InsertChunked(groupRowsByColumnSignature(rows).map((group) => insertAst(contract, root, group, conflict))), {});
|
|
5197
5476
|
graph.setResult(addWithIncludes(graph, collection, inserted));
|
|
5198
5477
|
return graph;
|
|
@@ -5232,24 +5511,94 @@ function sameColumns(columns) {
|
|
|
5232
5511
|
}
|
|
5233
5512
|
function upsertGraph(collection, create, update, conflictColumns) {
|
|
5234
5513
|
const { context, state } = collection;
|
|
5514
|
+
const { contract } = context;
|
|
5235
5515
|
const { root } = state.tables;
|
|
5236
5516
|
const graph = new Graph();
|
|
5237
5517
|
requireIdentityColumnsForIncludes(collection);
|
|
5238
|
-
const
|
|
5239
|
-
|
|
5518
|
+
const targeted = hasContractCapability(contract, "insertOnConflictTarget");
|
|
5519
|
+
if (!targeted) requireOnlyCollidingKey(collection, create, conflictColumns);
|
|
5520
|
+
const updateSet = Object.keys(update).length > 0 ? updateAssignments(contract, root, update) : Object.fromEntries(conflictColumns.slice(0, 1).map((column) => [column, ColumnRef.of("excluded", column)]));
|
|
5521
|
+
const upsert = upsertAst(contract, root, create, targeted ? conflictColumns : [], updateSet);
|
|
5522
|
+
if (readsBack(collection, "rows")) {
|
|
5523
|
+
const conflictValues = upsertConflictValues(collection, create, update, conflictColumns);
|
|
5524
|
+
const upsertOwner = {
|
|
5525
|
+
operation: "upsert",
|
|
5526
|
+
modelName: collection.modelName
|
|
5527
|
+
};
|
|
5528
|
+
const upserted = graph.add(new InsertReportingKeys([upsert], [conflictValues], void 0, upsertOwner), {});
|
|
5529
|
+
graph.setResult(addFindOfWrittenRows(graph, collection, upserted, projectTableColumns(contract, root, conflictColumns), upsertOwner));
|
|
5530
|
+
return graph;
|
|
5531
|
+
}
|
|
5240
5532
|
const upserted = graph.add(new Insert(upsert), { payload: [] });
|
|
5241
5533
|
graph.setResult(addWithIncludes(graph, collection, upserted));
|
|
5242
5534
|
return graph;
|
|
5243
5535
|
}
|
|
5244
5536
|
function addWithIncludes(graph, collection, written) {
|
|
5537
|
+
if (collection.state.includes.length === 0) return written;
|
|
5538
|
+
return graph.add(new Find(readBackAst(collection)), { filter: [sameRow(written, collection)] });
|
|
5539
|
+
}
|
|
5540
|
+
function readBackAst(collection) {
|
|
5245
5541
|
const { state } = collection;
|
|
5246
|
-
|
|
5247
|
-
const select = selectRowsAst(collection, {
|
|
5542
|
+
return selectRowsAst(collection, {
|
|
5248
5543
|
...emptyState(state.tables),
|
|
5249
5544
|
selectedFields: state.selectedFields,
|
|
5250
5545
|
includes: state.includes
|
|
5251
5546
|
});
|
|
5252
|
-
|
|
5547
|
+
}
|
|
5548
|
+
/**
|
|
5549
|
+
* Without `RETURNING`, a write that returns rows runs as the write, then a select of the rows by key, chosen from the contract before anything runs.
|
|
5550
|
+
*/
|
|
5551
|
+
function readsBack(collection, returns) {
|
|
5552
|
+
return returns === "rows" && !hasContractCapability(collection.context.contract, "returning");
|
|
5553
|
+
}
|
|
5554
|
+
/** A read of the rows a write changed, by the keys `keysFrom` found, with the new values of any key column the write set. */
|
|
5555
|
+
function addReadBack(graph, collection, keysFrom, changed) {
|
|
5556
|
+
return graph.add(new Find(readBackAst(collection)), { filter: [new FilterData(keysFrom, sameColumns(identityProjection(collection)), changed)] });
|
|
5557
|
+
}
|
|
5558
|
+
function addFindOfWrittenRows(graph, collection, inserted, keyColumns, owner) {
|
|
5559
|
+
const pairs = sameColumns(keyColumns);
|
|
5560
|
+
return graph.add(new FindByKeys(readBackAst(collection), pairs, owner), { keys: new Rows(inserted, pairs) });
|
|
5561
|
+
}
|
|
5562
|
+
function identityProjection(collection) {
|
|
5563
|
+
const { context, state } = collection;
|
|
5564
|
+
return projectTableColumns(context.contract, state.tables.root, identityColumnsOf(collection));
|
|
5565
|
+
}
|
|
5566
|
+
function keyOverrides(collection, set) {
|
|
5567
|
+
return Object.fromEntries(identityColumnsOf(collection).filter((column) => Object.hasOwn(set, column)).map((column) => [column, set[column]]));
|
|
5568
|
+
}
|
|
5569
|
+
function refuseSkipWithReadBack(collection, conflict, method) {
|
|
5570
|
+
if (conflict === void 0) return;
|
|
5571
|
+
throw ormError("ORM.CAPABILITY_MISSING", `${method} with onConflict "skip" on model "${collection.modelName}" requires contract capability "returning": without it the rows are read back by key, which finds a skipped row's existing match. Use createAndCount() to skip conflicting rows.`, { meta: {
|
|
5572
|
+
capability: "returning",
|
|
5573
|
+
action: method
|
|
5574
|
+
} });
|
|
5575
|
+
}
|
|
5576
|
+
/**
|
|
5577
|
+
* Without capability `insertOnConflictTarget`, the database's conflict clause fires on any unique key, so the upsert is allowed only when the named columns are the only key the create values can collide on: every other primary key or unique constraint contains an auto-increment column the create values leave out.
|
|
5578
|
+
*/
|
|
5579
|
+
function requireOnlyCollidingKey(collection, create, conflictColumns) {
|
|
5580
|
+
const { context, modelName, state } = collection;
|
|
5581
|
+
const { namespaceId, tableName } = state.tables.root.storage;
|
|
5582
|
+
const named = new Set(conflictColumns);
|
|
5583
|
+
const colliding = resolveUniqueKeyColumnSets(context.contract, namespaceId, tableName).find((columns) => !(columns.length === named.size && columns.every((column) => named.has(column))) && !columns.some((column) => create[column] === void 0 && isAutoIncrementColumn(context.contract, namespaceId, tableName, column)));
|
|
5584
|
+
if (colliding === void 0) return;
|
|
5585
|
+
throw ormError("ORM.CAPABILITY_MISSING", `upsert() on model "${modelName}" requires contract capability "insertOnConflictTarget": without it the conflict clause applies to every unique key, and the create values can also collide on (${colliding.join(", ")}), which would update a row other than the one conflictOn names.`, { meta: {
|
|
5586
|
+
capability: "insertOnConflictTarget",
|
|
5587
|
+
action: "upsert()"
|
|
5588
|
+
} });
|
|
5589
|
+
}
|
|
5590
|
+
/** The create's values for the conflict columns, by which an upsert without `RETURNING` reads its row back. */
|
|
5591
|
+
function upsertConflictValues(collection, create, update, conflictColumns) {
|
|
5592
|
+
const { modelName } = collection;
|
|
5593
|
+
const refused = (problem) => ormError("ORM.CAPABILITY_MISSING", `upsert() on model "${modelName}" ${problem}; without capability "returning" the row is read back by the create's values for the conflict columns.`, { meta: {
|
|
5594
|
+
capability: "returning",
|
|
5595
|
+
action: "upsert()"
|
|
5596
|
+
} });
|
|
5597
|
+
const updated = conflictColumns.filter((column) => Object.hasOwn(update, column));
|
|
5598
|
+
if (updated.length > 0) throw refused(`updates conflict column "${updated.join("\", \"")}"`);
|
|
5599
|
+
const absent = conflictColumns.filter((column) => create[column] === void 0);
|
|
5600
|
+
if (absent.length > 0) throw refused(`gives conflict column "${absent.join("\", \"")}" no create value`);
|
|
5601
|
+
return Object.fromEntries(conflictColumns.map((column) => [column, create[column]]));
|
|
5253
5602
|
}
|
|
5254
5603
|
function requireIdentityColumnsForIncludes(collection) {
|
|
5255
5604
|
const { modelName, state } = collection;
|
|
@@ -5335,7 +5684,7 @@ async function runNodesInOrder(graph, ctx, scope, callerRows) {
|
|
|
5335
5684
|
collected[id] = executed;
|
|
5336
5685
|
if (id !== graph.result) continue;
|
|
5337
5686
|
const storageRows = rowsOf(executed);
|
|
5338
|
-
count =
|
|
5687
|
+
count = Array.isArray(executed) ? storageRows.length : executed.affectedRows;
|
|
5339
5688
|
if (callerRows !== void 0) rows = await shapeRows(graph, id, streamOf(storageRows), callerRows).toArray();
|
|
5340
5689
|
}
|
|
5341
5690
|
return {
|
|
@@ -5355,7 +5704,7 @@ function runOn(ctx, scope) {
|
|
|
5355
5704
|
const planOf = (ast) => buildOrmQueryPlan(contract, ast, deriveParamsFromAst(ast).params);
|
|
5356
5705
|
return {
|
|
5357
5706
|
query: (ast) => queryPlanRows(scope, planOf(ast)),
|
|
5358
|
-
execute:
|
|
5707
|
+
execute: (ast) => scope.execute(planOf(ast))
|
|
5359
5708
|
};
|
|
5360
5709
|
}
|
|
5361
5710
|
function shapeRows(graph, id, storageRows, callerRows) {
|
|
@@ -5370,7 +5719,7 @@ function shapeRows(graph, id, storageRows, callerRows) {
|
|
|
5370
5719
|
});
|
|
5371
5720
|
}
|
|
5372
5721
|
function rowsOf(executed) {
|
|
5373
|
-
return
|
|
5722
|
+
return Array.isArray(executed) ? executed : [];
|
|
5374
5723
|
}
|
|
5375
5724
|
function rowStream(executed) {
|
|
5376
5725
|
return executed instanceof AsyncIterableResult ? executed : streamOf([]);
|
|
@@ -5976,7 +6325,6 @@ var CollectionBase = class CollectionBase {
|
|
|
5976
6325
|
}
|
|
5977
6326
|
async create(data, configure) {
|
|
5978
6327
|
assertLockCompatible(this.state, "mutation");
|
|
5979
|
-
assertReturningCapability(this.contract, "create()");
|
|
5980
6328
|
const annotations = this.#collectAnnotationsFromMeta(configure, "write", "create");
|
|
5981
6329
|
return runOrmCall(this.ctx.runtime, this.#writeCall("create", annotations, ormResults.row), (queryable) => this.#create(queryable, data));
|
|
5982
6330
|
}
|
|
@@ -6016,15 +6364,15 @@ var CollectionBase = class CollectionBase {
|
|
|
6016
6364
|
const generator = async function* () {};
|
|
6017
6365
|
return () => new AsyncIterableResult(generator());
|
|
6018
6366
|
}
|
|
6019
|
-
assertReturningCapability(this.contract, "createAll()");
|
|
6020
6367
|
const rows = blindCast(data);
|
|
6021
6368
|
const mtiContext = this.#resolveMtiCreateContext();
|
|
6022
6369
|
if (mtiContext) {
|
|
6370
|
+
assertReturningCapability(this.contract, "createAll()");
|
|
6023
6371
|
const variantTable = requireVariantTable(this.state.tables, mtiContext.variant.value);
|
|
6024
6372
|
const graph = createAllVariantGraph(this.#descriptionWithoutIncludes(), variantTable, mtiContext.variant.modelName, this.#variantCreateRows(rows, mtiContext, variantTable));
|
|
6025
6373
|
return (queryable) => queryGraph(graph, this.#on(queryable), this.#descriptionWithoutIncludes());
|
|
6026
6374
|
}
|
|
6027
|
-
const graph = createAllGraph(this.#descriptionOptions(), this.#createValues(rows), conflictSkip);
|
|
6375
|
+
const graph = createAllGraph(this.#descriptionOptions(), this.#createValues(rows), conflictSkip, "rows");
|
|
6028
6376
|
return (queryable) => queryGraph(graph, this.#on(queryable), this.#descriptionOptions());
|
|
6029
6377
|
}
|
|
6030
6378
|
#createValues(rows) {
|
|
@@ -6155,7 +6503,7 @@ var CollectionBase = class CollectionBase {
|
|
|
6155
6503
|
if (data.length === 0) return runOrmCall(this.ctx.runtime, call, async () => 0);
|
|
6156
6504
|
this.#assertNotMtiVariant("createAndCount()");
|
|
6157
6505
|
const rows = blindCast(data);
|
|
6158
|
-
const graph = createAllGraph(this.#descriptionWithoutIncludes(), this.#createValues(rows), conflictSkip);
|
|
6506
|
+
const graph = createAllGraph(this.#descriptionWithoutIncludes(), this.#createValues(rows), conflictSkip, "count");
|
|
6159
6507
|
return this.#countCall(call, graph);
|
|
6160
6508
|
}
|
|
6161
6509
|
#countCall(call, graph) {
|
|
@@ -6165,7 +6513,6 @@ var CollectionBase = class CollectionBase {
|
|
|
6165
6513
|
}
|
|
6166
6514
|
async upsert(input, configure) {
|
|
6167
6515
|
assertLockCompatible(this.state, "mutation");
|
|
6168
|
-
assertReturningCapability(this.contract, "upsert()");
|
|
6169
6516
|
this.#assertNotMtiVariant("upsert()");
|
|
6170
6517
|
const annotations = this.#collectAnnotationsFromMeta(configure, "write", "upsert");
|
|
6171
6518
|
const createValues = this.#mapCreateRows([blindCast(input.create)])[0] ?? {};
|
|
@@ -6189,7 +6536,6 @@ var CollectionBase = class CollectionBase {
|
|
|
6189
6536
|
}
|
|
6190
6537
|
async update(data, configure) {
|
|
6191
6538
|
assertLockCompatible(this.state, "mutation");
|
|
6192
|
-
assertReturningCapability(this.contract, "update()");
|
|
6193
6539
|
const annotations = this.#collectAnnotationsFromMeta(configure, "write", "update");
|
|
6194
6540
|
return runOrmCall(this.ctx.runtime, this.#writeCall("update", annotations, ormResults.rowOrNull), (queryable) => this.#update(queryable, data));
|
|
6195
6541
|
}
|
|
@@ -6217,8 +6563,7 @@ var CollectionBase = class CollectionBase {
|
|
|
6217
6563
|
assertBulkWriteIgnoresNothing(this.state, this.modelName, "updateAll");
|
|
6218
6564
|
assertLockCompatible(this.state, "mutation");
|
|
6219
6565
|
const annotations = this.#collectAnnotationsFromMeta(configure, "write", "updateAll");
|
|
6220
|
-
|
|
6221
|
-
const graph = updateAllGraph(this.#descriptionOptions(), this.#updateValues(data));
|
|
6566
|
+
const graph = updateAllGraph(this.#descriptionOptions(), this.#updateValues(data), "rows");
|
|
6222
6567
|
return this.#rowsCall("updateAll", annotations, graph);
|
|
6223
6568
|
}
|
|
6224
6569
|
#rowsCall(method, annotations, graph) {
|
|
@@ -6231,13 +6576,12 @@ var CollectionBase = class CollectionBase {
|
|
|
6231
6576
|
assertBulkWriteIgnoresNothing(this.state, this.modelName, "updateAndCount");
|
|
6232
6577
|
assertLockCompatible(this.state, "mutation");
|
|
6233
6578
|
const values = this.#updateValues(data);
|
|
6234
|
-
const graph = Object.keys(values).length === 0 ? new Graph() : updateAllGraph(this.#descriptionWithoutIncludes(), values);
|
|
6579
|
+
const graph = Object.keys(values).length === 0 ? new Graph() : updateAllGraph(this.#descriptionWithoutIncludes(), values, "count");
|
|
6235
6580
|
const annotations = this.#collectAnnotationsFromMeta(configure, "write", "updateAndCount");
|
|
6236
6581
|
return this.#countCall(this.#writeCall("updateAndCount", annotations, ormResults.count), graph);
|
|
6237
6582
|
}
|
|
6238
6583
|
async delete(configure) {
|
|
6239
6584
|
assertLockCompatible(this.state, "mutation");
|
|
6240
|
-
assertReturningCapability(this.contract, "delete()");
|
|
6241
6585
|
const annotations = this.#collectAnnotationsFromMeta(configure, "write", "delete");
|
|
6242
6586
|
const graph = deleteFirstGraph(this.#descriptionOptions());
|
|
6243
6587
|
return this.#firstRowCall("delete", annotations, graph);
|
|
@@ -6246,15 +6590,14 @@ var CollectionBase = class CollectionBase {
|
|
|
6246
6590
|
assertBulkWriteIgnoresNothing(this.state, this.modelName, "deleteAll");
|
|
6247
6591
|
assertLockCompatible(this.state, "mutation");
|
|
6248
6592
|
const annotations = this.#collectAnnotationsFromMeta(configure, "write", "deleteAll");
|
|
6249
|
-
|
|
6250
|
-
const graph = deleteAllGraph(this.#descriptionOptions());
|
|
6593
|
+
const graph = deleteAllGraph(this.#descriptionOptions(), "rows");
|
|
6251
6594
|
return this.#rowsCall("deleteAll", annotations, graph);
|
|
6252
6595
|
}
|
|
6253
6596
|
async deleteAndCount(configure) {
|
|
6254
6597
|
assertBulkWriteIgnoresNothing(this.state, this.modelName, "deleteAndCount");
|
|
6255
6598
|
assertLockCompatible(this.state, "mutation");
|
|
6256
6599
|
const annotations = this.#collectAnnotationsFromMeta(configure, "write", "deleteAndCount");
|
|
6257
|
-
const graph = deleteAllGraph(this.#descriptionWithoutIncludes());
|
|
6600
|
+
const graph = deleteAllGraph(this.#descriptionWithoutIncludes(), "count");
|
|
6258
6601
|
return this.#countCall(this.#writeCall("deleteAndCount", annotations, ormResults.count), graph);
|
|
6259
6602
|
}
|
|
6260
6603
|
#descriptionWithoutIncludes() {
|