turbine-orm 0.95.0 → 0.96.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -63,21 +63,26 @@
63
63
  * - `instanceof PrismaClientKnownRequestError`, `.meta`/message byte parity
64
64
  * (opt into `prismaErrorCodes` for a `.code` like `P2002`, without pretending
65
65
  * `instanceof` identity).
66
- * - `Prisma.join` / `Prisma.raw` composition beyond plain fragment flattening.
66
+ * - Splicing another library's `Prisma.sql` fragments unless asked to: they are
67
+ * bound as values until the client is given that library's namespace
68
+ * ({@link PrismaCompatOptions.prismaNamespace}).
67
69
  * - Fluent relation chaining (`prisma.user.findUnique().posts()`).
68
70
  * - Accelerate / Pulse / driver-adapter preview features, the Mongo API, and the
69
71
  * `prisma migrate`/`db` CLI family (Turbine ships its own migrations).
70
72
  * - **Negative `take`** (take-from-end) throws: Turbine has no reverse-take.
71
73
  * A **`cursor` on a nested relation include** throws: `with` has no cursor
72
74
  * (`take` / `skip` there page each parent's rows, as in Prisma).
73
- * - **A filtered relation count** (`_count: { select: { posts: { where } } }`)
74
- * and **`distinct` on a nested include** throw `UnsupportedFeatureError`:
75
- * core counts and includes a relation whole, so honoring either would mean
76
- * returning a wrong number or duplicate rows. The message names the
77
- * alternative (a `count` / `findMany` on the related model).
75
+ * - **`distinct` on a nested include** throws `UnsupportedFeatureError`: core
76
+ * includes a relation whole, so honoring it would mean returning duplicate
77
+ * rows. The message names the alternative (a `findMany` on the related model).
78
+ * A filtered relation count (`_count: { select: { posts: { where } } }`) and a
79
+ * `_count` below the top level ARE supported: this layer runs one grouped
80
+ * count per counted relation after the read, in the same transaction (see
81
+ * {@link ReadPlan}). Those two forms count one-to-many relations only; a
82
+ * many-to-many one is refused by name.
78
83
  * - **Nothing is accepted and dropped.** Every option on an included relation
79
- * and every key under `_count` is translated, refused by name (the two
80
- * above, `cursor`), or refused as unknown (`ValidationError`, with a
84
+ * and every key under `_count` is translated, refused by name (`distinct`,
85
+ * `cursor`), or refused as unknown (`ValidationError`, with a
81
86
  * suggestion): a misspelled `wher`, a Turbine spelling like `limit`, a
82
87
  * relation `_count` does not know. The same holds for `$transaction` options
83
88
  * (`maxWait` is accepted, warned about once, and not applied: the pool's
@@ -89,10 +94,11 @@
89
94
  * - **Write projections**: `select` / `omit` on create/update/delete/upsert
90
95
  * narrow the RETURNED OBJECT (see {@link resolveWriteProjection}); they do
91
96
  * NOT narrow the statement's `RETURNING` list, so the column still crosses
92
- * the wire, and `pii: true` remains the SQL-level control. A relation key in
93
- * either (or any `include` on a write) THROWS, since a write returns its own
94
- * row only. `omit` on READS is translated to core's own `omit`, see
95
- * {@link translateOmit}.
97
+ * the wire, and `pii: true` remains the SQL-level control. A write whose
98
+ * `include` / `select` names a relation or `_count` runs as the write followed
99
+ * by a read of the written row by primary key, in one transaction (a delete
100
+ * reads first), so it returns what Prisma returns. `omit` on READS is
101
+ * translated to core's own `omit`, see {@link translateOmit}.
96
102
  * - **`take` / `skip` / `cursor` on `count` and `aggregate`** throw: Prisma
97
103
  * computes those over one page of rows and Turbine has no paged count. An
98
104
  * `orderBy` alone changes nothing there and is accepted. `count({ select })`
@@ -162,6 +168,48 @@ function isSqlFragment(x) {
162
168
  function makeSql(strings, values) {
163
169
  return { strings, values, [SQL_FRAGMENT]: true };
164
170
  }
171
+ /** The default reader: this module's own branded fragments only. */
172
+ const ownFragment = (value) => (isSqlFragment(value) ? value : undefined);
173
+ /**
174
+ * A reader that also splices fragments built by another library's `Prisma`
175
+ * namespace (in practice `@prisma/client`, whose `Prisma.sql` / `join` / `raw` /
176
+ * `empty` all return instances of one class that is not exported).
177
+ *
178
+ * Recognition is by PROTOTYPE IDENTITY with the namespace's own `empty`
179
+ * fragment, never by shape. A shape test (`strings` + `values` arrays) would
180
+ * splice a request body: `JSON.parse` happily produces
181
+ * `{ "strings": ["1; DROP TABLE t; --"], "values": [] }`, and that object sitting
182
+ * in `$queryRaw\`... ${body.filter}\`` would then be SQL rather than a bound
183
+ * value. A parsed body can never carry a class prototype, so it stays a value,
184
+ * exactly as it does in Prisma, which recognizes its fragments by `instanceof`.
185
+ */
186
+ function foreignFragmentReader(namespace) {
187
+ const empty = namespace?.empty;
188
+ const proto = typeof empty === 'object' && empty !== null ? Object.getPrototypeOf(empty) : null;
189
+ if (proto === null || proto === Object.prototype || !hasFragmentParts(empty)) {
190
+ throw new ValidationError('prisma-compat: `prismaNamespace` takes the `Prisma` namespace of a client library ' +
191
+ '(`import { Prisma } from "@prisma/client"`), whose `Prisma.empty` is a fragment instance with ' +
192
+ '`strings` and `values` arrays. The value given has no such `empty`.');
193
+ }
194
+ return (value) => {
195
+ if (isSqlFragment(value))
196
+ return value;
197
+ if (typeof value !== 'object' || value === null || Object.getPrototypeOf(value) !== proto)
198
+ return undefined;
199
+ if (!hasFragmentParts(value)) {
200
+ throw new ValidationError('prisma-compat: a fragment from the configured `prismaNamespace` does not have `strings` and `values` ' +
201
+ 'arrays with one more string than values, so it cannot be composed.');
202
+ }
203
+ return value;
204
+ };
205
+ }
206
+ function hasFragmentParts(value) {
207
+ const { strings, values } = value;
208
+ return (Array.isArray(strings) &&
209
+ Array.isArray(values) &&
210
+ strings.length === values.length + 1 &&
211
+ strings.every((part) => typeof part === 'string'));
212
+ }
165
213
  /**
166
214
  * `Prisma`-compatible raw-SQL helpers, a minimal local implementation so
167
215
  * migrated `Prisma.sql\`…\`` / `Prisma.join(...)` / `Prisma.raw(...)` calls keep
@@ -748,7 +796,7 @@ function translateOmit(ctx, mm, omit) {
748
796
  * `RangeError` here, before core's own depth-10 relation cap
749
797
  * (`CircularRelationError`) could ever see the `with` clause it was building.
750
798
  */
751
- function translateProjection(ctx, mm, args, depth = 0) {
799
+ function translateProjection(ctx, mm, args, depth = 0, plan = newReadPlan(mm, false)) {
752
800
  assertTranslateDepth(depth, 'include');
753
801
  const include = args.include;
754
802
  const select = args.select;
@@ -760,51 +808,266 @@ function translateProjection(ctx, mm, args, depth = 0) {
760
808
  throw new ValidationError('prisma-compat: `select` and `omit` are mutually exclusive. ' +
761
809
  'A `select` already lists exactly the fields you want.');
762
810
  }
763
- const omit = omitArg ? translateOmit(ctx, mm, omitArg) : undefined;
811
+ let omit = omitArg ? translateOmit(ctx, mm, omitArg) : undefined;
764
812
  const withClause = {};
765
813
  let hasWith = false;
814
+ /** The `_count` value on this level, decided after the loop (see planCounts). */
815
+ let countVal;
766
816
  if (include) {
767
817
  for (const [key, val] of Object.entries(include)) {
768
818
  if (val === false || val == null)
769
819
  continue;
770
820
  if (key === '_count') {
771
- withClause._count = translateCountSelect(ctx, mm, val);
772
- hasWith = true;
821
+ countVal = val;
773
822
  continue;
774
823
  }
775
824
  const rel = ownLookup(mm.relations, key);
776
825
  if (!rel) {
777
826
  throw new ValidationError(`prisma-compat: unknown relation "${key}" in include on model "${modelName(ctx, mm)}".`);
778
827
  }
779
- setOwn(withClause, rel.name, translateWithOption(ctx, mm, rel.name, val, depth + 1));
828
+ setOwn(withClause, rel.name, translateWithOption(ctx, mm, rel.name, val, depth + 1, plan));
780
829
  hasWith = true;
781
830
  }
831
+ if (countVal !== undefined) {
832
+ const core = planCounts(ctx, mm, countVal, plan);
833
+ if (core !== undefined) {
834
+ withClause._count = core;
835
+ hasWith = true;
836
+ }
837
+ else if (omit) {
838
+ // The follow-up count needs each row's key; an `omit` naming it gets it
839
+ // back for the count and drops it again afterwards.
840
+ for (const field of countKeyFields(plan)) {
841
+ if (Object.hasOwn(omit, field)) {
842
+ delete omit[field];
843
+ plan.drop ??= new Set();
844
+ plan.drop.add(prismaFieldName(ctx, mm, field));
845
+ }
846
+ }
847
+ if (Object.keys(omit).length === 0)
848
+ omit = undefined;
849
+ }
850
+ }
782
851
  return { omit, with: hasWith ? withClause : undefined };
783
852
  }
784
853
  if (select) {
785
854
  const scalar = {};
786
855
  let hasScalar = false;
856
+ const picked = new Set();
787
857
  for (const [key, val] of Object.entries(select)) {
788
858
  if (val === false || val == null)
789
859
  continue;
790
860
  if (key === '_count') {
791
- withClause._count = translateCountSelect(ctx, mm, val);
792
- hasWith = true;
861
+ countVal = val;
862
+ picked.add('_count');
793
863
  continue;
794
864
  }
795
865
  const rel = ownLookup(mm.relations, key);
796
866
  if (rel) {
797
- setOwn(withClause, rel.name, translateWithOption(ctx, mm, rel.name, val, depth + 1));
867
+ setOwn(withClause, rel.name, translateWithOption(ctx, mm, rel.name, val, depth + 1, plan));
798
868
  hasWith = true;
869
+ picked.add(key);
799
870
  continue;
800
871
  }
801
872
  setOwn(scalar, renameField(mm, key), true);
802
873
  hasScalar = true;
874
+ picked.add(key);
875
+ }
876
+ if (countVal !== undefined) {
877
+ const core = planCounts(ctx, mm, countVal, plan);
878
+ if (core !== undefined) {
879
+ withClause._count = core;
880
+ hasWith = true;
881
+ }
803
882
  }
883
+ // A key this layer needs on each row (to attach a follow-up count) is
884
+ // selected for it and dropped again before the row is returned.
885
+ let added = false;
886
+ for (const field of countKeyFields(plan)) {
887
+ if (!Object.hasOwn(scalar, field)) {
888
+ setOwn(scalar, field, true);
889
+ hasScalar = true;
890
+ added = true;
891
+ }
892
+ }
893
+ // A `select` naming relations or `_count` and no scalar field returns no
894
+ // scalar in Prisma. Core reads "no scalar select" as every column, so the
895
+ // smallest projection that keeps the row addressable (its primary key) is
896
+ // asked for, and trimmed off again.
897
+ if (!hasScalar && picked.size > 0) {
898
+ for (const field of primaryKeyFields(ctx, mm))
899
+ setOwn(scalar, field, true);
900
+ hasScalar = Object.keys(scalar).length > 0;
901
+ added = hasScalar;
902
+ }
903
+ if (added)
904
+ plan.keep = picked;
804
905
  return { select: hasScalar ? scalar : undefined, with: hasWith ? withClause : undefined };
805
906
  }
806
907
  return { omit };
807
908
  }
909
+ function newReadPlan(mm, root) {
910
+ return { mm, root, counts: [], children: new Map() };
911
+ }
912
+ function planHasCounts(plan) {
913
+ if (plan.counts.length > 0)
914
+ return true;
915
+ for (const child of plan.children.values())
916
+ if (planHasCounts(child))
917
+ return true;
918
+ return false;
919
+ }
920
+ function planHasTrim(plan) {
921
+ if (plan.keep || plan.drop)
922
+ return true;
923
+ for (const child of plan.children.values())
924
+ if (planHasTrim(child))
925
+ return true;
926
+ return false;
927
+ }
928
+ /** The parent-side key fields this level's follow-up counts read. */
929
+ function countKeyFields(plan) {
930
+ return [...new Set(plan.counts.map((c) => c.parentField))];
931
+ }
932
+ function primaryKeyFields(ctx, mm) {
933
+ const meta = ownLookup(ctx.schema.tables, mm.table);
934
+ return (meta?.primaryKey ?? []).map((col) => meta?.reverseColumnMap?.[col] ?? col);
935
+ }
936
+ function prismaFieldName(ctx, mm, turbineField) {
937
+ return ownLookup(lookupsFor(ctx, mm).reverseFields, turbineField) ?? turbineField;
938
+ }
939
+ /** The one column of a single-column key, or undefined for a composite one. */
940
+ function singleColumn(key) {
941
+ if (!Array.isArray(key))
942
+ return key;
943
+ return key.length === 1 ? key[0] : undefined;
944
+ }
945
+ /**
946
+ * Decide where one level's `_count` is computed. Returns the value for core's
947
+ * `with._count` when core can answer it (top level, every count unfiltered),
948
+ * else records the counts on `plan` and returns undefined.
949
+ */
950
+ function planCounts(ctx, mm, val, plan) {
951
+ const parsed = translateCountSelect(ctx, mm, val);
952
+ const filtered = parsed !== true && parsed.some((c) => c.where !== undefined);
953
+ if (plan.root && !filtered) {
954
+ return parsed === true ? true : Object.fromEntries(parsed.map((c) => [c.relation, true]));
955
+ }
956
+ const meta = ownLookup(ctx.schema.tables, mm.table);
957
+ const relations = meta?.relations ?? {};
958
+ const wanted = parsed === true
959
+ ? Object.values(relations)
960
+ .filter((r) => r.type === 'hasMany' || r.type === 'manyToMany')
961
+ .map((r) => ({ relation: r.name, where: undefined }))
962
+ : parsed;
963
+ for (const { relation, where } of wanted) {
964
+ const rd = ownLookup(relations, relation);
965
+ const label = `${modelName(ctx, mm)}.${prismaRelationName(ctx, mm, relation)}`;
966
+ const parentColumn = rd ? singleColumn(rd.referenceKey) : undefined;
967
+ const childColumn = rd ? singleColumn(rd.foreignKey) : undefined;
968
+ if (rd?.type !== 'hasMany' || parentColumn === undefined || childColumn === undefined) {
969
+ throw new UnsupportedFeatureError(`a nested or filtered \`_count\` of "${label}"`, 'prisma-compat', rd?.type === 'manyToMany'
970
+ ? 'Below the top level, and with a `where`, only one-to-many relations are counted. Count the ' +
971
+ 'junction rows with a groupBy on the related model, or use an unfiltered top-level `_count`.'
972
+ : 'Below the top level, and with a `where`, only one-to-many relations on a single-column key are ' +
973
+ 'counted. Use a groupBy on the related model.');
974
+ }
975
+ const target = ownLookup(ctx.schema.tables, rd.to);
976
+ const targetModel = relTargetModel(ctx, mm, relation);
977
+ plan.counts.push({
978
+ relation,
979
+ table: rd.to,
980
+ parentField: meta?.reverseColumnMap?.[parentColumn] ?? parentColumn,
981
+ childField: target?.reverseColumnMap?.[childColumn] ?? childColumn,
982
+ ...(where !== undefined
983
+ ? { where: targetModel ? translateWhere(ctx, targetModel, where) : where }
984
+ : {}),
985
+ });
986
+ }
987
+ return undefined;
988
+ }
989
+ /** A value usable as a Map key that equals for equal key values (a Date by its instant). */
990
+ function countKeyOf(value) {
991
+ return value instanceof Date ? `date:${value.getTime()}` : value;
992
+ }
993
+ /** Every raw row at one plan level, in result order. */
994
+ function collectPlanRows(rows, plan, into) {
995
+ const level = into.get(plan) ?? [];
996
+ into.set(plan, level);
997
+ for (const row of rows) {
998
+ if (!isPlainRecord(row))
999
+ continue;
1000
+ level.push(row);
1001
+ for (const [rel, child] of plan.children) {
1002
+ const value = row[rel];
1003
+ const next = Array.isArray(value) ? value : value == null ? [] : [value];
1004
+ collectPlanRows(next, child, into);
1005
+ }
1006
+ }
1007
+ }
1008
+ /**
1009
+ * Run every count a {@link ReadPlan} holds and attach it to core's raw rows as
1010
+ * `_count`, keyed by turbine relation name (the reshape renames it).
1011
+ */
1012
+ async function attachPlannedCounts(table, raw, plan, passthrough) {
1013
+ const levels = new Map();
1014
+ collectPlanRows(Array.isArray(raw) ? raw : raw == null ? [] : [raw], plan, levels);
1015
+ for (const [level, rows] of levels) {
1016
+ if (level.counts.length === 0)
1017
+ continue;
1018
+ for (const row of rows)
1019
+ row._count = {};
1020
+ for (const req of level.counts) {
1021
+ const ids = [...new Set(rows.map((r) => r[req.parentField]).filter((v) => v !== null && v !== undefined))];
1022
+ const counts = new Map();
1023
+ if (ids.length > 0) {
1024
+ const byParent = { [req.childField]: { in: ids } };
1025
+ const groups = await table(req.table).groupBy({
1026
+ ...passthrough,
1027
+ by: [req.childField],
1028
+ where: req.where ? { AND: [byParent, req.where] } : byParent,
1029
+ _count: true,
1030
+ });
1031
+ for (const group of groups) {
1032
+ counts.set(countKeyOf(group[req.childField]), Number(group._count));
1033
+ }
1034
+ }
1035
+ for (const row of rows) {
1036
+ row._count[req.relation] = counts.get(countKeyOf(row[req.parentField])) ?? 0;
1037
+ }
1038
+ }
1039
+ }
1040
+ }
1041
+ /** Drop the keys this layer added (or an `omit` asked for) from reshaped, Prisma-named rows. */
1042
+ function trimPlannedRows(ctx, rows, plan) {
1043
+ const trimRow = (row, level) => {
1044
+ if (!isPlainRecord(row))
1045
+ return row;
1046
+ let out = row;
1047
+ if (level.keep) {
1048
+ out = {};
1049
+ for (const key of level.keep)
1050
+ if (Object.hasOwn(row, key))
1051
+ setOwn(out, key, row[key]);
1052
+ }
1053
+ else if (level.drop) {
1054
+ out = { ...row };
1055
+ for (const key of level.drop)
1056
+ delete out[key];
1057
+ }
1058
+ for (const [rel, child] of level.children) {
1059
+ const key = prismaRelationName(ctx, level.mm, rel);
1060
+ const value = out[key];
1061
+ if (value === undefined)
1062
+ continue;
1063
+ if (out === row)
1064
+ out = { ...row };
1065
+ out[key] = Array.isArray(value) ? value.map((v) => trimRow(v, child)) : trimRow(value, child);
1066
+ }
1067
+ return out;
1068
+ };
1069
+ return Array.isArray(rows) ? rows.map((r) => trimRow(r, plan)) : trimRow(rows, plan);
1070
+ }
808
1071
  const NO_WRITE_PROJECTION = {};
809
1072
  /**
810
1073
  * Refuse a write-projection key that names no field on the model.
@@ -849,9 +1112,9 @@ function assertWriteProjectionField(ctx, mm, op, clause, key) {
849
1112
  * SQL-level control is `pii: true` on the column, which is enforced in core and
850
1113
  * is unaffected by any of this.
851
1114
  *
852
- * A relation (or `_count`) key THROWS instead: a write returns its own row and
853
- * nothing else, so serving it is impossible, and the alternative is handing
854
- * back a row whose relation property is silently `undefined`, which would hide an unsupported projection.
1115
+ * A projection naming a relation (or `_count`) never reaches this function: the
1116
+ * delegate runs that write as the write plus a read-back (see
1117
+ * `projectsRelations` in makeDelegate). The refusals below are the backstop.
855
1118
  */
856
1119
  function resolveWriteProjection(ctx, mm, op, args) {
857
1120
  if (!args)
@@ -1007,7 +1270,7 @@ function assertNestedRelationKeys(label, opts) {
1007
1270
  * one arg with relation hops and then nests the other cannot spend two separate
1008
1271
  * budgets to reach the same stack depth.
1009
1272
  */
1010
- function translateWithOption(ctx, mm, turbineRel, val, depth = 0) {
1273
+ function translateWithOption(ctx, mm, turbineRel, val, depth = 0, parentPlan) {
1011
1274
  if (val === true)
1012
1275
  return true;
1013
1276
  const label = `${modelName(ctx, mm)}.${prismaRelationName(ctx, mm, turbineRel)}`;
@@ -1043,7 +1306,10 @@ function translateWithOption(ctx, mm, turbineRel, val, depth = 0) {
1043
1306
  '`select` / `include` / `omit` cannot be translated. Regenerate the map with ' +
1044
1307
  '`turbine migrate-from-prisma`, or drop the projection.');
1045
1308
  }
1046
- const proj = translateProjection(ctx, target, val, depth);
1309
+ const childPlan = newReadPlan(target, false);
1310
+ const proj = translateProjection(ctx, target, val, depth, childPlan);
1311
+ if (parentPlan)
1312
+ parentPlan.children.set(turbineRel, childPlan);
1047
1313
  if (proj.select)
1048
1314
  opt.select = proj.select;
1049
1315
  // Same silent drop as the top level: a nested `omit` names the sensitive
@@ -1060,14 +1326,12 @@ function isUnfilteredCountWhere(where) {
1060
1326
  return where === undefined || (isPlainRecord(where) && Object.values(where).every((v) => v === undefined));
1061
1327
  }
1062
1328
  /**
1063
- * Translate a Prisma `_count: { select: { rel: true } }` / `true` into Turbine
1064
- * `with._count`.
1065
- *
1066
- * Core counts a relation whole: `with._count` takes `true` or `{ rel: true }`.
1067
- * So a Prisma filtered count (`{ rel: { where } }`) is refused (E017) naming the
1068
- * alternative, a relation that is not on the model is E003, and so is any key
1069
- * but `select` under `_count` (a misspelled `selec` used to count EVERY relation,
1070
- * and a misspelled relation counted nothing, both without a word).
1329
+ * Validate a Prisma `_count` value and read it as the relations it counts:
1330
+ * `true` (every to-many relation) or a list of turbine relation names, each with
1331
+ * the caller's `where` when it filters anything. {@link planCounts} decides who
1332
+ * computes them. A relation that is not on the model is E003, and so is any key
1333
+ * but `select` under `_count` (a misspelled `selec` used to count EVERY
1334
+ * relation, and a misspelled relation counted nothing, both without a word).
1071
1335
  */
1072
1336
  function translateCountSelect(ctx, mm, val) {
1073
1337
  if (val === true)
@@ -1091,7 +1355,7 @@ function translateCountSelect(ctx, mm, val) {
1091
1355
  throw new ValidationError(`prisma-compat: \`_count.select\` on model "${model}" takes { <relation>: true }, ` +
1092
1356
  `received ${describeValue(val.select)}.`);
1093
1357
  }
1094
- const out = {};
1358
+ const out = [];
1095
1359
  for (const [key, v] of Object.entries(val.select)) {
1096
1360
  if (v === undefined || v === false || v === null)
1097
1361
  continue;
@@ -1104,7 +1368,7 @@ function translateCountSelect(ctx, mm, val) {
1104
1368
  ` Relations: ${known.join(', ') || '(none)'}.`);
1105
1369
  }
1106
1370
  if (v === true) {
1107
- setOwn(out, rel.name, true);
1371
+ out.push({ relation: rel.name });
1108
1372
  continue;
1109
1373
  }
1110
1374
  if (!isPlainRecord(v)) {
@@ -1119,16 +1383,7 @@ function translateCountSelect(ctx, mm, val) {
1119
1383
  (hint ? ` Did you mean "${hint}"?` : '') +
1120
1384
  ' The only key is "where".');
1121
1385
  }
1122
- if (!isUnfilteredCountWhere(v.where)) {
1123
- const target = relTargetModel(ctx, mm, rel.name);
1124
- const targetName = target ? modelName(ctx, target) : undefined;
1125
- const delegate = targetName ? (prismaPropertyAlias(targetName) ?? targetName) : '<model>';
1126
- throw new UnsupportedFeatureError(`a filtered relation count (\`_count.select.${key}.where\` on model "${model}")`, 'prisma-compat', 'Turbine counts every row of a relation, so the filter would be dropped and the number would be wrong. ' +
1127
- `Count the filtered rows through the related model instead: prisma.${delegate}.count({ where: ... }) ` +
1128
- `with the foreign key and your filter, or prisma.${delegate}.groupBy({ by: [<foreign key>], _count: true }) ` +
1129
- 'for many parents at once.');
1130
- }
1131
- setOwn(out, rel.name, true);
1386
+ out.push(isUnfilteredCountWhere(v.where) ? { relation: rel.name } : { relation: rel.name, where: v.where });
1132
1387
  }
1133
1388
  return out;
1134
1389
  }
@@ -1154,7 +1409,7 @@ function translateFieldList(ctx, mm, option, val) {
1154
1409
  * `orderBy` are translated first, so the cursor step works in turbine-field
1155
1410
  * space.
1156
1411
  */
1157
- function translateReadArgs(ctx, mm, prismaArgs, kind) {
1412
+ function translateReadArgs(ctx, mm, prismaArgs, kind, plan = newReadPlan(mm, true)) {
1158
1413
  const t = {};
1159
1414
  // FIRST, so a per-call `stableRelationOrder` overrides it: the client-level
1160
1415
  // option is a default, the arg is an instruction.
@@ -1167,7 +1422,7 @@ function translateReadArgs(ctx, mm, prismaArgs, kind) {
1167
1422
  t.where = translateWhere(ctx, mm, prismaArgs.where);
1168
1423
  if (prismaArgs.orderBy !== undefined)
1169
1424
  t.orderBy = translateOrderBy(ctx, mm, prismaArgs.orderBy);
1170
- const proj = translateProjection(ctx, mm, prismaArgs);
1425
+ const proj = translateProjection(ctx, mm, prismaArgs, 0, plan);
1171
1426
  if (proj.select)
1172
1427
  t.select = proj.select;
1173
1428
  if (proj.omit)
@@ -1328,7 +1583,7 @@ function translateWriteData(ctx, mm, data, depth = 0) {
1328
1583
  const rel = ownLookup(mm.relations, key);
1329
1584
  if (rel && isPlainRecord(val) && Object.keys(val).some((k) => NESTED_WRITE_OPS.has(k))) {
1330
1585
  const target = relTargetModel(ctx, mm, rel.name);
1331
- setOwn(out, rel.name, translateNestedWrite(ctx, target, val, depth + 1));
1586
+ setOwn(out, rel.name, translateNestedWrite(ctx, target, val, depth + 1, rel.cardinality === 'one'));
1332
1587
  continue;
1333
1588
  }
1334
1589
  setOwn(out, renameField(mm, key), val);
@@ -1355,13 +1610,21 @@ function isExpressionNode(value) {
1355
1610
  * changes is HOW: a typed refusal instead of a `RangeError` raised before core
1356
1611
  * is reached at all (measured: a 1,000-hop `create` chain, a 43 KB body).
1357
1612
  */
1358
- function translateNestedWrite(ctx, target, ops, depth) {
1613
+ function translateNestedWrite(ctx, target, ops, depth, toOne = false) {
1359
1614
  const out = {};
1615
+ // Rows a nested write CREATES get the target model's client defaults
1616
+ // (`cuid()` / `uuid()` ids, `@default(now())`, `@updatedAt`) and rows it
1617
+ // UPDATES get `@updatedAt`, exactly as the top-level row does: Prisma fills
1618
+ // them at every depth, and a nested row without its id reached the database
1619
+ // as NULL.
1620
+ const created = (p) => target ? translateWriteData(ctx, target, applyCreateDefaults(target, p), depth + 1) : p;
1360
1621
  for (const [op, payload] of Object.entries(ops)) {
1361
1622
  switch (op) {
1362
1623
  case 'create':
1624
+ out[op] = mapMaybeArray(payload, created);
1625
+ break;
1363
1626
  case 'createMany':
1364
- out[op] = mapMaybeArray(payload, (p) => (target ? translateWriteData(ctx, target, p, depth + 1) : p));
1627
+ out[op] = translateNestedCreateMany(payload, created);
1365
1628
  break;
1366
1629
  case 'connect':
1367
1630
  case 'disconnect':
@@ -1370,9 +1633,18 @@ function translateNestedWrite(ctx, target, ops, depth) {
1370
1633
  out[op] = mapMaybeArray(payload, (p) => (target ? translateWhere(ctx, target, p, depth + 1) : p));
1371
1634
  break;
1372
1635
  case 'deleteMany':
1636
+ out[op] = mapMaybeArray(payload, (p) => translateWhereDataPair(ctx, target, op, p, depth + 1));
1637
+ break;
1373
1638
  case 'updateMany':
1639
+ out[op] = mapMaybeArray(payload, (p) => translateWhereDataPair(ctx, target, op, p, depth + 1, true));
1640
+ break;
1374
1641
  case 'update':
1375
- out[op] = mapMaybeArray(payload, (p) => translateWhereDataPair(ctx, target, op, p, depth + 1));
1642
+ out[op] = mapMaybeArray(payload, (p) => {
1643
+ const pair = translateWhereDataPair(ctx, target, op, p, depth + 1, true);
1644
+ // Prisma's to-one `update` takes the data itself (`profile: { update:
1645
+ // { bio } }`) as well as `{ data }`; core reads `{ data }`.
1646
+ return toOne && isPlainRecord(p) && !('data' in p) && !('where' in p) ? { data: pair } : pair;
1647
+ });
1376
1648
  break;
1377
1649
  case 'connectOrCreate':
1378
1650
  out[op] = mapMaybeArray(payload, (p) => translateConnectOrCreate(ctx, target, p, depth + 1));
@@ -1405,19 +1677,34 @@ function assertNestedPayloadKeys(op, p, allowed) {
1405
1677
  }
1406
1678
  }
1407
1679
  /** A `{ where?, data }` pair (nested update/updateMany), or a bare data object. */
1408
- function translateWhereDataPair(ctx, target, op, p, depth) {
1680
+ function translateWhereDataPair(ctx, target, op, p, depth, touch = false) {
1409
1681
  if (!isPlainRecord(p))
1410
1682
  return p;
1683
+ const data = (d) => target ? translateWriteData(ctx, target, touch ? applyUpdateTouch(target, d) : d, depth) : d;
1411
1684
  if ('data' in p || 'where' in p) {
1412
1685
  assertNestedPayloadKeys(op, p, ['where', 'data']);
1413
1686
  const out = {};
1414
1687
  if (p.where !== undefined)
1415
1688
  out.where = target ? translateWhere(ctx, target, p.where, depth) : p.where;
1416
1689
  if (p.data !== undefined)
1417
- out.data = target ? translateWriteData(ctx, target, p.data, depth) : p.data;
1690
+ out.data = data(p.data);
1418
1691
  return out;
1419
1692
  }
1420
- return target ? translateWriteData(ctx, target, p, depth) : p;
1693
+ return data(p);
1694
+ }
1695
+ /**
1696
+ * A nested `createMany: { data, skipDuplicates }`. Its rows are translated (and
1697
+ * get client defaults) like nested `create` rows; the wrapper keys pass through
1698
+ * for core to validate.
1699
+ */
1700
+ function translateNestedCreateMany(payload, created) {
1701
+ if (!isPlainRecord(payload))
1702
+ return payload;
1703
+ assertNestedPayloadKeys('createMany', payload, ['data', 'skipDuplicates']);
1704
+ const out = { ...payload };
1705
+ if (payload.data !== undefined)
1706
+ out.data = mapMaybeArray(payload.data, created);
1707
+ return out;
1421
1708
  }
1422
1709
  function translateConnectOrCreate(ctx, target, p, depth) {
1423
1710
  if (!isPlainRecord(p))
@@ -1426,8 +1713,9 @@ function translateConnectOrCreate(ctx, target, p, depth) {
1426
1713
  const out = {};
1427
1714
  if (p.where !== undefined)
1428
1715
  out.where = target ? translateWhere(ctx, target, p.where, depth) : p.where;
1429
- if (p.create !== undefined)
1430
- out.create = target ? translateWriteData(ctx, target, p.create, depth) : p.create;
1716
+ if (p.create !== undefined) {
1717
+ out.create = target ? translateWriteData(ctx, target, applyCreateDefaults(target, p.create), depth) : p.create;
1718
+ }
1431
1719
  return out;
1432
1720
  }
1433
1721
  function translateUpsertNested(ctx, target, p, depth) {
@@ -1437,10 +1725,12 @@ function translateUpsertNested(ctx, target, p, depth) {
1437
1725
  const out = {};
1438
1726
  if (p.where !== undefined)
1439
1727
  out.where = target ? translateWhere(ctx, target, p.where, depth) : p.where;
1440
- if (p.create !== undefined)
1441
- out.create = target ? translateWriteData(ctx, target, p.create, depth) : p.create;
1442
- if (p.update !== undefined)
1443
- out.update = target ? translateWriteData(ctx, target, p.update, depth) : p.update;
1728
+ if (p.create !== undefined) {
1729
+ out.create = target ? translateWriteData(ctx, target, applyCreateDefaults(target, p.create), depth) : p.create;
1730
+ }
1731
+ if (p.update !== undefined) {
1732
+ out.update = target ? translateWriteData(ctx, target, applyUpdateTouch(target, p.update), depth) : p.update;
1733
+ }
1444
1734
  return out;
1445
1735
  }
1446
1736
  // --- aggregate / groupBy translation --------------------------------------
@@ -1923,6 +2213,123 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
1923
2213
  }
1924
2214
  }, batchable);
1925
2215
  };
2216
+ /**
2217
+ * One read operation. The {@link ReadPlan} filled by the translation says
2218
+ * whether this layer has counts to run (then the read and its counts share a
2219
+ * transaction, and a `$transaction([...])` array takes its sequential path)
2220
+ * and keys to trim off the reshaped rows.
2221
+ */
2222
+ const readCall = (op, args, kind, read, build, reshape) => {
2223
+ let plan = newReadPlan(mm, true);
2224
+ const finish = (raw) => {
2225
+ const shaped = reshape(raw);
2226
+ return planHasTrim(plan) ? trimPlannedRows(ctx, shaped, plan) : shaped;
2227
+ };
2228
+ const withCounts = async (table, t) => {
2229
+ const raw = await read(table(mm.table), t);
2230
+ const passthrough = {};
2231
+ if (t.skipGlobalFilters !== undefined)
2232
+ passthrough.skipGlobalFilters = t.skipGlobalFilters;
2233
+ if (t.timeout !== undefined)
2234
+ passthrough.timeout = t.timeout;
2235
+ await attachPlannedCounts(table, raw, plan, passthrough);
2236
+ return finish(raw);
2237
+ };
2238
+ return defer(op, args, () => {
2239
+ plan = newReadPlan(mm, true);
2240
+ const a = kind === 'unique' ? requireWhere(args, op) : (args ?? {});
2241
+ return translateReadArgs(ctx, mm, a, kind, plan);
2242
+ }, (qi, t) => (planHasCounts(plan) ? runInTx((table) => withCounts(table, t)) : read(qi, t).then(finish)), {
2243
+ build,
2244
+ reshape: finish,
2245
+ nested: () => planHasCounts(plan),
2246
+ execInTx: (table, t) => (planHasCounts(plan) ? withCounts(table, t) : read(table(mm.table), t).then(finish)),
2247
+ });
2248
+ };
2249
+ /**
2250
+ * A write whose `include` / `select` names a relation or `_count`. A write
2251
+ * statement returns its own row only, so these run as Prisma's semantics
2252
+ * describe them: the write, then a read of the written row by primary key with
2253
+ * the caller's projection, in ONE transaction (a delete reads first, since
2254
+ * afterwards there is nothing to read). The read is an ordinary compat read,
2255
+ * so nested and filtered counts work there too.
2256
+ */
2257
+ const projectsRelations = (a) => {
2258
+ if (!a)
2259
+ return false;
2260
+ const include = a.include;
2261
+ if (isPlainRecord(include) && Object.values(include).some((v) => v !== false && v != null))
2262
+ return true;
2263
+ const select = a.select;
2264
+ if (!isPlainRecord(select))
2265
+ return false;
2266
+ return Object.entries(select).some(([key, v]) => v !== false && v != null && (key === '_count' || ownLookup(mm.relations, key) !== undefined));
2267
+ };
2268
+ const projectionOf = (a) => {
2269
+ const out = {};
2270
+ if (a.select !== undefined)
2271
+ out.select = a.select;
2272
+ if (a.include !== undefined)
2273
+ out.include = a.include;
2274
+ if (a.omit !== undefined)
2275
+ out.omit = a.omit;
2276
+ return out;
2277
+ };
2278
+ /** Validate the projection before anything is written (its errors would otherwise follow the write). */
2279
+ const checkReadProjection = (a) => {
2280
+ translateProjection(ctx, mm, projectionOf(a), 0, newReadPlan(mm, true));
2281
+ };
2282
+ /** The Prisma `where` naming one written row by primary key, from core's raw row. */
2283
+ const primaryKeyWhere = (op, raw) => {
2284
+ const fields = primaryKeyFields(ctx, mm);
2285
+ if (fields.length === 0 || !isPlainRecord(raw)) {
2286
+ throw new UnsupportedFeatureError(`include / a relation select on ${op} of model "${modelName(ctx, mm)}"`, 'prisma-compat', 'The written row is read back by primary key and this model has none. Read the relation with a ' +
2287
+ 'separate findUnique inside the same $transaction.');
2288
+ }
2289
+ const where = {};
2290
+ for (const field of fields)
2291
+ setOwn(where, prismaFieldName(ctx, mm, field), raw[field]);
2292
+ return where;
2293
+ };
2294
+ const readWritten = async (table, where, a) => {
2295
+ const plan = newReadPlan(mm, true);
2296
+ const t = translateReadArgs(ctx, mm, { where, ...projectionOf(a) }, 'unique', plan);
2297
+ const raw = await table(mm.table).findUnique(t);
2298
+ if (planHasCounts(plan))
2299
+ await attachPlannedCounts(table, raw, plan, {});
2300
+ const shaped = reshapeRowOrNull(ctx, mm, raw);
2301
+ return planHasTrim(plan) ? trimPlannedRows(ctx, shaped, plan) : shaped;
2302
+ };
2303
+ const writeThenRead = (op, a, write) => {
2304
+ if (op === 'delete') {
2305
+ return async (table) => {
2306
+ const before = await readWritten(table, a.where, a);
2307
+ await write(table(mm.table));
2308
+ return before;
2309
+ };
2310
+ }
2311
+ return async (table) => readWritten(table, primaryKeyWhere(op, await write(table(mm.table))), a);
2312
+ };
2313
+ /**
2314
+ * A write's own row, Prisma-shaped. Core returns the relations a nested write
2315
+ * touched (it reads the written tree back); a Prisma write without `include`
2316
+ * returns scalars only, so those keys are dropped rather than handed to a
2317
+ * caller who never asked for them.
2318
+ */
2319
+ const writtenRow = (raw) => {
2320
+ const row = reshapeRow(ctx, mm, raw);
2321
+ if (!isPlainRecord(row))
2322
+ return row;
2323
+ let out = row;
2324
+ for (const key of Object.keys(row)) {
2325
+ if (key !== '_count' && ownLookup(mm.relations, key) === undefined)
2326
+ continue;
2327
+ if (out === row)
2328
+ out = { ...row };
2329
+ delete out[key];
2330
+ }
2331
+ return out;
2332
+ };
1926
2333
  const requireWhere = (args, op) => {
1927
2334
  if (!args || args.where === undefined) {
1928
2335
  throw new ValidationError(`prisma-compat: ${op} on "${modelName(ctx, mm)}" requires a \`where\`.`);
@@ -1930,28 +2337,35 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
1930
2337
  return args;
1931
2338
  };
1932
2339
  return {
1933
- findMany: (args = {}) => defer('findMany', args, () => translateReadArgs(ctx, mm, args, 'many'), (qi, t) => qi.findMany(t).then((r) => reshapeRows(ctx, mm, r)), { build: (qi, t) => qi.buildFindMany(t), reshape: (raw) => reshapeRows(ctx, mm, raw) }),
1934
- findFirst: (args = {}) => defer('findFirst', args, () => translateReadArgs(ctx, mm, args, 'first'), (qi, t) => qi.findFirst(t).then((r) => reshapeRowOrNull(ctx, mm, r)), { build: (qi, t) => qi.buildFindFirst(t), reshape: (raw) => reshapeRowOrNull(ctx, mm, raw) }),
1935
- findUnique: (args) => defer('findUnique', args, () => translateReadArgs(ctx, mm, requireWhere(args, 'findUnique'), 'unique'), (qi, t) => qi.findUnique(t).then((r) => reshapeRowOrNull(ctx, mm, r)), { build: (qi, t) => qi.buildFindUnique(t), reshape: (raw) => reshapeRowOrNull(ctx, mm, raw) }),
1936
- findFirstOrThrow: (args = {}) => defer('findFirstOrThrow', args, () => translateReadArgs(ctx, mm, args, 'first'), (qi, t) => qi.findFirstOrThrow(t).then((r) => reshapeRow(ctx, mm, r)), { build: (qi, t) => qi.buildFindFirstOrThrow(t), reshape: (raw) => reshapeRow(ctx, mm, raw) }),
1937
- findUniqueOrThrow: (args) => defer('findUniqueOrThrow', args, () => translateReadArgs(ctx, mm, requireWhere(args, 'findUniqueOrThrow'), 'unique'), (qi, t) => qi.findUniqueOrThrow(t).then((r) => reshapeRow(ctx, mm, r)), { build: (qi, t) => qi.buildFindUniqueOrThrow(t), reshape: (raw) => reshapeRow(ctx, mm, raw) }),
2340
+ findMany: (args = {}) => readCall('findMany', args, 'many', (qi, t) => qi.findMany(t), (qi, t) => qi.buildFindMany(t), (raw) => reshapeRows(ctx, mm, raw)),
2341
+ findFirst: (args = {}) => readCall('findFirst', args, 'first', (qi, t) => qi.findFirst(t), (qi, t) => qi.buildFindFirst(t), (raw) => reshapeRowOrNull(ctx, mm, raw)),
2342
+ findUnique: (args) => readCall('findUnique', args, 'unique', (qi, t) => qi.findUnique(t), (qi, t) => qi.buildFindUnique(t), (raw) => reshapeRowOrNull(ctx, mm, raw)),
2343
+ findFirstOrThrow: (args = {}) => readCall('findFirstOrThrow', args, 'first', (qi, t) => qi.findFirstOrThrow(t), (qi, t) => qi.buildFindFirstOrThrow(t), (raw) => reshapeRow(ctx, mm, raw)),
2344
+ findUniqueOrThrow: (args) => readCall('findUniqueOrThrow', args, 'unique', (qi, t) => qi.findUniqueOrThrow(t), (qi, t) => qi.buildFindUniqueOrThrow(t), (raw) => reshapeRow(ctx, mm, raw)),
1938
2345
  create: (args) => {
1939
2346
  // Resolved inside the translate thunk below (so it validates before the
1940
2347
  // write runs and stays deferred), read back by every result path.
1941
2348
  let proj = NO_WRITE_PROJECTION;
1942
- const shape = (raw) => applyWriteProjection(proj, reshapeRow(ctx, mm, raw));
2349
+ const shape = (raw) => applyWriteProjection(proj, writtenRow(raw));
2350
+ const a = (args ?? {});
2351
+ const relational = projectsRelations(a);
2352
+ const projected = (t) => writeThenRead('create', a, (qi) => qi.create(t));
1943
2353
  return defer('create', args, () => {
1944
- proj = resolveWriteProjection(ctx, mm, 'create', args);
2354
+ if (relational)
2355
+ checkReadProjection(a);
2356
+ else
2357
+ proj = resolveWriteProjection(ctx, mm, 'create', a);
1945
2358
  const t = {
1946
- data: translateWriteData(ctx, mm, applyCreateDefaults(mm, args.data)),
2359
+ data: translateWriteData(ctx, mm, applyCreateDefaults(mm, a.data)),
1947
2360
  ...coreWriteProjection(mm, proj),
1948
2361
  };
1949
- applyNativeOptions(CREATE_OPTIONS, args, t);
2362
+ applyNativeOptions(CREATE_OPTIONS, a, t);
1950
2363
  return t;
1951
- }, (qi, t) => qi.create(t).then(shape), {
2364
+ }, (qi, t) => (relational ? runInTx(projected(t)) : qi.create(t).then(shape)), {
1952
2365
  build: (qi, t) => qi.buildCreate(t),
1953
2366
  reshape: shape,
1954
- nested: (t) => hasNestedKeys(ctx, mm, t.data),
2367
+ nested: (t) => relational || hasNestedKeys(ctx, mm, t.data),
2368
+ execInTx: (table, t) => (relational ? projected(t)(table) : table(mm.table).create(t).then(shape)),
1955
2369
  });
1956
2370
  },
1957
2371
  createMany: (args) => defer('createMany', args, () => {
@@ -1991,10 +2405,15 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
1991
2405
  }),
1992
2406
  update: (args) => {
1993
2407
  let proj = NO_WRITE_PROJECTION;
1994
- const shape = (raw) => applyWriteProjection(proj, reshapeRow(ctx, mm, raw));
2408
+ const shape = (raw) => applyWriteProjection(proj, writtenRow(raw));
2409
+ const relational = projectsRelations(args);
2410
+ const projected = (t) => writeThenRead('update', args, (qi) => qi.update(t));
1995
2411
  return defer('update', args, () => {
1996
2412
  const a = requireWhere(args, 'update');
1997
- proj = resolveWriteProjection(ctx, mm, 'update', a);
2413
+ if (relational)
2414
+ checkReadProjection(a);
2415
+ else
2416
+ proj = resolveWriteProjection(ctx, mm, 'update', a);
1998
2417
  const t = {
1999
2418
  where: translateWhere(ctx, mm, a.where),
2000
2419
  data: translateWriteData(ctx, mm, applyUpdateTouch(mm, a.data)),
@@ -2011,10 +2430,11 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2011
2430
  };
2012
2431
  }
2013
2432
  return t;
2014
- }, (qi, t) => qi.update(t).then(shape), {
2433
+ }, (qi, t) => (relational ? runInTx(projected(t)) : qi.update(t).then(shape)), {
2015
2434
  build: (qi, t) => qi.buildUpdate(t),
2016
2435
  reshape: shape,
2017
- nested: (t) => hasNestedKeys(ctx, mm, t.data),
2436
+ nested: (t) => relational || hasNestedKeys(ctx, mm, t.data),
2437
+ execInTx: (table, t) => (relational ? projected(t)(table) : table(mm.table).update(t).then(shape)),
2018
2438
  });
2019
2439
  },
2020
2440
  updateMany: (args) => defer('updateMany', args, () => {
@@ -2034,14 +2454,24 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2034
2454
  }, (qi, t) => qi.updateMany(t), { build: (qi, t) => qi.buildUpdateMany(t), reshape: (raw) => raw }),
2035
2455
  delete: (args) => {
2036
2456
  let proj = NO_WRITE_PROJECTION;
2037
- const shape = (raw) => applyWriteProjection(proj, reshapeRow(ctx, mm, raw));
2457
+ const shape = (raw) => applyWriteProjection(proj, writtenRow(raw));
2458
+ const relational = projectsRelations(args);
2459
+ const projected = (t) => writeThenRead('delete', args, (qi) => qi.delete(t));
2038
2460
  return defer('delete', args, () => {
2039
2461
  const a = requireWhere(args, 'delete');
2040
- proj = resolveWriteProjection(ctx, mm, 'delete', a);
2462
+ if (relational)
2463
+ checkReadProjection(a);
2464
+ else
2465
+ proj = resolveWriteProjection(ctx, mm, 'delete', a);
2041
2466
  const t = { where: translateWhere(ctx, mm, a.where), ...coreWriteProjection(mm, proj) };
2042
2467
  applyNativeOptions(DELETE_OPTIONS, a, t);
2043
2468
  return t;
2044
- }, (qi, t) => qi.delete(t).then(shape), { build: (qi, t) => qi.buildDelete(t), reshape: shape });
2469
+ }, (qi, t) => (relational ? runInTx(projected(t)) : qi.delete(t).then(shape)), {
2470
+ build: (qi, t) => qi.buildDelete(t),
2471
+ reshape: shape,
2472
+ nested: () => relational,
2473
+ execInTx: (table, t) => (relational ? projected(t)(table) : table(mm.table).delete(t).then(shape)),
2474
+ });
2045
2475
  },
2046
2476
  deleteMany: (args = {}) => defer('deleteMany', args, () => {
2047
2477
  const a = args;
@@ -2055,10 +2485,15 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2055
2485
  }, (qi, t) => qi.deleteMany(t), { build: (qi, t) => qi.buildDeleteMany(t), reshape: (raw) => raw }),
2056
2486
  upsert: (args) => {
2057
2487
  let proj = NO_WRITE_PROJECTION;
2058
- const shape = (raw) => applyWriteProjection(proj, reshapeRow(ctx, mm, raw));
2488
+ const shape = (raw) => applyWriteProjection(proj, writtenRow(raw));
2489
+ const relational = projectsRelations(args);
2490
+ const projected = (t) => writeThenRead('upsert', args, (qi) => qi.upsert(t));
2059
2491
  return defer('upsert', args, () => {
2060
2492
  const a = requireWhere(args, 'upsert');
2061
- proj = resolveWriteProjection(ctx, mm, 'upsert', a);
2493
+ if (relational)
2494
+ checkReadProjection(a);
2495
+ else
2496
+ proj = resolveWriteProjection(ctx, mm, 'upsert', a);
2062
2497
  const t = {
2063
2498
  where: translateWhere(ctx, mm, a.where),
2064
2499
  create: translateWriteData(ctx, mm, applyCreateDefaults(mm, a.create)),
@@ -2071,13 +2506,13 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2071
2506
  // Core `upsert` has Prisma's semantics itself (it looks the row up by
2072
2507
  // `where` whenever one conflict statement would mean something else,
2073
2508
  // and runs nested writes), so the adapter passes it straight through.
2074
- (qi, t) => qi.upsert(t).then(shape), {
2509
+ (qi, t) => (relational ? runInTx(projected(t)) : qi.upsert(t).then(shape)), {
2075
2510
  build: (qi, t) => qi.buildUpsert(t),
2076
2511
  reshape: shape,
2077
2512
  // Batchable only when core would run it as one statement. PowDB has
2078
2513
  // no deferred statements at all, so it always takes the tx path.
2079
- nested: (t, qi) => qi.upsertNeedsLookup?.(t) ?? true,
2080
- execInTx: async (table, t) => shape(await table(mm.table).upsert(t)),
2514
+ nested: (t, qi) => relational || (qi.upsertNeedsLookup?.(t) ?? true),
2515
+ execInTx: async (table, t) => (relational ? projected(t)(table) : shape(await table(mm.table).upsert(t))),
2081
2516
  });
2082
2517
  },
2083
2518
  count: (args = {}) => {
@@ -2106,10 +2541,21 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2106
2541
  }, (qi, t) => qi.count(t), { build: (qi, t) => qi.buildCount(t), reshape: (raw) => raw });
2107
2542
  },
2108
2543
  aggregate: (args) => defer('aggregate', args, () => translateAggregateArgs(ctx, mm, args, false), (qi, t) => qi.aggregate(t).then((r) => reshapeAggregate(ctx, mm, r)), { build: (qi, t) => qi.buildAggregate(t), reshape: (raw) => reshapeAggregate(ctx, mm, raw) }),
2109
- groupBy: (args) => defer('groupBy', args, () => translateAggregateArgs(ctx, mm, args, true), (qi, t) => qi.groupBy(t).then((rows) => rows.map((r) => reshapeGroupRow(ctx, mm, r))), {
2110
- build: (qi, t) => qi.buildGroupBy(t),
2111
- reshape: (raw) => raw.map((r) => reshapeGroupRow(ctx, mm, r)),
2112
- }),
2544
+ groupBy: (args) => {
2545
+ // Core always counts a group when `_count` is omitted (its documented
2546
+ // default); Prisma returns only the blocks the call names. The count
2547
+ // still runs (an `orderBy: { _count }` reads it), it is just not handed
2548
+ // back unasked.
2549
+ const askedForCount = isPlainRecord(args) && args._count !== undefined && args._count !== false;
2550
+ const reshape = (raw) => raw.map((r) => {
2551
+ const row = reshapeGroupRow(ctx, mm, r);
2552
+ if (askedForCount || !isPlainRecord(row) || !Object.hasOwn(row, '_count'))
2553
+ return row;
2554
+ const { _count: _dropped, ...rest } = row;
2555
+ return rest;
2556
+ });
2557
+ return defer('groupBy', args, () => translateAggregateArgs(ctx, mm, args, true), (qi, t) => qi.groupBy(t).then(reshape), { build: (qi, t) => qi.buildGroupBy(t), reshape });
2558
+ },
2113
2559
  };
2114
2560
  }
2115
2561
  function poolOf(db) {
@@ -2129,7 +2575,7 @@ function placeholderOf(db) {
2129
2575
  * injection-safe. `Prisma.raw(...)` fragments are the sole verbatim splice, by
2130
2576
  * contract.
2131
2577
  */
2132
- function flattenTemplate(strings, values, ph) {
2578
+ function flattenTemplate(strings, values, ph, fragmentOf) {
2133
2579
  const params = [];
2134
2580
  let text = '';
2135
2581
  const append = (segStrings, segValues) => {
@@ -2137,8 +2583,9 @@ function flattenTemplate(strings, values, ph) {
2137
2583
  text += segStrings[i];
2138
2584
  if (i < segValues.length) {
2139
2585
  const v = segValues[i];
2140
- if (isSqlFragment(v)) {
2141
- append(v.strings, v.values);
2586
+ const fragment = fragmentOf(v);
2587
+ if (fragment) {
2588
+ append(fragment.strings, fragment.values);
2142
2589
  }
2143
2590
  else {
2144
2591
  params.push(v);
@@ -2157,17 +2604,43 @@ function flattenTemplate(strings, values, ph) {
2157
2604
  * (`$queryRaw` → rows, `$executeRaw` → affected-row count). The only difference
2158
2605
  * is which connection the executor runs on.
2159
2606
  */
2160
- function makeRawSurface(exec, ph) {
2607
+ function makeRawSurface(exec, ph, fragmentOf) {
2608
+ /**
2609
+ * The statement a `$queryRaw` / `$executeRaw` call means. Prisma takes either a
2610
+ * tagged template or ONE fragment (`$queryRaw(Prisma.sql\`...\`)`). The
2611
+ * fragment form used to be read as a template whose `strings` was the
2612
+ * fragment object itself, which has no indices, so the statement sent was the
2613
+ * empty string and the call resolved to `[]` without a word.
2614
+ */
2615
+ const compose = (first, values, method) => {
2616
+ const fragment = fragmentOf(first);
2617
+ if (fragment) {
2618
+ if (values.length > 0) {
2619
+ throw new ValidationError(`prisma-compat: ${method}(fragment) takes the fragment alone; ${values.length} further ` +
2620
+ 'argument(s) would be ignored. Interpolate the values inside the fragment instead.');
2621
+ }
2622
+ return flattenTemplate(fragment.strings, fragment.values, ph, fragmentOf);
2623
+ }
2624
+ // Anything else that is not a template's strings array (a plain string, an
2625
+ // object that is not a recognized fragment) would flatten to an empty or
2626
+ // character-split statement. Prisma refuses those too.
2627
+ if (!Array.isArray(first)) {
2628
+ throw new ValidationError(`prisma-compat: ${method} takes a tagged template (${method}\`SELECT ...\`) or one fragment ` +
2629
+ `(${method}(Prisma.sql\`SELECT ...\`)), received ${describeValue(first)}. ` +
2630
+ `For SQL text built at runtime use ${method}Unsafe(text, ...values).`);
2631
+ }
2632
+ return flattenTemplate(first, values, ph, fragmentOf);
2633
+ };
2161
2634
  return {
2162
2635
  $queryRaw: async (strings, ...values) => {
2163
- const { text, params } = flattenTemplate(strings, values, ph);
2636
+ const { text, params } = compose(strings, values, '$queryRaw');
2164
2637
  return (await exec(text, params, '$queryRaw')).rows;
2165
2638
  },
2166
2639
  $queryRawUnsafe: async (sql, ...params) => {
2167
2640
  return (await exec(sql, params, '$queryRawUnsafe')).rows;
2168
2641
  },
2169
2642
  $executeRaw: async (strings, ...values) => {
2170
- const { text, params } = flattenTemplate(strings, values, ph);
2643
+ const { text, params } = compose(strings, values, '$executeRaw');
2171
2644
  return (await exec(text, params, '$executeRaw')).rowCount ?? 0;
2172
2645
  },
2173
2646
  $executeRawUnsafe: async (sql, ...params) => {
@@ -2176,6 +2649,33 @@ function makeRawSurface(exec, ph) {
2176
2649
  };
2177
2650
  }
2178
2651
  // ---------------------------------------------------------------------------
2652
+ // Core interop: the Turbine client under a compat client
2653
+ // ---------------------------------------------------------------------------
2654
+ /**
2655
+ * Every compat client and transaction client this module builds, mapped to the
2656
+ * core client or core transaction it runs on. A WeakMap rather than a property,
2657
+ * so nothing is added to a surface whose every key is a model name or a Prisma
2658
+ * `$` member, and a hand-made lookalike object is never mistaken for one.
2659
+ */
2660
+ const CORE_OF = new WeakMap();
2661
+ /** Each compat client's way of wrapping a core transaction it did not open. */
2662
+ const BIND_OF = new WeakMap();
2663
+ export function turbineOf(compat) {
2664
+ const core = typeof compat === 'object' && compat !== null ? CORE_OF.get(compat) : undefined;
2665
+ if (core === undefined) {
2666
+ throw new ValidationError('prisma-compat: turbineOf takes a client made by createPrismaCompatClient, or the `tx` one of its ' +
2667
+ '$transaction callbacks receives.');
2668
+ }
2669
+ return core;
2670
+ }
2671
+ export function bindTransaction(compat, tx) {
2672
+ const bind = typeof compat === 'object' && compat !== null ? BIND_OF.get(compat) : undefined;
2673
+ if (!bind) {
2674
+ throw new ValidationError('prisma-compat: bindTransaction takes a client made by createPrismaCompatClient (not a transaction client).');
2675
+ }
2676
+ return bind(tx);
2677
+ }
2678
+ // ---------------------------------------------------------------------------
2179
2679
  // createPrismaCompatClient
2180
2680
  // ---------------------------------------------------------------------------
2181
2681
  /**
@@ -2405,6 +2905,7 @@ export function createPrismaCompatClient(client, map, options = {}) {
2405
2905
  stablePkOrder: options.stablePkOrder ?? false,
2406
2906
  prismaErrorCodes: options.prismaErrorCodes ?? false,
2407
2907
  },
2908
+ fragmentOf: options.prismaNamespace === undefined ? ownFragment : foreignFragmentReader(options.prismaNamespace),
2408
2909
  };
2409
2910
  // Every model the client exposes: the map's Prisma models, plus the implicit
2410
2911
  // many-to-many junction tables (see below). Both delegate loops (base and
@@ -2433,6 +2934,24 @@ export function createPrismaCompatClient(client, map, options = {}) {
2433
2934
  baseDelegates.set(prismaModel, makeDelegate(ctx, mm, () => db.table(mm.table), (fn) => db.$transaction((tx) => fn((n) => tx.table(n)))));
2434
2935
  }
2435
2936
  const ph = placeholderOf(db);
2937
+ // `$connect` / `$disconnect` used to be no-ops, so a script that ended with
2938
+ // `await prisma.$disconnect()` kept the pool open and never exited. One
2939
+ // closing promise per wrapped client: every extended client shares it, and a
2940
+ // second call resolves with the first instead of ending the pool twice.
2941
+ let closing;
2942
+ const lifecycle = {
2943
+ connect: async () => {
2944
+ if (typeof db.connect === 'function')
2945
+ await db.connect();
2946
+ },
2947
+ disconnect: () => {
2948
+ closing ??= (async () => {
2949
+ if (typeof db.disconnect === 'function')
2950
+ await db.disconnect();
2951
+ })();
2952
+ return closing;
2953
+ },
2954
+ };
2436
2955
  // Prefer the client's own raw seam, which emits a `$on('query')` event; a
2437
2956
  // client without one (an older core, a test stub) runs on the pool as before.
2438
2957
  const runRaw = async (text, params, action) => {
@@ -2480,6 +2999,34 @@ export function createPrismaCompatClient(client, map, options = {}) {
2480
2999
  * transaction. Absent, it is a TypeError at the call site instead.
2481
3000
  */
2482
3001
  const build = (exts) => {
3002
+ /**
3003
+ * The transaction-scoped compat client over ONE core transaction: a delegate
3004
+ * per model (both spellings), extended like the base ones, plus the raw
3005
+ * surface on the transaction's own connection. The callback `$transaction`
3006
+ * and {@link bindTransaction} both build it here, so a transaction this
3007
+ * layer opened and one it was handed cannot differ.
3008
+ */
3009
+ const txClientFor = (tx) => {
3010
+ const txDelegates = {};
3011
+ for (const [prismaModel, mm] of delegateModels) {
3012
+ setOwn(txDelegates, prismaModel, extendDelegate(makeDelegate(ctx, mm, () => tx.table(mm.table), (fn) => fn((n) => tx.table(n))), prismaModel, exts));
3013
+ const alias = prismaPropertyAlias(prismaModel);
3014
+ if (alias && !Object.hasOwn(map.models, alias) && !Object.hasOwn(txDelegates, alias)) {
3015
+ setOwn(txDelegates, alias, ownLookup(txDelegates, prismaModel));
3016
+ }
3017
+ }
3018
+ // Raw SQL on the transaction's own connection. Prisma's tx client
3019
+ // carries these four, and code that mixes `$transaction` with raw SQL is
3020
+ // the common case in a migrated codebase. No model can shadow them: a
3021
+ // Prisma model name cannot start with `$`, and junction accessors skip
3022
+ // every CLIENT_RESERVED_KEYS name.
3023
+ const txClient = {
3024
+ ...txDelegates,
3025
+ ...makeRawSurface(txRunRaw(tx), ph, ctx.fragmentOf),
3026
+ };
3027
+ CORE_OF.set(txClient, tx);
3028
+ return txClient;
3029
+ };
2483
3030
  // Delegates bound to the base client, extended where the extension has
2484
3031
  // members for them. `baseDelegates` is built ONCE (outside), so a client
2485
3032
  // whose extension only adds `client` members shares the very same delegate
@@ -2535,23 +3082,7 @@ export function createPrismaCompatClient(client, map, options = {}) {
2535
3082
  }
2536
3083
  // Callback form: hand the user a compat client bound to the tx connection.
2537
3084
  const fn = arg;
2538
- return db.$transaction((tx) => {
2539
- const txDelegates = {};
2540
- for (const [prismaModel, mm] of delegateModels) {
2541
- setOwn(txDelegates, prismaModel, extendDelegate(makeDelegate(ctx, mm, () => tx.table(mm.table), (fn) => fn((n) => tx.table(n))), prismaModel, exts));
2542
- const alias = prismaPropertyAlias(prismaModel);
2543
- if (alias && !Object.hasOwn(map.models, alias) && !Object.hasOwn(txDelegates, alias)) {
2544
- setOwn(txDelegates, alias, ownLookup(txDelegates, prismaModel));
2545
- }
2546
- }
2547
- // Raw SQL on the transaction's own connection. Prisma's tx client
2548
- // carries these four, and code that mixes `$transaction` with raw SQL is
2549
- // the common case in a migrated codebase. No model can shadow them: a
2550
- // Prisma model name cannot start with `$`, and junction accessors skip
2551
- // every CLIENT_RESERVED_KEYS name.
2552
- const txClient = { ...txDelegates, ...makeRawSurface(txRunRaw(tx), ph) };
2553
- return fn(txClient);
2554
- }, txOptions);
3085
+ return db.$transaction((tx) => fn(txClientFor(tx)), txOptions);
2555
3086
  }),
2556
3087
  $extends: ((extension) => {
2557
3088
  // Prisma's callback form: `client.$extends(fn)` IS `fn(client)`.
@@ -2559,9 +3090,9 @@ export function createPrismaCompatClient(client, map, options = {}) {
2559
3090
  return extension(result);
2560
3091
  return build(applyExtension(exts, extension, modelKeys, clientKeys));
2561
3092
  }),
2562
- ...makeRawSurface(runRaw, ph),
2563
- $connect: async () => { },
2564
- $disconnect: async () => { },
3093
+ ...makeRawSurface(runRaw, ph, ctx.fragmentOf),
3094
+ $connect: () => lifecycle.connect(),
3095
+ $disconnect: () => lifecycle.disconnect(),
2565
3096
  };
2566
3097
  // Assemble the result: model delegates keyed by Prisma model name, plus the
2567
3098
  // client-level base methods. A plain object suffices, every model is a known
@@ -2579,6 +3110,14 @@ export function createPrismaCompatClient(client, map, options = {}) {
2579
3110
  // Extension `client` members last: every name was checked against the real
2580
3111
  // client keys in applyExtension, so this can never overwrite a delegate.
2581
3112
  Object.assign(result, exts.client);
3113
+ CORE_OF.set(result, client);
3114
+ BIND_OF.set(result, (tx) => {
3115
+ if (tx === client || typeof tx?.table !== 'function') {
3116
+ throw new ValidationError('prisma-compat: bindTransaction takes the core transaction client a `$transaction(async (tx) => ...)` ' +
3117
+ 'callback receives on the TurbineClient this compat client wraps.');
3118
+ }
3119
+ return txClientFor(tx);
3120
+ });
2582
3121
  return result;
2583
3122
  };
2584
3123
  return build(EMPTY_EXTENSIONS);