@prisma/orm-family-sql 8.0.0-rc.18-dev.17 → 8.0.0-rc.18-dev.19

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.
Files changed (108) hide show
  1. package/dist/{authoring-type-constructors-0Iv2zdwS-MFIpJ4fA.mjs → authoring-type-constructors-0Iv2zdwS-BJjO5EnA.mjs} +2 -2
  2. package/dist/{authoring-type-constructors-0Iv2zdwS-MFIpJ4fA.mjs.map → authoring-type-constructors-0Iv2zdwS-BJjO5EnA.mjs.map} +1 -1
  3. package/dist/{config-types-ComQZUlA.mjs → config-types-DopEiXtk.mjs} +2 -2
  4. package/dist/{config-types-ComQZUlA.mjs.map → config-types-DopEiXtk.mjs.map} +1 -1
  5. package/dist/{contract-builder-fQ3gkIR5.mjs → contract-builder-C1X8KoEM.mjs} +3 -3
  6. package/dist/{contract-builder-fQ3gkIR5.mjs.map → contract-builder-C1X8KoEM.mjs.map} +1 -1
  7. package/dist/contract-prisma7__provider.d.mts +3 -3
  8. package/dist/contract-prisma7__provider.d.mts.map +1 -1
  9. package/dist/contract-prisma7__provider.mjs +19 -47
  10. package/dist/contract-prisma7__provider.mjs.map +1 -1
  11. package/dist/contract-psl.mjs +1 -1
  12. package/dist/contract-psl__attribute-specs.mjs +1 -1
  13. package/dist/contract-psl__provider.mjs +2 -2
  14. package/dist/contract-psl__provider.mjs.map +1 -1
  15. package/dist/contract-ts.mjs +3 -3
  16. package/dist/contract-ts__config-types.mjs +1 -1
  17. package/dist/contract-ts__contract-builder.mjs +2 -2
  18. package/dist/contract.d.mts +2 -2
  19. package/dist/contract.mjs +3 -3
  20. package/dist/contract__data-type.d.mts +1 -1
  21. package/dist/contract__foreign-key-materialization.d.mts +1 -1
  22. package/dist/contract__foreign-key-materialization.mjs +2 -2
  23. package/dist/contract__validators.mjs +1 -1
  24. package/dist/{control-mpACqp72.d.mts → control-BqS5MMDh.d.mts} +21 -12
  25. package/dist/control-BqS5MMDh.d.mts.map +1 -0
  26. package/dist/{control-ClahTAD-.mjs → control-C7MNvu5Q.mjs} +27 -13
  27. package/dist/control-C7MNvu5Q.mjs.map +1 -0
  28. package/dist/{control-adapter-BCopdpsT-DIHCWbq_.d.mts → control-adapter-BCopdpsT-Bou0wWLF.d.mts} +3 -3
  29. package/dist/{control-adapter-BCopdpsT-DIHCWbq_.d.mts.map → control-adapter-BCopdpsT-Bou0wWLF.d.mts.map} +1 -1
  30. package/dist/control-adapter-CUwBiImd.d.mts +1 -0
  31. package/dist/{data-type-B8N33s-_.d.mts → data-type-DuzmTpzK.d.mts} +3 -3
  32. package/dist/{data-type-B8N33s-_.d.mts.map → data-type-DuzmTpzK.d.mts.map} +1 -1
  33. package/dist/{derived-checks-CrvMQTJF-DlxFFtNM.mjs → derived-checks-sRZp_gTF-UGwFWkVX.mjs} +7 -20
  34. package/dist/derived-checks-sRZp_gTF-UGwFWkVX.mjs.map +1 -0
  35. package/dist/{diff-Bd9ILpZL.d.mts → diff-D6PbCUWL.d.mts} +5 -5
  36. package/dist/{diff-Bd9ILpZL.d.mts.map → diff-D6PbCUWL.d.mts.map} +1 -1
  37. package/dist/exports-DVsHk8HP-DrH_2a-H.mjs +2371 -0
  38. package/dist/exports-DVsHk8HP-DrH_2a-H.mjs.map +1 -0
  39. package/dist/family.d.mts +10 -10
  40. package/dist/family.mjs +6 -6
  41. package/dist/family__control-adapter.d.mts +2 -2
  42. package/dist/family__control.d.mts +3 -3
  43. package/dist/family__control.mjs +2 -2
  44. package/dist/family__diff.d.mts +1 -1
  45. package/dist/family__ir.mjs +1 -1
  46. package/dist/family__migration.d.mts +1 -1
  47. package/dist/family__pack.mjs +2 -2
  48. package/dist/family__psl-build.d.mts +2 -2
  49. package/dist/family__psl-build.mjs +2 -2
  50. package/dist/family__psl-infer.d.mts +1 -1
  51. package/dist/family__psl-infer.mjs +1 -1
  52. package/dist/{foreign-key-materialization-DfNPQL9G.mjs → foreign-key-materialization-BIvQTfz8.mjs} +2 -2
  53. package/dist/{foreign-key-materialization-DfNPQL9G.mjs.map → foreign-key-materialization-BIvQTfz8.mjs.map} +1 -1
  54. package/dist/{foreign-key-materialization-DCaDnUs-.d.mts → foreign-key-materialization-BiWTp2vi.d.mts} +3 -3
  55. package/dist/{foreign-key-materialization-DCaDnUs-.d.mts.map → foreign-key-materialization-BiWTp2vi.d.mts.map} +1 -1
  56. package/dist/{index-DWNoqFzr.d.mts → index-BxlXOVeT.d.mts} +14 -7
  57. package/dist/{index-DWNoqFzr.d.mts.map → index-BxlXOVeT.d.mts.map} +1 -1
  58. package/dist/{index-equivalence-DswCiq5l-BsphajRC.mjs → index-equivalence-DswCiq5l-Cp2V5nhL.mjs} +2 -2
  59. package/dist/{index-equivalence-DswCiq5l-BsphajRC.mjs.map → index-equivalence-DswCiq5l-Cp2V5nhL.mjs.map} +1 -1
  60. package/dist/{interpreter-CFj2aTEP-BHL3TOqk.mjs → interpreter-B9wNACvu-CjrIm-Jo.mjs} +5 -5
  61. package/dist/{interpreter-CFj2aTEP-BHL3TOqk.mjs.map → interpreter-B9wNACvu-CjrIm-Jo.mjs.map} +1 -1
  62. package/dist/{migration-lg_VgP_F.d.mts → migration-CJ0xK_7n.d.mts} +2 -2
  63. package/dist/{migration-lg_VgP_F.d.mts.map → migration-CJ0xK_7n.d.mts.map} +1 -1
  64. package/dist/orm-client.d.mts +12 -44
  65. package/dist/orm-client.d.mts.map +1 -1
  66. package/dist/orm-client.mjs +505 -187
  67. package/dist/orm-client.mjs.map +1 -1
  68. package/dist/psl-build-ClY62mZM.d.mts +157 -0
  69. package/dist/psl-build-ClY62mZM.d.mts.map +1 -0
  70. package/dist/{psl-build-BsJ6eChh.mjs → psl-build-pU0gKdVI.mjs} +146 -7
  71. package/dist/psl-build-pU0gKdVI.mjs.map +1 -0
  72. package/dist/{psl-field-resolution-o9sXqIlE-BJnlxQ4z.mjs → psl-field-resolution-BOJPyV5I-0zJJ0fOo.mjs} +20 -14
  73. package/dist/{psl-field-resolution-o9sXqIlE-BJnlxQ4z.mjs.map → psl-field-resolution-BOJPyV5I-0zJJ0fOo.mjs.map} +1 -1
  74. package/dist/{psl-infer-B6iemK9i.d.mts → psl-infer-1C9FqGO2.d.mts} +3 -3
  75. package/dist/{psl-infer-B6iemK9i.d.mts.map → psl-infer-1C9FqGO2.d.mts.map} +1 -1
  76. package/dist/{psl-infer-HPi_YMeE.mjs → psl-infer-CvUWefHM.mjs} +2 -2
  77. package/dist/{psl-infer-HPi_YMeE.mjs.map → psl-infer-CvUWefHM.mjs.map} +1 -1
  78. package/dist/runtime.d.mts +2 -2
  79. package/dist/runtime.mjs +1 -2289
  80. package/dist/{schema-differ-DmP74bB8-BGA6fzOv.d.mts → schema-differ-DmP74bB8-GfOUaGGy.d.mts} +3 -3
  81. package/dist/{schema-differ-DmP74bB8-BGA6fzOv.d.mts.map → schema-differ-DmP74bB8-GfOUaGGy.d.mts.map} +1 -1
  82. package/dist/schema-ir.d.mts +2 -2
  83. package/dist/schema-ir.mjs +1 -1
  84. package/dist/schema-ir__types.d.mts +3 -3
  85. package/dist/schema-ir__types.mjs +1 -1
  86. package/dist/{sql-contract-serializer-sMY3prTx-C8IEwSsf.mjs → sql-contract-serializer-sMY3prTx-BKQ4Yh-n.mjs} +2 -2
  87. package/dist/{sql-contract-serializer-sMY3prTx-C8IEwSsf.mjs.map → sql-contract-serializer-sMY3prTx-BKQ4Yh-n.mjs.map} +1 -1
  88. package/dist/{types-c1iIhJep-DdMj6TNl.d.mts → types-Bqe0AXuw-xqQnkIj4.d.mts} +25 -6
  89. package/dist/types-Bqe0AXuw-xqQnkIj4.d.mts.map +1 -0
  90. package/dist/types-CTdsm45r.d.mts +1 -0
  91. package/dist/{types-CaVn_xxe-D9WdU3Iy.mjs → types-CfPB-Kz_-ByWDfwMj.mjs} +31 -6
  92. package/dist/types-CfPB-Kz_-ByWDfwMj.mjs.map +1 -0
  93. package/dist/{types-DaYtBAYT-B22gkh5z.d.mts → types-DaYtBAYT-DbsbDMTk.d.mts} +4 -4
  94. package/dist/{types-DaYtBAYT-B22gkh5z.d.mts.map → types-DaYtBAYT-DbsbDMTk.d.mts.map} +1 -1
  95. package/dist/{validators-Bvfk0aN7.mjs → validators-V8vN9R85.mjs} +2 -2
  96. package/dist/{validators-Bvfk0aN7.mjs.map → validators-V8vN9R85.mjs.map} +1 -1
  97. package/package.json +18 -18
  98. package/dist/control-ClahTAD-.mjs.map +0 -1
  99. package/dist/control-adapter-BsSf5pqM.d.mts +0 -1
  100. package/dist/control-mpACqp72.d.mts.map +0 -1
  101. package/dist/derived-checks-CrvMQTJF-DlxFFtNM.mjs.map +0 -1
  102. package/dist/psl-build-BHQfP1_C.d.mts +0 -73
  103. package/dist/psl-build-BHQfP1_C.d.mts.map +0 -1
  104. package/dist/psl-build-BsJ6eChh.mjs.map +0 -1
  105. package/dist/runtime.mjs.map +0 -1
  106. package/dist/types-BLyhYk6B.d.mts +0 -1
  107. package/dist/types-CaVn_xxe-D9WdU3Iy.mjs.map +0 -1
  108. package/dist/types-c1iIhJep-DdMj6TNl.d.mts.map +0 -1
@@ -8,13 +8,16 @@ import { n as codecRefForStorageColumn } from "./codec-descriptor-registry-4kw8F
8
8
  import { t as createFunctions } from "./functions-0YWByawj.mjs";
9
9
  import { t as createIndexReferences } from "./index-reference-DR62gjQS.mjs";
10
10
  import { o as settlementOf } from "./transaction-state-BfXhs7D7-3k10jZ8I.mjs";
11
+ import { p as findActivitySource } from "./exports-DVsHk8HP-DrH_2a-H.mjs";
11
12
  import { structuredError } from "@prisma/orm-framework/utils/structured-error";
12
13
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
13
14
  import { blindCast, castAs } from "@prisma/orm-framework/utils/casts";
14
15
  import { InternalError, isInternalError } from "@prisma/orm-framework/utils/internal-error";
15
16
  import { domainModelsAtDefaultNamespace } from "@prisma/orm-framework/contract/types";
17
+ import { canonicalStringify } from "@prisma/orm-framework/utils/canonical-stringify";
16
18
  import { AsyncIterableResult, createMetaBuilder, isRuntimeError, runtimeError } from "@prisma/orm-framework/components/runtime";
17
19
  import { assertDefined, invariant } from "@prisma/orm-framework/utils/assertions";
20
+ import { hashContent } from "@prisma/orm-framework/utils/hash-content";
18
21
  //#region ../../../3-extensions/sql-orm-client/dist/index.mjs
19
22
  const operationNamesByRegistry = /* @__PURE__ */ new WeakMap();
20
23
  /**
@@ -954,54 +957,20 @@ function checkedOrderByItem(dir, expr, options) {
954
957
  function deriveParamsFromAst(ast) {
955
958
  return { params: collectOrderedParamRefs(ast).map((p) => p.kind === "param-ref" ? p.value : void 0) };
956
959
  }
957
- function buildOrmPlanMeta(contract, annotations) {
958
- const annotationRecord = annotations !== void 0 && annotations.size > 0 ? Object.freeze(Object.fromEntries(annotations)) : void 0;
960
+ function buildOrmPlanMeta(contract) {
959
961
  return {
960
962
  target: contract.target,
961
963
  targetFamily: contract.targetFamily,
962
964
  storageHash: contract.storage.storageHash,
963
965
  ...ifDefined("profileHash", contract.profileHash),
964
- ...ifDefined("annotations", annotationRecord),
965
966
  lane: "orm-client"
966
967
  };
967
968
  }
968
- function buildOrmQueryPlan(contract, ast, params, annotations) {
969
+ function buildOrmQueryPlan(contract, ast, params) {
969
970
  return Object.freeze({
970
971
  ast,
971
972
  params: [...params],
972
- meta: buildOrmPlanMeta(contract, annotations)
973
- });
974
- }
975
- /**
976
- * Merges annotations into an existing `SqlQueryPlan`'s
977
- * `meta.annotations` and returns a new frozen plan.
978
- *
979
- * Used by the ORM dispatch path to attach terminal-call annotations to
980
- * plans produced by mutation compile functions (which don't take
981
- * annotations as parameters). Reads compile through `compileSelect`-
982
- * family functions that pass `state.annotations` directly to
983
- * `buildOrmQueryPlan`; this helper is the alternate path for write
984
- * terminals where annotations arrive at the call site, not via state.
985
- *
986
- * Returns the input plan unchanged when `annotations` is undefined
987
- * or empty. Reserved namespaces already on the input plan (`codecs`, target keys such as `pg`)
988
- * win over caller-supplied entries under the same key —
989
- * see the reserved-namespace policy on `defineAnnotation`.
990
- */
991
- function mergeAnnotations(plan, annotations) {
992
- if (annotations === void 0 || annotations.size === 0) return plan;
993
- const callerEntries = {};
994
- for (const [namespace, value] of annotations) callerEntries[namespace] = value;
995
- const mergedAnnotations = Object.freeze({
996
- ...callerEntries,
997
- ...plan.meta.annotations ?? {}
998
- });
999
- return Object.freeze({
1000
- ...plan,
1001
- meta: Object.freeze({
1002
- ...plan.meta,
1003
- annotations: mergedAnnotations
1004
- })
973
+ meta: buildOrmPlanMeta(contract)
1005
974
  });
1006
975
  }
1007
976
  function bindWhereExpr(contract, expr, aliases) {
@@ -1349,8 +1318,7 @@ function emptyState(tables) {
1349
1318
  limit: void 0,
1350
1319
  offset: void 0,
1351
1320
  variantValue: void 0,
1352
- locking: void 0,
1353
- annotations: /* @__PURE__ */ new Map()
1321
+ locking: void 0
1354
1322
  };
1355
1323
  }
1356
1324
  function emptyGroupPagingState() {
@@ -2370,7 +2338,7 @@ function collectionSelectAst(contract, modelName, state) {
2370
2338
  function compileSelect(contract, modelName, state) {
2371
2339
  const ast = collectionSelectAst(contract, modelName, state);
2372
2340
  const { params } = deriveParamsFromAst(ast);
2373
- return buildOrmQueryPlan(contract, ast, params, state.annotations);
2341
+ return buildOrmQueryPlan(contract, ast, params);
2374
2342
  }
2375
2343
  function collectionSelectWithIncludesAst(contract, aggregates, modelName, state) {
2376
2344
  assertLockCompatible(state);
@@ -2395,7 +2363,7 @@ function collectionSelectWithIncludesAst(contract, aggregates, modelName, state)
2395
2363
  function compileSelectWithIncludes(contract, aggregates, modelName, state) {
2396
2364
  const ast = collectionSelectWithIncludesAst(contract, aggregates, modelName, state);
2397
2365
  const { params } = deriveParamsFromAst(ast);
2398
- return buildOrmQueryPlan(contract, ast, params, state.annotations);
2366
+ return buildOrmQueryPlan(contract, ast, params);
2399
2367
  }
2400
2368
  function queryPlanRows(scope, plan) {
2401
2369
  return scope.query(plan);
@@ -2572,24 +2540,37 @@ function describeCollectionFirstOrThrow(options) {
2572
2540
  consume: (source) => rows.consume(source).firstOrThrow()
2573
2541
  };
2574
2542
  }
2575
- function dispatchCollectionRows(options) {
2576
- const { context, runtime, state, modelName, namespaceId } = options;
2577
- const descriptionOptions = {
2578
- context,
2579
- state,
2580
- modelName,
2581
- namespaceId
2582
- };
2543
+ function describeCollectionQuery(options) {
2544
+ const { context, state, modelName, namespaceId } = options;
2583
2545
  if (state.includes.length === 0) {
2584
- const query = describeExecutionRows(descriptionOptions);
2585
- return query.consume(queryPlanRows(runtime, query.plan));
2546
+ const query = describeExecutionRows(options);
2547
+ return {
2548
+ plan: () => query.plan,
2549
+ rows: (scope) => runQuery(scope, query)
2550
+ };
2586
2551
  }
2587
2552
  resolvePolymorphismInfo(context.contract, namespaceId, modelName);
2588
- const generator = async function* () {
2589
- const query = describeExecutionRows(descriptionOptions);
2590
- yield* query.consume(queryPlanRows(runtime, query.plan));
2553
+ let compiled;
2554
+ const query = () => {
2555
+ compiled ??= describeExecutionRows(options);
2556
+ return compiled;
2557
+ };
2558
+ return {
2559
+ plan: () => query().plan,
2560
+ rows: (scope) => {
2561
+ const generator = async function* () {
2562
+ yield* runQuery(scope, query());
2563
+ };
2564
+ return new AsyncIterableResult(generator());
2565
+ }
2591
2566
  };
2592
- return new AsyncIterableResult(generator());
2567
+ }
2568
+ function runQuery(scope, query) {
2569
+ return query.consume(queryPlanRows(scope, query.plan));
2570
+ }
2571
+ function dispatchCollectionRows(options) {
2572
+ const { runtime, ...descriptionOptions } = options;
2573
+ return describeCollectionQuery(descriptionOptions).rows(runtime);
2593
2574
  }
2594
2575
  function consumeIncludeRows(context, state, namespaceId, modelName, rows) {
2595
2576
  const { contract } = context;
@@ -3805,6 +3786,313 @@ function buildJoinWhere(contract, parentNamespaceId, parentModelName, parentTabl
3805
3786
  if (joinExprs.length === 1 && firstExpr !== void 0) return firstExpr;
3806
3787
  return and(...joinExprs);
3807
3788
  }
3789
+ /** The hash input of a read is the content hash of the plan it sends first. */
3790
+ function planHashInput(plan) {
3791
+ return (source) => source.planContentHash(plan());
3792
+ }
3793
+ /** The hash input of a prepared read is the content hash of the statement with the parameters this execution binds. */
3794
+ function preparedHashInput(statement, params) {
3795
+ return (source) => source.planContentHash({
3796
+ statement,
3797
+ params
3798
+ });
3799
+ }
3800
+ /** A write's statements depend on earlier results, so its hash input is the model it writes. */
3801
+ function modelHashInput(namespaceId, modelName) {
3802
+ return async () => ({
3803
+ namespace: namespaceId,
3804
+ model: modelName
3805
+ });
3806
+ }
3807
+ function isRecord(value) {
3808
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3809
+ }
3810
+ const ormResults = {
3811
+ rows: (value) => Array.isArray(value),
3812
+ row: (value) => isRecord(value),
3813
+ rowOrNull: (value) => value === null || isRecord(value),
3814
+ count: (value) => typeof value === "number"
3815
+ };
3816
+ async function ormCallContentHash(source, call) {
3817
+ return hashContent(canonicalStringify({
3818
+ kind: "orm-call",
3819
+ method: call.method,
3820
+ hashInput: await call.hashInput(source)
3821
+ }));
3822
+ }
3823
+ /** Starts the call in the same turn as the terminal method, so a runtime closed after the method returns waits for it. The content hash is computed only when a middleware asks for it. */
3824
+ function startOrmCall(source, call) {
3825
+ return source.startActivity({
3826
+ kind: "orm-call",
3827
+ contentHash: () => ormCallContentHash(source, call),
3828
+ ...call.annotations === void 0 ? {} : { annotations: call.annotations }
3829
+ });
3830
+ }
3831
+ /** Ends a call whose work failed. The runtime has ended the activity `failed` even when `end` rejects, so the caller gets the error that failed the call; the error from `end`, such as one an `activityEnded` hook threw, becomes its `cause` when it has none. */
3832
+ async function endFailed(handle, failure) {
3833
+ try {
3834
+ await handle.end({ outcome: "failed" });
3835
+ } catch (endError) {
3836
+ if (failure instanceof Error && failure.cause === void 0) failure.cause = endError;
3837
+ }
3838
+ }
3839
+ async function interceptedResult(handle, call, intercepted) {
3840
+ const { result } = intercepted;
3841
+ if (!call.accepts(result)) {
3842
+ const invalid = ormError("ORM.INTERCEPTED_RESULT_INVALID", `A middleware answered ${call.method}() with a value that is not a result of ${call.method}()`, { meta: { method: call.method } });
3843
+ await endFailed(handle, invalid);
3844
+ throw invalid;
3845
+ }
3846
+ await handle.end({ outcome: "succeeded" });
3847
+ return result;
3848
+ }
3849
+ function activitySourceOf(queryable, method) {
3850
+ const source = findActivitySource(queryable);
3851
+ if (source === void 0) throw ormError("ORM.ACTIVITY_SOURCE_MISSING", `${method}() runs as an orm-call activity, and the queryable it was given has no activity source`, {
3852
+ fix: "Pass the ORM a runtime, connection or transaction from the SQL runtime, or a wrapper that keeps its [activitySource] member.",
3853
+ meta: { method }
3854
+ });
3855
+ return source;
3856
+ }
3857
+ async function runOrmCall(queryable, call, run) {
3858
+ const handle = await startOrmCall(activitySourceOf(queryable, call.method), call);
3859
+ if (handle.intercepted !== void 0) return interceptedResult(handle, call, handle.intercepted);
3860
+ let result;
3861
+ try {
3862
+ result = await run(handle);
3863
+ } catch (error) {
3864
+ await endFailed(handle, error);
3865
+ throw error;
3866
+ }
3867
+ await handle.end({
3868
+ outcome: "succeeded",
3869
+ result
3870
+ });
3871
+ return result;
3872
+ }
3873
+ /** The call ends when the caller reads to the end, stops early or the stream fails. Its result holds the rows only when it carries annotations, so an unannotated stream does not hold its rows. */
3874
+ function streamOrmCall(queryable, call, run) {
3875
+ return new AsyncIterableResult(new OrmCallRows(activitySourceOf(queryable, call.method), call, run));
3876
+ }
3877
+ const done = {
3878
+ done: true,
3879
+ value: void 0
3880
+ };
3881
+ /**
3882
+ * The rows of a streaming call. The call starts on the first `next()`. Like an async generator, it runs one `next()`, `return()` or `throw()` at a time and queues the calls that overlap it; unlike one, it forwards each row from the statement's iterator with a single promise.
3883
+ */
3884
+ var OrmCallRows = class {
3885
+ #source;
3886
+ #call;
3887
+ #run;
3888
+ #state = "idle";
3889
+ #handle;
3890
+ #inner;
3891
+ #intercepted;
3892
+ #collected;
3893
+ #busy = false;
3894
+ #waiting = [];
3895
+ constructor(source, call, run) {
3896
+ this.#source = source;
3897
+ this.#call = call;
3898
+ this.#run = run;
3899
+ }
3900
+ next() {
3901
+ return this.#enqueue(() => this.#next());
3902
+ }
3903
+ return() {
3904
+ return this.#enqueue(() => this.#return());
3905
+ }
3906
+ throw(error) {
3907
+ return this.#enqueue(() => this.#throw(error));
3908
+ }
3909
+ [Symbol.asyncIterator]() {
3910
+ return this;
3911
+ }
3912
+ async [Symbol.asyncDispose]() {
3913
+ await this.return();
3914
+ }
3915
+ #enqueue(operation) {
3916
+ if (!this.#busy) {
3917
+ this.#busy = true;
3918
+ return operation();
3919
+ }
3920
+ return new Promise((resolve, reject) => {
3921
+ this.#waiting.push(() => {
3922
+ operation().then(resolve, reject);
3923
+ });
3924
+ });
3925
+ }
3926
+ #release() {
3927
+ const waiting = this.#waiting.shift();
3928
+ if (waiting === void 0) this.#busy = false;
3929
+ else waiting();
3930
+ }
3931
+ #next() {
3932
+ switch (this.#state) {
3933
+ case "idle": return this.#start().then(() => this.#next(), (error) => {
3934
+ this.#release();
3935
+ throw error;
3936
+ });
3937
+ case "running": return this.#nextRow();
3938
+ case "intercepted": {
3939
+ const row = this.#intercepted?.next();
3940
+ this.#release();
3941
+ if (row === void 0 || row.done === true) {
3942
+ this.#state = "finished";
3943
+ return Promise.resolve(done);
3944
+ }
3945
+ return Promise.resolve({
3946
+ done: false,
3947
+ value: row.value
3948
+ });
3949
+ }
3950
+ default:
3951
+ this.#release();
3952
+ return Promise.resolve(done);
3953
+ }
3954
+ }
3955
+ async #return() {
3956
+ try {
3957
+ const handle = this.#handle;
3958
+ if (this.#state !== "running" || handle === void 0) {
3959
+ this.#state = "finished";
3960
+ return done;
3961
+ }
3962
+ this.#state = "finished";
3963
+ try {
3964
+ await this.#inner?.return?.();
3965
+ } catch (error) {
3966
+ await endFailed(handle, error);
3967
+ throw error;
3968
+ }
3969
+ await handle.end({ outcome: "stopped" });
3970
+ return done;
3971
+ } finally {
3972
+ this.#release();
3973
+ }
3974
+ }
3975
+ async #throw(error) {
3976
+ try {
3977
+ const handle = this.#handle;
3978
+ if (this.#state !== "running" || handle === void 0) {
3979
+ this.#state = "finished";
3980
+ throw error;
3981
+ }
3982
+ this.#state = "finished";
3983
+ try {
3984
+ await this.#inner?.return?.();
3985
+ } catch {}
3986
+ await endFailed(handle, error);
3987
+ throw error;
3988
+ } finally {
3989
+ this.#release();
3990
+ }
3991
+ }
3992
+ async #start() {
3993
+ let handle;
3994
+ try {
3995
+ handle = await startOrmCall(this.#source, this.#call);
3996
+ } catch (error) {
3997
+ this.#state = "finished";
3998
+ throw error;
3999
+ }
4000
+ this.#handle = handle;
4001
+ if (handle.intercepted !== void 0) {
4002
+ try {
4003
+ const rows = await interceptedResult(handle, this.#call, handle.intercepted);
4004
+ this.#intercepted = rows[Symbol.iterator]();
4005
+ } catch (error) {
4006
+ this.#state = "finished";
4007
+ throw error;
4008
+ }
4009
+ this.#state = "intercepted";
4010
+ return;
4011
+ }
4012
+ const annotations = this.#call.annotations;
4013
+ this.#collected = annotations !== void 0 && annotations.size > 0 ? [] : void 0;
4014
+ try {
4015
+ this.#inner = this.#run(handle)[Symbol.asyncIterator]();
4016
+ } catch (error) {
4017
+ this.#state = "finished";
4018
+ await endFailed(handle, error);
4019
+ throw error;
4020
+ }
4021
+ this.#state = "running";
4022
+ }
4023
+ #nextRow() {
4024
+ const inner = this.#inner;
4025
+ const handle = this.#handle;
4026
+ if (inner === void 0 || handle === void 0) {
4027
+ this.#release();
4028
+ return Promise.resolve(done);
4029
+ }
4030
+ let pending;
4031
+ try {
4032
+ pending = inner.next();
4033
+ } catch (error) {
4034
+ return this.#fail(handle, error);
4035
+ }
4036
+ return pending.then((result) => {
4037
+ if (result.done !== true) {
4038
+ this.#collected?.push(result.value);
4039
+ this.#release();
4040
+ return result;
4041
+ }
4042
+ this.#state = "finished";
4043
+ const collected = this.#collected;
4044
+ return handle.end(collected === void 0 ? { outcome: "succeeded" } : {
4045
+ outcome: "succeeded",
4046
+ result: collected
4047
+ }).then(() => {
4048
+ this.#release();
4049
+ return done;
4050
+ }, (endError) => {
4051
+ this.#release();
4052
+ throw endError;
4053
+ });
4054
+ }, (error) => this.#fail(handle, error));
4055
+ }
4056
+ async #fail(handle, error) {
4057
+ try {
4058
+ this.#state = "finished";
4059
+ await endFailed(handle, error);
4060
+ throw error;
4061
+ } finally {
4062
+ this.#release();
4063
+ }
4064
+ }
4065
+ };
4066
+ const preparedOrmCall = Symbol("preparedOrmCall");
4067
+ function asPreparedOrmCall(preparable, call) {
4068
+ return {
4069
+ ...preparable,
4070
+ [preparedOrmCall]: call
4071
+ };
4072
+ }
4073
+ function isPreparableOrmCall(preparable) {
4074
+ return preparedOrmCall in preparable;
4075
+ }
4076
+ function preparedOrmCallOf(preparable) {
4077
+ return isPreparableOrmCall(preparable) ? preparable[preparedOrmCall] : void 0;
4078
+ }
4079
+ function preparedRowsCall(method, annotations, consume) {
4080
+ return (target, rows, hashInput) => streamOrmCall(target, {
4081
+ method,
4082
+ annotations,
4083
+ hashInput,
4084
+ accepts: ormResults.rows
4085
+ }, (queryable) => consume(rows(queryable)));
4086
+ }
4087
+ function preparedValueCall(method, annotations, consume, accepts) {
4088
+ return (target, rows, hashInput) => runOrmCall(target, {
4089
+ method,
4090
+ annotations,
4091
+ hashInput,
4092
+ accepts
4093
+ }, (queryable) => consume(rows(queryable)));
4094
+ }
4095
+ const groupedAggregateMethod = "groupBy.aggregate";
3808
4096
  var GroupedCollection = class GroupedCollection {
3809
4097
  ctx;
3810
4098
  contract;
@@ -3892,21 +4180,34 @@ var GroupedCollection = class GroupedCollection {
3892
4180
  offset: typeof n === "number" ? n : toExpr(n)
3893
4181
  } });
3894
4182
  }
4183
+ get prepared() {
4184
+ return { aggregate: (fn, configure) => {
4185
+ const description = this.#describeAggregate(fn);
4186
+ return asPreparedOrmCall(description, preparedValueCall(groupedAggregateMethod, this.#annotations(configure), description.consume, ormResults.rows));
4187
+ } };
4188
+ }
3895
4189
  /**
3896
4190
  * Read terminal: run a grouped aggregate query.
3897
4191
  *
3898
4192
  * Accepts an optional `configure` callback that receives a
3899
- * `MetaBuilder<'read'>` for attaching typed annotations.
3900
- * Annotations are merged into the compiled plan's `meta.annotations`.
4193
+ * `MetaBuilder<'read'>` for attaching typed annotations to the call.
3901
4194
  */
3902
- get prepared() {
3903
- return { aggregate: (fn, configure) => this.#describeAggregate(fn, configure) };
3904
- }
3905
4195
  async aggregate(fn, configure) {
3906
- const description = this.#describeAggregate(fn, configure);
3907
- return description.consume(queryPlanRows(this.ctx.runtime, description.plan));
4196
+ const description = this.#describeAggregate(fn);
4197
+ return runOrmCall(this.ctx.runtime, {
4198
+ method: groupedAggregateMethod,
4199
+ annotations: this.#annotations(configure),
4200
+ hashInput: planHashInput(() => description.plan),
4201
+ accepts: ormResults.rows
4202
+ }, (queryable) => runQuery(queryable, description));
4203
+ }
4204
+ #annotations(configure) {
4205
+ if (configure === void 0) return void 0;
4206
+ const meta = createMetaBuilder("read", groupedAggregateMethod);
4207
+ configure(meta);
4208
+ return meta.annotations.size > 0 ? meta.annotations : void 0;
3908
4209
  }
3909
- #describeAggregate(fn, configure) {
4210
+ #describeAggregate(fn) {
3910
4211
  const aggregateSpec = fn(createAggregateBuilder(this.contract, this.ctx.context.aggregateDescriptors, this.namespaceId, this.modelName));
3911
4212
  const aggregateEntries = Object.entries(aggregateSpec);
3912
4213
  if (aggregateEntries.length === 0) throw ormError("ORM.AGGREGATE_SELECTOR_MISSING", "groupBy().aggregate() requires at least one aggregation selector", { meta: {
@@ -3918,13 +4219,7 @@ var GroupedCollection = class GroupedCollection {
3918
4219
  model: this.modelName,
3919
4220
  alias
3920
4221
  } });
3921
- let annotationsMap;
3922
- if (configure !== void 0) {
3923
- const meta = createMetaBuilder("read", "groupBy.aggregate");
3924
- configure(meta);
3925
- if (meta.annotations.size > 0) annotationsMap = meta.annotations;
3926
- }
3927
- const compiled = mergeAnnotations(compileGroupedAggregate(this.contract, this.ctx.context.aggregateDescriptors, this.preGroupState, this.groupByColumns, aggregateSpec, combineWhereExprs(this.havingFilters), this.modelName, this.postGroup), annotationsMap);
4222
+ const compiled = compileGroupedAggregate(this.contract, this.ctx.context.aggregateDescriptors, this.preGroupState, this.groupByColumns, aggregateSpec, combineWhereExprs(this.havingFilters), this.modelName, this.postGroup);
3928
4223
  const mapRow = createStorageRowMapper(this.contract, this.namespaceId, this.modelName);
3929
4224
  return {
3930
4225
  plan: compiled,
@@ -5002,36 +5297,33 @@ function whereOf(collection) {
5002
5297
  const { context, state } = collection;
5003
5298
  return countMutationWhere(context.contract, state.tables, state.filters, state.variantValue);
5004
5299
  }
5005
- function queryGraph(graph, ctx, annotations, callerRows) {
5300
+ function queryGraph(graph, ctx, callerRows) {
5006
5301
  returnCallerColumns(graph, callerRows);
5007
5302
  const [only, ...others] = graph.nodes();
5008
5303
  if (only !== void 0 && others.length === 0 && only[0] === graph.result) {
5009
5304
  const [id, node] = only;
5010
- const run = runOn(ctx, annotations);
5305
+ const run = runOn(ctx, ctx.runtime);
5011
5306
  return shapeRows(graph, id, rowStream(node.execute(inputsOf(graph, id, []), run)), callerRows);
5012
5307
  }
5013
5308
  const generator = async function* () {
5014
- yield* (await runAllNodes(graph, ctx, annotations, callerRows)).rows;
5309
+ yield* (await runAllNodes(graph, ctx, callerRows)).rows;
5015
5310
  };
5016
5311
  return new AsyncIterableResult(generator());
5017
5312
  }
5018
- async function executeGraph(graph, ctx, annotations) {
5019
- return { affectedRows: (await runAllNodes(graph, ctx, annotations, void 0)).count };
5313
+ async function executeGraph(graph, ctx) {
5314
+ return { affectedRows: (await runAllNodes(graph, ctx, void 0)).count };
5020
5315
  }
5021
5316
  function returnCallerColumns(graph, callerRows) {
5022
5317
  const { context, modelName, state } = callerRows;
5023
5318
  const columns = returningProjection(context.contract, modelName, state.tables.root, state.selectedFields);
5024
5319
  for (const [id, node] of graph.nodes()) if (id === graph.result && node instanceof StatementNode) graph.replace(id, node.withReturning(columns));
5025
5320
  }
5026
- function runAllNodes(graph, ctx, annotations, callerRows) {
5027
- if (graph.nodes().length > 1) return withMutationScope(ctx.runtime, (scope) => runNodesInOrder(graph, {
5028
- ...ctx,
5029
- runtime: scope
5030
- }, annotations, callerRows));
5031
- return runNodesInOrder(graph, ctx, annotations, callerRows);
5321
+ function runAllNodes(graph, ctx, callerRows) {
5322
+ if (graph.nodes().length > 1) return withMutationScope(ctx.runtime, (scope) => runNodesInOrder(graph, ctx, scope, callerRows));
5323
+ return runNodesInOrder(graph, ctx, ctx.runtime, callerRows);
5032
5324
  }
5033
- async function runNodesInOrder(graph, ctx, annotations, callerRows) {
5034
- const run = runOn(ctx, annotations);
5325
+ async function runNodesInOrder(graph, ctx, scope, callerRows) {
5326
+ const run = runOn(ctx, scope);
5035
5327
  const collected = [];
5036
5328
  let rows = [];
5037
5329
  let count = 0;
@@ -5055,12 +5347,12 @@ function inputsOf(graph, id, collected) {
5055
5347
  else outputs[name] = slot.length === 0 ? null : slot.map(outputOf);
5056
5348
  return outputs;
5057
5349
  }
5058
- function runOn(ctx, annotations) {
5350
+ function runOn(ctx, scope) {
5059
5351
  const { contract } = ctx.context;
5060
- const planOf = (ast) => mergeAnnotations(buildOrmQueryPlan(contract, ast, deriveParamsFromAst(ast).params), annotations);
5352
+ const planOf = (ast) => buildOrmQueryPlan(contract, ast, deriveParamsFromAst(ast).params);
5061
5353
  return {
5062
- query: (ast) => queryPlanRows(ctx.runtime, planOf(ast)),
5063
- execute: async (ast) => (await ctx.runtime.execute(planOf(ast))).affectedRows
5354
+ query: (ast) => queryPlanRows(scope, planOf(ast)),
5355
+ execute: async (ast) => (await scope.execute(planOf(ast))).affectedRows
5064
5356
  };
5065
5357
  }
5066
5358
  function shapeRows(graph, id, storageRows, callerRows) {
@@ -5560,22 +5852,36 @@ var CollectionBase = class CollectionBase {
5560
5852
  return this.#cloneSelf({ offset: typeof n === "number" ? n : toExpr(n) });
5561
5853
  }
5562
5854
  all(configure) {
5563
- return this.#withAnnotationsFromMeta(configure, "all").#dispatch();
5855
+ const annotations = this.#collectAnnotationsFromMeta(configure, "read", "all");
5856
+ const query = describeCollectionQuery(this.#descriptionOptions());
5857
+ return streamOrmCall(this.ctx.runtime, this.#readCall("all", annotations, query.plan, ormResults.rows), query.rows);
5564
5858
  }
5565
5859
  get prepared() {
5566
5860
  return blindCast({
5567
- aggregate: (fn, configure) => this.#describeAggregate(fn, configure),
5861
+ aggregate: (fn, configure) => this.#preparedAggregate(fn, configure),
5568
5862
  all: (configure) => {
5569
- return describeCollectionRows(this.#withAnnotationsFromMeta(configure, "all").#descriptionOptions());
5863
+ const annotations = this.#collectAnnotationsFromMeta(configure, "read", "all");
5864
+ const description = describeCollectionRows(this.#descriptionOptions());
5865
+ return asPreparedOrmCall(description, preparedRowsCall("all", annotations, description.consume));
5570
5866
  },
5571
5867
  first: (filter, configure) => {
5572
- return describeCollectionFirst(this.#forFirst(filter, configure, "first").#descriptionOptions());
5868
+ const scoped = this.#forFirst(filter);
5869
+ const annotations = this.#collectAnnotationsFromMeta(configure, "read", "first");
5870
+ const description = describeCollectionFirst(scoped.#descriptionOptions());
5871
+ return asPreparedOrmCall(description, preparedValueCall("first", annotations, description.consume, ormResults.rowOrNull));
5573
5872
  },
5574
5873
  firstOrThrow: (filter, configure) => {
5575
- return describeCollectionFirstOrThrow(this.#forFirst(filter, configure, "firstOrThrow").#descriptionOptions());
5874
+ const scoped = this.#forFirst(filter);
5875
+ const annotations = this.#collectAnnotationsFromMeta(configure, "read", "firstOrThrow");
5876
+ const description = describeCollectionFirstOrThrow(scoped.#descriptionOptions());
5877
+ return asPreparedOrmCall(description, preparedValueCall("firstOrThrow", annotations, description.consume, ormResults.row));
5576
5878
  }
5577
5879
  });
5578
5880
  }
5881
+ #preparedAggregate(fn, configure) {
5882
+ const description = this.#describeAggregate(fn);
5883
+ return asPreparedOrmCall(description, preparedValueCall("aggregate", this.#collectAnnotationsFromMeta(configure, "read", "aggregate"), description.consume, ormResults.row));
5884
+ }
5579
5885
  #descriptionOptions() {
5580
5886
  return {
5581
5887
  context: this.ctx.context,
@@ -5584,20 +5890,49 @@ var CollectionBase = class CollectionBase {
5584
5890
  namespaceId: this.namespaceId
5585
5891
  };
5586
5892
  }
5587
- #forFirst(filter, configure, terminalName) {
5588
- return (filter === void 0 ? this : typeof filter === "function" ? this.where(filter) : this.where(filter)).limit(1).#withAnnotationsFromMeta(configure, terminalName);
5893
+ #forFirst(filter) {
5894
+ return (filter === void 0 ? this : typeof filter === "function" ? this.where(filter) : this.where(filter)).limit(1);
5895
+ }
5896
+ #readCall(method, annotations, plan, accepts) {
5897
+ return {
5898
+ method,
5899
+ annotations,
5900
+ hashInput: planHashInput(plan),
5901
+ accepts
5902
+ };
5903
+ }
5904
+ #writeCall(method, annotations, accepts) {
5905
+ return {
5906
+ method,
5907
+ annotations,
5908
+ hashInput: modelHashInput(this.namespaceId, this.modelName),
5909
+ accepts
5910
+ };
5911
+ }
5912
+ #on(queryable) {
5913
+ return {
5914
+ ...this.ctx,
5915
+ runtime: queryable
5916
+ };
5589
5917
  }
5590
5918
  async first(filter, configure) {
5591
- return consumeFirstRow(this.#forFirst(filter, configure, "first").#dispatch());
5919
+ const scoped = this.#forFirst(filter);
5920
+ const annotations = this.#collectAnnotationsFromMeta(configure, "read", "first");
5921
+ const query = describeCollectionQuery(scoped.#descriptionOptions());
5922
+ return runOrmCall(this.ctx.runtime, this.#readCall("first", annotations, query.plan, ormResults.rowOrNull), (queryable) => consumeFirstRow(query.rows(queryable)));
5592
5923
  }
5593
5924
  async firstOrThrow(filter, configure) {
5594
- return this.#forFirst(filter, configure, "firstOrThrow").#dispatch().firstOrThrow();
5925
+ const scoped = this.#forFirst(filter);
5926
+ const annotations = this.#collectAnnotationsFromMeta(configure, "read", "firstOrThrow");
5927
+ const query = describeCollectionQuery(scoped.#descriptionOptions());
5928
+ return runOrmCall(this.ctx.runtime, this.#readCall("firstOrThrow", annotations, query.plan, ormResults.row), (queryable) => query.rows(queryable).firstOrThrow());
5595
5929
  }
5596
5930
  async aggregate(fn, configure) {
5597
- const description = this.#describeAggregate(fn, configure);
5598
- return description.consume(queryPlanRows(this.ctx.runtime, description.plan));
5931
+ const description = this.#describeAggregate(fn);
5932
+ const annotations = this.#collectAnnotationsFromMeta(configure, "read", "aggregate");
5933
+ return runOrmCall(this.ctx.runtime, this.#readCall("aggregate", annotations, () => description.plan, ormResults.row), (queryable) => runQuery(queryable, description));
5599
5934
  }
5600
- #describeAggregate(fn, configure) {
5935
+ #describeAggregate(fn) {
5601
5936
  assertLockCompatible(this.state, "aggregate");
5602
5937
  const aggregateSpec = fn(createAggregateBuilder(this.contract, this.ctx.context.aggregateDescriptors, this.namespaceId, this.modelName));
5603
5938
  const entries = Object.entries(aggregateSpec);
@@ -5610,8 +5945,7 @@ var CollectionBase = class CollectionBase {
5610
5945
  model: this.modelName,
5611
5946
  alias
5612
5947
  } });
5613
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "read", "aggregate");
5614
- const compiled = mergeAnnotations(compileAggregate(this.contract, this.ctx.context.aggregateDescriptors, this.state, aggregateSpec, this.modelName), annotationsMap);
5948
+ const compiled = compileAggregate(this.contract, this.ctx.context.aggregateDescriptors, this.state, aggregateSpec, this.modelName);
5615
5949
  const results = entries.map(([alias, selector]) => {
5616
5950
  const resolved = resolveAggregate({
5617
5951
  aggregates: this.ctx.context.aggregateDescriptors,
@@ -5640,24 +5974,27 @@ var CollectionBase = class CollectionBase {
5640
5974
  async create(data, configure) {
5641
5975
  assertLockCompatible(this.state, "mutation");
5642
5976
  assertReturningCapability(this.contract, "create()");
5643
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "write", "create");
5977
+ const annotations = this.#collectAnnotationsFromMeta(configure, "write", "create");
5978
+ return runOrmCall(this.ctx.runtime, this.#writeCall("create", annotations, ormResults.row), (queryable) => this.#create(queryable, data));
5979
+ }
5980
+ async #create(queryable, data) {
5644
5981
  if (hasNestedMutationCallbacks(this.contract, this.namespaceId, this.modelName, blindCast(data))) {
5645
5982
  const createdRow = await executeNestedCreateMutation({
5646
5983
  context: this.ctx.context,
5647
- runtime: this.ctx.runtime,
5984
+ runtime: queryable,
5648
5985
  namespaceId: this.namespaceId,
5649
5986
  modelName: this.modelName,
5650
5987
  data: blindCast(data)
5651
5988
  });
5652
5989
  const identityCriterion = buildRowIdentityFilterFromRow(this.contract, this.namespaceId, this.modelName, createdRow);
5653
- const reloaded = await this.#reloadMutationRowByIdentity(identityCriterion);
5990
+ const reloaded = await this.#reloadMutationRowByIdentity(queryable, identityCriterion);
5654
5991
  if (!reloaded) throw ormError("ORM.MUTATION_ROW_MISSING", `create() for model "${this.modelName}" did not return a row`, { meta: {
5655
5992
  operation: "create",
5656
5993
  model: this.modelName
5657
5994
  } });
5658
5995
  return reloaded;
5659
5996
  }
5660
- const created = (await this.#createAllWithAnnotations([blindCast(data)], annotationsMap))[0];
5997
+ const created = (await this.#createAllRows([blindCast(data)])(queryable))[0];
5661
5998
  if (created) return created;
5662
5999
  throw ormError("ORM.MUTATION_ROW_MISSING", `create() for model "${this.modelName}" did not return a row`, { meta: {
5663
6000
  operation: "create",
@@ -5668,21 +6005,24 @@ var CollectionBase = class CollectionBase {
5668
6005
  assertLockCompatible(this.state, "mutation");
5669
6006
  const { options, configureCallback } = splitCreateArguments(optionsOrConfigure, configure);
5670
6007
  const conflictSkip = this.#resolveConflictSkip(options, "createAll()");
5671
- return this.#createAllWithAnnotations(data, this.#collectAnnotationsFromMeta(configureCallback, "write", "createAll"), conflictSkip);
6008
+ const annotations = this.#collectAnnotationsFromMeta(configureCallback, "write", "createAll");
6009
+ return streamOrmCall(this.ctx.runtime, this.#writeCall("createAll", annotations, ormResults.rows), this.#createAllRows(data, conflictSkip));
5672
6010
  }
5673
- #createAllWithAnnotations(data, annotationsMap, conflictSkip) {
6011
+ #createAllRows(data, conflictSkip) {
5674
6012
  if (data.length === 0) {
5675
6013
  const generator = async function* () {};
5676
- return new AsyncIterableResult(generator());
6014
+ return () => new AsyncIterableResult(generator());
5677
6015
  }
5678
6016
  assertReturningCapability(this.contract, "createAll()");
5679
6017
  const rows = blindCast(data);
5680
6018
  const mtiContext = this.#resolveMtiCreateContext();
5681
6019
  if (mtiContext) {
5682
6020
  const variantTable = requireVariantTable(this.state.tables, mtiContext.variant.value);
5683
- return queryGraph(createAllVariantGraph(this.#descriptionWithoutIncludes(), variantTable, mtiContext.variant.modelName, this.#variantCreateRows(rows, mtiContext, variantTable)), this.ctx, annotationsMap, this.#descriptionWithoutIncludes());
6021
+ const graph = createAllVariantGraph(this.#descriptionWithoutIncludes(), variantTable, mtiContext.variant.modelName, this.#variantCreateRows(rows, mtiContext, variantTable));
6022
+ return (queryable) => queryGraph(graph, this.#on(queryable), this.#descriptionWithoutIncludes());
5684
6023
  }
5685
- return queryGraph(createAllGraph(this.#descriptionOptions(), this.#createValues(rows), conflictSkip), this.ctx, annotationsMap, this.#descriptionOptions());
6024
+ const graph = createAllGraph(this.#descriptionOptions(), this.#createValues(rows), conflictSkip);
6025
+ return (queryable) => queryGraph(graph, this.#on(queryable), this.#descriptionOptions());
5686
6026
  }
5687
6027
  #createValues(rows) {
5688
6028
  const mappedRows = this.#mapCreateRows(rows);
@@ -5807,17 +6147,24 @@ var CollectionBase = class CollectionBase {
5807
6147
  assertLockCompatible(this.state, "mutation");
5808
6148
  const { options, configureCallback } = splitCreateArguments(optionsOrConfigure, configure);
5809
6149
  const conflictSkip = this.#resolveConflictSkip(options, "createAndCount()");
5810
- if (data.length === 0) return 0;
6150
+ const annotations = this.#collectAnnotationsFromMeta(configureCallback, "write", "createAndCount");
6151
+ const call = this.#writeCall("createAndCount", annotations, ormResults.count);
6152
+ if (data.length === 0) return runOrmCall(this.ctx.runtime, call, async () => 0);
5811
6153
  this.#assertNotMtiVariant("createAndCount()");
5812
- const annotationsMap = this.#collectAnnotationsFromMeta(configureCallback, "write", "createAndCount");
5813
6154
  const rows = blindCast(data);
5814
- return (await executeGraph(createAllGraph(this.#descriptionWithoutIncludes(), this.#createValues(rows), conflictSkip), this.ctx, annotationsMap)).affectedRows;
6155
+ const graph = createAllGraph(this.#descriptionWithoutIncludes(), this.#createValues(rows), conflictSkip);
6156
+ return this.#countCall(call, graph);
6157
+ }
6158
+ #countCall(call, graph) {
6159
+ return runOrmCall(this.ctx.runtime, call, async (queryable) => {
6160
+ return (await executeGraph(graph, this.#on(queryable))).affectedRows;
6161
+ });
5815
6162
  }
5816
6163
  async upsert(input, configure) {
5817
6164
  assertLockCompatible(this.state, "mutation");
5818
6165
  assertReturningCapability(this.contract, "upsert()");
5819
6166
  this.#assertNotMtiVariant("upsert()");
5820
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "write", "upsert");
6167
+ const annotations = this.#collectAnnotationsFromMeta(configure, "write", "upsert");
5821
6168
  const createValues = this.#mapCreateRows([blindCast(input.create)])[0] ?? {};
5822
6169
  applyCreateDefaults(this.ctx, this.namespaceId, this.tableName, [createValues]);
5823
6170
  const updateValues = mapModelDataToStorageRow(this.contract, this.namespaceId, this.modelName, input.update);
@@ -5827,22 +6174,28 @@ var CollectionBase = class CollectionBase {
5827
6174
  method: "upsert",
5828
6175
  model: this.modelName
5829
6176
  } });
5830
- const row = await consumeFirstRow(queryGraph(upsertGraph(this.#descriptionOptions(), createValues, updateValues, conflictColumns), this.ctx, annotationsMap, this.#descriptionOptions()));
5831
- if (row) return row;
5832
- throw ormError("ORM.MUTATION_ROW_MISSING", `upsert() for model "${this.modelName}" did not return a row`, { meta: {
5833
- operation: "upsert",
5834
- model: this.modelName
5835
- } });
6177
+ const graph = upsertGraph(this.#descriptionOptions(), createValues, updateValues, conflictColumns);
6178
+ return runOrmCall(this.ctx.runtime, this.#writeCall("upsert", annotations, ormResults.row), async (queryable) => {
6179
+ const row = await consumeFirstRow(queryGraph(graph, this.#on(queryable), this.#descriptionOptions()));
6180
+ if (row) return row;
6181
+ throw ormError("ORM.MUTATION_ROW_MISSING", `upsert() for model "${this.modelName}" did not return a row`, { meta: {
6182
+ operation: "upsert",
6183
+ model: this.modelName
6184
+ } });
6185
+ });
5836
6186
  }
5837
6187
  async update(data, configure) {
5838
6188
  assertLockCompatible(this.state, "mutation");
5839
6189
  assertReturningCapability(this.contract, "update()");
5840
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "write", "update");
6190
+ const annotations = this.#collectAnnotationsFromMeta(configure, "write", "update");
6191
+ return runOrmCall(this.ctx.runtime, this.#writeCall("update", annotations, ormResults.rowOrNull), (queryable) => this.#update(queryable, data));
6192
+ }
6193
+ async #update(queryable, data) {
5841
6194
  if (hasNestedMutationCallbacks(this.contract, this.namespaceId, this.modelName, blindCast(data))) {
5842
6195
  assertRelationUpdateIgnoresNothing(this.state, this.modelName);
5843
6196
  const updatedRow = await executeNestedUpdateMutation({
5844
6197
  context: this.ctx.context,
5845
- runtime: this.ctx.runtime,
6198
+ runtime: queryable,
5846
6199
  namespaceId: this.namespaceId,
5847
6200
  modelName: this.modelName,
5848
6201
  tables: this.state.tables,
@@ -5851,45 +6204,55 @@ var CollectionBase = class CollectionBase {
5851
6204
  });
5852
6205
  if (!updatedRow) return null;
5853
6206
  const identityCriterion = buildRowIdentityFilterFromRow(this.contract, this.namespaceId, this.modelName, updatedRow);
5854
- return this.#reloadMutationRowByIdentity(identityCriterion);
6207
+ return this.#reloadMutationRowByIdentity(queryable, identityCriterion);
5855
6208
  }
5856
6209
  assertModelFieldNames(this.contract, this.namespaceId, this.modelName, blindCast(data));
5857
6210
  const values = this.#updateValues(blindCast(data));
5858
- return consumeFirstRow(queryGraph(updateFirstGraph(this.#descriptionOptions(), values), this.ctx, annotationsMap, this.#descriptionOptions()));
6211
+ return consumeFirstRow(queryGraph(updateFirstGraph(this.#descriptionOptions(), values), this.#on(queryable), this.#descriptionOptions()));
5859
6212
  }
5860
6213
  updateAll(data, configure) {
5861
6214
  assertBulkWriteIgnoresNothing(this.state, this.modelName, "updateAll");
5862
6215
  assertLockCompatible(this.state, "mutation");
5863
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "write", "updateAll");
6216
+ const annotations = this.#collectAnnotationsFromMeta(configure, "write", "updateAll");
5864
6217
  assertReturningCapability(this.contract, "updateAll()");
5865
- return queryGraph(updateAllGraph(this.#descriptionOptions(), this.#updateValues(data)), this.ctx, annotationsMap, this.#descriptionOptions());
6218
+ const graph = updateAllGraph(this.#descriptionOptions(), this.#updateValues(data));
6219
+ return this.#rowsCall("updateAll", annotations, graph);
6220
+ }
6221
+ #rowsCall(method, annotations, graph) {
6222
+ return streamOrmCall(this.ctx.runtime, this.#writeCall(method, annotations, ormResults.rows), (queryable) => queryGraph(graph, this.#on(queryable), this.#descriptionOptions()));
6223
+ }
6224
+ #firstRowCall(method, annotations, graph) {
6225
+ return runOrmCall(this.ctx.runtime, this.#writeCall(method, annotations, ormResults.rowOrNull), (queryable) => consumeFirstRow(queryGraph(graph, this.#on(queryable), this.#descriptionOptions())));
5866
6226
  }
5867
6227
  async updateAndCount(data, configure) {
5868
6228
  assertBulkWriteIgnoresNothing(this.state, this.modelName, "updateAndCount");
5869
6229
  assertLockCompatible(this.state, "mutation");
5870
6230
  const values = this.#updateValues(data);
5871
6231
  const graph = Object.keys(values).length === 0 ? new Graph() : updateAllGraph(this.#descriptionWithoutIncludes(), values);
5872
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "write", "updateAndCount");
5873
- return (await executeGraph(graph, this.ctx, annotationsMap)).affectedRows;
6232
+ const annotations = this.#collectAnnotationsFromMeta(configure, "write", "updateAndCount");
6233
+ return this.#countCall(this.#writeCall("updateAndCount", annotations, ormResults.count), graph);
5874
6234
  }
5875
6235
  async delete(configure) {
5876
6236
  assertLockCompatible(this.state, "mutation");
5877
6237
  assertReturningCapability(this.contract, "delete()");
5878
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "write", "delete");
5879
- return consumeFirstRow(queryGraph(deleteFirstGraph(this.#descriptionOptions()), this.ctx, annotationsMap, this.#descriptionOptions()));
6238
+ const annotations = this.#collectAnnotationsFromMeta(configure, "write", "delete");
6239
+ const graph = deleteFirstGraph(this.#descriptionOptions());
6240
+ return this.#firstRowCall("delete", annotations, graph);
5880
6241
  }
5881
6242
  deleteAll(configure) {
5882
6243
  assertBulkWriteIgnoresNothing(this.state, this.modelName, "deleteAll");
5883
6244
  assertLockCompatible(this.state, "mutation");
5884
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "write", "deleteAll");
6245
+ const annotations = this.#collectAnnotationsFromMeta(configure, "write", "deleteAll");
5885
6246
  assertReturningCapability(this.contract, "deleteAll()");
5886
- return queryGraph(deleteAllGraph(this.#descriptionOptions()), this.ctx, annotationsMap, this.#descriptionOptions());
6247
+ const graph = deleteAllGraph(this.#descriptionOptions());
6248
+ return this.#rowsCall("deleteAll", annotations, graph);
5887
6249
  }
5888
6250
  async deleteAndCount(configure) {
5889
6251
  assertBulkWriteIgnoresNothing(this.state, this.modelName, "deleteAndCount");
5890
6252
  assertLockCompatible(this.state, "mutation");
5891
- const annotationsMap = this.#collectAnnotationsFromMeta(configure, "write", "deleteAndCount");
5892
- return (await executeGraph(deleteAllGraph(this.#descriptionWithoutIncludes()), this.ctx, annotationsMap)).affectedRows;
6253
+ const annotations = this.#collectAnnotationsFromMeta(configure, "write", "deleteAndCount");
6254
+ const graph = deleteAllGraph(this.#descriptionWithoutIncludes());
6255
+ return this.#countCall(this.#writeCall("deleteAndCount", annotations, ormResults.count), graph);
5893
6256
  }
5894
6257
  #descriptionWithoutIncludes() {
5895
6258
  return {
@@ -5905,10 +6268,10 @@ var CollectionBase = class CollectionBase {
5905
6268
  if (Object.keys(values).length > 0) applyUpdateDefaults(this.ctx, this.namespaceId, this.tableName, values);
5906
6269
  return values;
5907
6270
  }
5908
- async #reloadMutationRowByIdentity(criterion) {
5909
- return this.#reloadMutationRowByCriterion(criterion, "row identity");
6271
+ async #reloadMutationRowByIdentity(queryable, criterion) {
6272
+ return this.#reloadMutationRowByCriterion(queryable, criterion, "row identity");
5910
6273
  }
5911
- async #reloadMutationRowByCriterion(criterion, criterionLabel) {
6274
+ async #reloadMutationRowByCriterion(queryable, criterion, criterionLabel) {
5912
6275
  const whereExpr = shorthandToWhereExpr(this.ctx.context, this.namespaceId, this.modelName, blindCast(criterion), this.state.tables.root);
5913
6276
  if (!whereExpr) throw new InternalError(`Failed to build ${criterionLabel} filter for mutation result on model "${this.modelName}"`);
5914
6277
  const resultState = {
@@ -5920,7 +6283,7 @@ var CollectionBase = class CollectionBase {
5920
6283
  };
5921
6284
  return (await dispatchCollectionRows({
5922
6285
  context: this.ctx.context,
5923
- runtime: this.ctx.runtime,
6286
+ runtime: queryable,
5924
6287
  state: resultState,
5925
6288
  modelName: this.modelName,
5926
6289
  namespaceId: this.namespaceId
@@ -5942,12 +6305,6 @@ var CollectionBase = class CollectionBase {
5942
6305
  });
5943
6306
  return this.#cloneSelf({ locking: [...this.state.locking ?? [], clause] });
5944
6307
  }
5945
- #clone(overrides) {
5946
- return this.#createSelf({
5947
- ...this.state,
5948
- ...overrides
5949
- });
5950
- }
5951
6308
  #cloneSelf(overrides) {
5952
6309
  return blindCast(this.#createSelf({
5953
6310
  ...this.state,
@@ -5978,48 +6335,6 @@ var CollectionBase = class CollectionBase {
5978
6335
  includeRefinementMode: options.includeRefinementMode ?? this.includeRefinementMode
5979
6336
  }));
5980
6337
  }
5981
- #dispatch() {
5982
- return dispatchCollectionRows({
5983
- context: this.ctx.context,
5984
- runtime: this.ctx.runtime,
5985
- state: this.state,
5986
- modelName: this.modelName,
5987
- namespaceId: this.namespaceId
5988
- });
5989
- }
5990
- /**
5991
- * Invokes the user-supplied configurator (if any) against a freshly
5992
- * constructed read meta builder, and returns a clone whose
5993
- * `state.annotations` carries the recorded map. Used by read
5994
- * terminals that flow annotations through state (`all`, `first`).
5995
- *
5996
- * Returns the receiver unchanged when no configurator was supplied
5997
- * or when the configurator did not call `meta.annotate(...)`. The
5998
- * meta builder's `annotate` method enforces applicability at the
5999
- * type level and at runtime, so terminal code does not need to
6000
- * re-validate.
6001
- */
6002
- #withAnnotationsFromMeta(configure, terminalName) {
6003
- if (configure === void 0) return this;
6004
- const meta = createMetaBuilder("read", terminalName);
6005
- configure(meta);
6006
- if (meta.annotations.size === 0) return this;
6007
- const next = new Map(this.state.annotations);
6008
- for (const [namespace, value] of meta.annotations) next.set(namespace, value);
6009
- return blindCast(this.#clone({ annotations: next }));
6010
- }
6011
- /**
6012
- * Invokes the user-supplied configurator (if any) against a freshly
6013
- * constructed meta builder of the given operation kind, and returns
6014
- * the recorded annotation map (or `undefined` when empty). Used by
6015
- * terminals where annotations don't flow through `state` — the
6016
- * compiled plan is post-wrapped via `mergeAnnotations` instead.
6017
- * Read terminals `all` and `first` populate `state.annotations`
6018
- * via `#withAnnotationsFromMeta` instead; `aggregate` uses this
6019
- * post-wrap path because `compileAggregate` does not forward `state.annotations` into the plan.
6020
- * The meta builder's `annotate` method enforces applicability at the
6021
- * type level and at runtime.
6022
- */
6023
6338
  #collectAnnotationsFromMeta(configure, kind, terminalName) {
6024
6339
  if (configure === void 0) return;
6025
6340
  const meta = createMetaBuilder(kind, terminalName);
@@ -6146,7 +6461,10 @@ async function prepareQuery(runtime, declaration, callback) {
6146
6461
  }
6147
6462
  function createPreparedRowQuery(description, statement) {
6148
6463
  return Object.freeze({ query(target, params, options) {
6149
- return description.consume(statement.query(target, params, options));
6464
+ const rows = (queryable) => statement.query(queryable, params, options);
6465
+ const call = preparedOrmCallOf(description);
6466
+ if (call === void 0) return description.consume(rows(target));
6467
+ return call(target, rows, preparedHashInput(statement, params));
6150
6468
  } });
6151
6469
  }
6152
6470
  //#endregion