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.
@@ -64,21 +64,26 @@
64
64
  * - `instanceof PrismaClientKnownRequestError`, `.meta`/message byte parity
65
65
  * (opt into `prismaErrorCodes` for a `.code` like `P2002`, without pretending
66
66
  * `instanceof` identity).
67
- * - `Prisma.join` / `Prisma.raw` composition beyond plain fragment flattening.
67
+ * - Splicing another library's `Prisma.sql` fragments unless asked to: they are
68
+ * bound as values until the client is given that library's namespace
69
+ * ({@link PrismaCompatOptions.prismaNamespace}).
68
70
  * - Fluent relation chaining (`prisma.user.findUnique().posts()`).
69
71
  * - Accelerate / Pulse / driver-adapter preview features, the Mongo API, and the
70
72
  * `prisma migrate`/`db` CLI family (Turbine ships its own migrations).
71
73
  * - **Negative `take`** (take-from-end) throws: Turbine has no reverse-take.
72
74
  * A **`cursor` on a nested relation include** throws: `with` has no cursor
73
75
  * (`take` / `skip` there page each parent's rows, as in Prisma).
74
- * - **A filtered relation count** (`_count: { select: { posts: { where } } }`)
75
- * and **`distinct` on a nested include** throw `UnsupportedFeatureError`:
76
- * core counts and includes a relation whole, so honoring either would mean
77
- * returning a wrong number or duplicate rows. The message names the
78
- * alternative (a `count` / `findMany` on the related model).
76
+ * - **`distinct` on a nested include** throws `UnsupportedFeatureError`: core
77
+ * includes a relation whole, so honoring it would mean returning duplicate
78
+ * rows. The message names the alternative (a `findMany` on the related model).
79
+ * A filtered relation count (`_count: { select: { posts: { where } } }`) and a
80
+ * `_count` below the top level ARE supported: this layer runs one grouped
81
+ * count per counted relation after the read, in the same transaction (see
82
+ * {@link ReadPlan}). Those two forms count one-to-many relations only; a
83
+ * many-to-many one is refused by name.
79
84
  * - **Nothing is accepted and dropped.** Every option on an included relation
80
- * and every key under `_count` is translated, refused by name (the two
81
- * above, `cursor`), or refused as unknown (`ValidationError`, with a
85
+ * and every key under `_count` is translated, refused by name (`distinct`,
86
+ * `cursor`), or refused as unknown (`ValidationError`, with a
82
87
  * suggestion): a misspelled `wher`, a Turbine spelling like `limit`, a
83
88
  * relation `_count` does not know. The same holds for `$transaction` options
84
89
  * (`maxWait` is accepted, warned about once, and not applied: the pool's
@@ -90,10 +95,11 @@
90
95
  * - **Write projections**: `select` / `omit` on create/update/delete/upsert
91
96
  * narrow the RETURNED OBJECT (see {@link resolveWriteProjection}); they do
92
97
  * NOT narrow the statement's `RETURNING` list, so the column still crosses
93
- * the wire, and `pii: true` remains the SQL-level control. A relation key in
94
- * either (or any `include` on a write) THROWS, since a write returns its own
95
- * row only. `omit` on READS is translated to core's own `omit`, see
96
- * {@link translateOmit}.
98
+ * the wire, and `pii: true` remains the SQL-level control. A write whose
99
+ * `include` / `select` names a relation or `_count` runs as the write followed
100
+ * by a read of the written row by primary key, in one transaction (a delete
101
+ * reads first), so it returns what Prisma returns. `omit` on READS is
102
+ * translated to core's own `omit`, see {@link translateOmit}.
97
103
  * - **`take` / `skip` / `cursor` on `count` and `aggregate`** throw: Prisma
98
104
  * computes those over one page of rows and Turbine has no paged count. An
99
105
  * `orderBy` alone changes nothing there and is accepted. `count({ select })`
@@ -162,6 +168,8 @@ var __importStar = (this && this.__importStar) || (function () {
162
168
  })();
163
169
  Object.defineProperty(exports, "__esModule", { value: true });
164
170
  exports.CLIENT_RESERVED_KEYS = exports.COMPAT_DEFERRED = exports.PRISMA_ARG_KEYS = exports.Prisma = void 0;
171
+ exports.turbineOf = turbineOf;
172
+ exports.bindTransaction = bindTransaction;
165
173
  exports.createPrismaCompatClient = createPrismaCompatClient;
166
174
  const diagnostics_js_1 = require("./diagnostics.js");
167
175
  const errors_js_1 = require("./errors.js");
@@ -199,6 +207,48 @@ function isSqlFragment(x) {
199
207
  function makeSql(strings, values) {
200
208
  return { strings, values, [SQL_FRAGMENT]: true };
201
209
  }
210
+ /** The default reader: this module's own branded fragments only. */
211
+ const ownFragment = (value) => (isSqlFragment(value) ? value : undefined);
212
+ /**
213
+ * A reader that also splices fragments built by another library's `Prisma`
214
+ * namespace (in practice `@prisma/client`, whose `Prisma.sql` / `join` / `raw` /
215
+ * `empty` all return instances of one class that is not exported).
216
+ *
217
+ * Recognition is by PROTOTYPE IDENTITY with the namespace's own `empty`
218
+ * fragment, never by shape. A shape test (`strings` + `values` arrays) would
219
+ * splice a request body: `JSON.parse` happily produces
220
+ * `{ "strings": ["1; DROP TABLE t; --"], "values": [] }`, and that object sitting
221
+ * in `$queryRaw\`... ${body.filter}\`` would then be SQL rather than a bound
222
+ * value. A parsed body can never carry a class prototype, so it stays a value,
223
+ * exactly as it does in Prisma, which recognizes its fragments by `instanceof`.
224
+ */
225
+ function foreignFragmentReader(namespace) {
226
+ const empty = namespace?.empty;
227
+ const proto = typeof empty === 'object' && empty !== null ? Object.getPrototypeOf(empty) : null;
228
+ if (proto === null || proto === Object.prototype || !hasFragmentParts(empty)) {
229
+ throw new errors_js_1.ValidationError('prisma-compat: `prismaNamespace` takes the `Prisma` namespace of a client library ' +
230
+ '(`import { Prisma } from "@prisma/client"`), whose `Prisma.empty` is a fragment instance with ' +
231
+ '`strings` and `values` arrays. The value given has no such `empty`.');
232
+ }
233
+ return (value) => {
234
+ if (isSqlFragment(value))
235
+ return value;
236
+ if (typeof value !== 'object' || value === null || Object.getPrototypeOf(value) !== proto)
237
+ return undefined;
238
+ if (!hasFragmentParts(value)) {
239
+ throw new errors_js_1.ValidationError('prisma-compat: a fragment from the configured `prismaNamespace` does not have `strings` and `values` ' +
240
+ 'arrays with one more string than values, so it cannot be composed.');
241
+ }
242
+ return value;
243
+ };
244
+ }
245
+ function hasFragmentParts(value) {
246
+ const { strings, values } = value;
247
+ return (Array.isArray(strings) &&
248
+ Array.isArray(values) &&
249
+ strings.length === values.length + 1 &&
250
+ strings.every((part) => typeof part === 'string'));
251
+ }
202
252
  /**
203
253
  * `Prisma`-compatible raw-SQL helpers, a minimal local implementation so
204
254
  * migrated `Prisma.sql\`…\`` / `Prisma.join(...)` / `Prisma.raw(...)` calls keep
@@ -785,7 +835,7 @@ function translateOmit(ctx, mm, omit) {
785
835
  * `RangeError` here, before core's own depth-10 relation cap
786
836
  * (`CircularRelationError`) could ever see the `with` clause it was building.
787
837
  */
788
- function translateProjection(ctx, mm, args, depth = 0) {
838
+ function translateProjection(ctx, mm, args, depth = 0, plan = newReadPlan(mm, false)) {
789
839
  assertTranslateDepth(depth, 'include');
790
840
  const include = args.include;
791
841
  const select = args.select;
@@ -797,51 +847,266 @@ function translateProjection(ctx, mm, args, depth = 0) {
797
847
  throw new errors_js_1.ValidationError('prisma-compat: `select` and `omit` are mutually exclusive. ' +
798
848
  'A `select` already lists exactly the fields you want.');
799
849
  }
800
- const omit = omitArg ? translateOmit(ctx, mm, omitArg) : undefined;
850
+ let omit = omitArg ? translateOmit(ctx, mm, omitArg) : undefined;
801
851
  const withClause = {};
802
852
  let hasWith = false;
853
+ /** The `_count` value on this level, decided after the loop (see planCounts). */
854
+ let countVal;
803
855
  if (include) {
804
856
  for (const [key, val] of Object.entries(include)) {
805
857
  if (val === false || val == null)
806
858
  continue;
807
859
  if (key === '_count') {
808
- withClause._count = translateCountSelect(ctx, mm, val);
809
- hasWith = true;
860
+ countVal = val;
810
861
  continue;
811
862
  }
812
863
  const rel = (0, utils_js_1.ownLookup)(mm.relations, key);
813
864
  if (!rel) {
814
865
  throw new errors_js_1.ValidationError(`prisma-compat: unknown relation "${key}" in include on model "${modelName(ctx, mm)}".`);
815
866
  }
816
- (0, filters_js_1.setOwn)(withClause, rel.name, translateWithOption(ctx, mm, rel.name, val, depth + 1));
867
+ (0, filters_js_1.setOwn)(withClause, rel.name, translateWithOption(ctx, mm, rel.name, val, depth + 1, plan));
817
868
  hasWith = true;
818
869
  }
870
+ if (countVal !== undefined) {
871
+ const core = planCounts(ctx, mm, countVal, plan);
872
+ if (core !== undefined) {
873
+ withClause._count = core;
874
+ hasWith = true;
875
+ }
876
+ else if (omit) {
877
+ // The follow-up count needs each row's key; an `omit` naming it gets it
878
+ // back for the count and drops it again afterwards.
879
+ for (const field of countKeyFields(plan)) {
880
+ if (Object.hasOwn(omit, field)) {
881
+ delete omit[field];
882
+ plan.drop ??= new Set();
883
+ plan.drop.add(prismaFieldName(ctx, mm, field));
884
+ }
885
+ }
886
+ if (Object.keys(omit).length === 0)
887
+ omit = undefined;
888
+ }
889
+ }
819
890
  return { omit, with: hasWith ? withClause : undefined };
820
891
  }
821
892
  if (select) {
822
893
  const scalar = {};
823
894
  let hasScalar = false;
895
+ const picked = new Set();
824
896
  for (const [key, val] of Object.entries(select)) {
825
897
  if (val === false || val == null)
826
898
  continue;
827
899
  if (key === '_count') {
828
- withClause._count = translateCountSelect(ctx, mm, val);
829
- hasWith = true;
900
+ countVal = val;
901
+ picked.add('_count');
830
902
  continue;
831
903
  }
832
904
  const rel = (0, utils_js_1.ownLookup)(mm.relations, key);
833
905
  if (rel) {
834
- (0, filters_js_1.setOwn)(withClause, rel.name, translateWithOption(ctx, mm, rel.name, val, depth + 1));
906
+ (0, filters_js_1.setOwn)(withClause, rel.name, translateWithOption(ctx, mm, rel.name, val, depth + 1, plan));
835
907
  hasWith = true;
908
+ picked.add(key);
836
909
  continue;
837
910
  }
838
911
  (0, filters_js_1.setOwn)(scalar, renameField(mm, key), true);
839
912
  hasScalar = true;
913
+ picked.add(key);
914
+ }
915
+ if (countVal !== undefined) {
916
+ const core = planCounts(ctx, mm, countVal, plan);
917
+ if (core !== undefined) {
918
+ withClause._count = core;
919
+ hasWith = true;
920
+ }
840
921
  }
922
+ // A key this layer needs on each row (to attach a follow-up count) is
923
+ // selected for it and dropped again before the row is returned.
924
+ let added = false;
925
+ for (const field of countKeyFields(plan)) {
926
+ if (!Object.hasOwn(scalar, field)) {
927
+ (0, filters_js_1.setOwn)(scalar, field, true);
928
+ hasScalar = true;
929
+ added = true;
930
+ }
931
+ }
932
+ // A `select` naming relations or `_count` and no scalar field returns no
933
+ // scalar in Prisma. Core reads "no scalar select" as every column, so the
934
+ // smallest projection that keeps the row addressable (its primary key) is
935
+ // asked for, and trimmed off again.
936
+ if (!hasScalar && picked.size > 0) {
937
+ for (const field of primaryKeyFields(ctx, mm))
938
+ (0, filters_js_1.setOwn)(scalar, field, true);
939
+ hasScalar = Object.keys(scalar).length > 0;
940
+ added = hasScalar;
941
+ }
942
+ if (added)
943
+ plan.keep = picked;
841
944
  return { select: hasScalar ? scalar : undefined, with: hasWith ? withClause : undefined };
842
945
  }
843
946
  return { omit };
844
947
  }
948
+ function newReadPlan(mm, root) {
949
+ return { mm, root, counts: [], children: new Map() };
950
+ }
951
+ function planHasCounts(plan) {
952
+ if (plan.counts.length > 0)
953
+ return true;
954
+ for (const child of plan.children.values())
955
+ if (planHasCounts(child))
956
+ return true;
957
+ return false;
958
+ }
959
+ function planHasTrim(plan) {
960
+ if (plan.keep || plan.drop)
961
+ return true;
962
+ for (const child of plan.children.values())
963
+ if (planHasTrim(child))
964
+ return true;
965
+ return false;
966
+ }
967
+ /** The parent-side key fields this level's follow-up counts read. */
968
+ function countKeyFields(plan) {
969
+ return [...new Set(plan.counts.map((c) => c.parentField))];
970
+ }
971
+ function primaryKeyFields(ctx, mm) {
972
+ const meta = (0, utils_js_1.ownLookup)(ctx.schema.tables, mm.table);
973
+ return (meta?.primaryKey ?? []).map((col) => meta?.reverseColumnMap?.[col] ?? col);
974
+ }
975
+ function prismaFieldName(ctx, mm, turbineField) {
976
+ return (0, utils_js_1.ownLookup)(lookupsFor(ctx, mm).reverseFields, turbineField) ?? turbineField;
977
+ }
978
+ /** The one column of a single-column key, or undefined for a composite one. */
979
+ function singleColumn(key) {
980
+ if (!Array.isArray(key))
981
+ return key;
982
+ return key.length === 1 ? key[0] : undefined;
983
+ }
984
+ /**
985
+ * Decide where one level's `_count` is computed. Returns the value for core's
986
+ * `with._count` when core can answer it (top level, every count unfiltered),
987
+ * else records the counts on `plan` and returns undefined.
988
+ */
989
+ function planCounts(ctx, mm, val, plan) {
990
+ const parsed = translateCountSelect(ctx, mm, val);
991
+ const filtered = parsed !== true && parsed.some((c) => c.where !== undefined);
992
+ if (plan.root && !filtered) {
993
+ return parsed === true ? true : Object.fromEntries(parsed.map((c) => [c.relation, true]));
994
+ }
995
+ const meta = (0, utils_js_1.ownLookup)(ctx.schema.tables, mm.table);
996
+ const relations = meta?.relations ?? {};
997
+ const wanted = parsed === true
998
+ ? Object.values(relations)
999
+ .filter((r) => r.type === 'hasMany' || r.type === 'manyToMany')
1000
+ .map((r) => ({ relation: r.name, where: undefined }))
1001
+ : parsed;
1002
+ for (const { relation, where } of wanted) {
1003
+ const rd = (0, utils_js_1.ownLookup)(relations, relation);
1004
+ const label = `${modelName(ctx, mm)}.${prismaRelationName(ctx, mm, relation)}`;
1005
+ const parentColumn = rd ? singleColumn(rd.referenceKey) : undefined;
1006
+ const childColumn = rd ? singleColumn(rd.foreignKey) : undefined;
1007
+ if (rd?.type !== 'hasMany' || parentColumn === undefined || childColumn === undefined) {
1008
+ throw new errors_js_1.UnsupportedFeatureError(`a nested or filtered \`_count\` of "${label}"`, 'prisma-compat', rd?.type === 'manyToMany'
1009
+ ? 'Below the top level, and with a `where`, only one-to-many relations are counted. Count the ' +
1010
+ 'junction rows with a groupBy on the related model, or use an unfiltered top-level `_count`.'
1011
+ : 'Below the top level, and with a `where`, only one-to-many relations on a single-column key are ' +
1012
+ 'counted. Use a groupBy on the related model.');
1013
+ }
1014
+ const target = (0, utils_js_1.ownLookup)(ctx.schema.tables, rd.to);
1015
+ const targetModel = relTargetModel(ctx, mm, relation);
1016
+ plan.counts.push({
1017
+ relation,
1018
+ table: rd.to,
1019
+ parentField: meta?.reverseColumnMap?.[parentColumn] ?? parentColumn,
1020
+ childField: target?.reverseColumnMap?.[childColumn] ?? childColumn,
1021
+ ...(where !== undefined
1022
+ ? { where: targetModel ? translateWhere(ctx, targetModel, where) : where }
1023
+ : {}),
1024
+ });
1025
+ }
1026
+ return undefined;
1027
+ }
1028
+ /** A value usable as a Map key that equals for equal key values (a Date by its instant). */
1029
+ function countKeyOf(value) {
1030
+ return value instanceof Date ? `date:${value.getTime()}` : value;
1031
+ }
1032
+ /** Every raw row at one plan level, in result order. */
1033
+ function collectPlanRows(rows, plan, into) {
1034
+ const level = into.get(plan) ?? [];
1035
+ into.set(plan, level);
1036
+ for (const row of rows) {
1037
+ if (!(0, filters_js_1.isPlainRecord)(row))
1038
+ continue;
1039
+ level.push(row);
1040
+ for (const [rel, child] of plan.children) {
1041
+ const value = row[rel];
1042
+ const next = Array.isArray(value) ? value : value == null ? [] : [value];
1043
+ collectPlanRows(next, child, into);
1044
+ }
1045
+ }
1046
+ }
1047
+ /**
1048
+ * Run every count a {@link ReadPlan} holds and attach it to core's raw rows as
1049
+ * `_count`, keyed by turbine relation name (the reshape renames it).
1050
+ */
1051
+ async function attachPlannedCounts(table, raw, plan, passthrough) {
1052
+ const levels = new Map();
1053
+ collectPlanRows(Array.isArray(raw) ? raw : raw == null ? [] : [raw], plan, levels);
1054
+ for (const [level, rows] of levels) {
1055
+ if (level.counts.length === 0)
1056
+ continue;
1057
+ for (const row of rows)
1058
+ row._count = {};
1059
+ for (const req of level.counts) {
1060
+ const ids = [...new Set(rows.map((r) => r[req.parentField]).filter((v) => v !== null && v !== undefined))];
1061
+ const counts = new Map();
1062
+ if (ids.length > 0) {
1063
+ const byParent = { [req.childField]: { in: ids } };
1064
+ const groups = await table(req.table).groupBy({
1065
+ ...passthrough,
1066
+ by: [req.childField],
1067
+ where: req.where ? { AND: [byParent, req.where] } : byParent,
1068
+ _count: true,
1069
+ });
1070
+ for (const group of groups) {
1071
+ counts.set(countKeyOf(group[req.childField]), Number(group._count));
1072
+ }
1073
+ }
1074
+ for (const row of rows) {
1075
+ row._count[req.relation] = counts.get(countKeyOf(row[req.parentField])) ?? 0;
1076
+ }
1077
+ }
1078
+ }
1079
+ }
1080
+ /** Drop the keys this layer added (or an `omit` asked for) from reshaped, Prisma-named rows. */
1081
+ function trimPlannedRows(ctx, rows, plan) {
1082
+ const trimRow = (row, level) => {
1083
+ if (!(0, filters_js_1.isPlainRecord)(row))
1084
+ return row;
1085
+ let out = row;
1086
+ if (level.keep) {
1087
+ out = {};
1088
+ for (const key of level.keep)
1089
+ if (Object.hasOwn(row, key))
1090
+ (0, filters_js_1.setOwn)(out, key, row[key]);
1091
+ }
1092
+ else if (level.drop) {
1093
+ out = { ...row };
1094
+ for (const key of level.drop)
1095
+ delete out[key];
1096
+ }
1097
+ for (const [rel, child] of level.children) {
1098
+ const key = prismaRelationName(ctx, level.mm, rel);
1099
+ const value = out[key];
1100
+ if (value === undefined)
1101
+ continue;
1102
+ if (out === row)
1103
+ out = { ...row };
1104
+ out[key] = Array.isArray(value) ? value.map((v) => trimRow(v, child)) : trimRow(value, child);
1105
+ }
1106
+ return out;
1107
+ };
1108
+ return Array.isArray(rows) ? rows.map((r) => trimRow(r, plan)) : trimRow(rows, plan);
1109
+ }
845
1110
  const NO_WRITE_PROJECTION = {};
846
1111
  /**
847
1112
  * Refuse a write-projection key that names no field on the model.
@@ -886,9 +1151,9 @@ function assertWriteProjectionField(ctx, mm, op, clause, key) {
886
1151
  * SQL-level control is `pii: true` on the column, which is enforced in core and
887
1152
  * is unaffected by any of this.
888
1153
  *
889
- * A relation (or `_count`) key THROWS instead: a write returns its own row and
890
- * nothing else, so serving it is impossible, and the alternative is handing
891
- * back a row whose relation property is silently `undefined`, which would hide an unsupported projection.
1154
+ * A projection naming a relation (or `_count`) never reaches this function: the
1155
+ * delegate runs that write as the write plus a read-back (see
1156
+ * `projectsRelations` in makeDelegate). The refusals below are the backstop.
892
1157
  */
893
1158
  function resolveWriteProjection(ctx, mm, op, args) {
894
1159
  if (!args)
@@ -1044,7 +1309,7 @@ function assertNestedRelationKeys(label, opts) {
1044
1309
  * one arg with relation hops and then nests the other cannot spend two separate
1045
1310
  * budgets to reach the same stack depth.
1046
1311
  */
1047
- function translateWithOption(ctx, mm, turbineRel, val, depth = 0) {
1312
+ function translateWithOption(ctx, mm, turbineRel, val, depth = 0, parentPlan) {
1048
1313
  if (val === true)
1049
1314
  return true;
1050
1315
  const label = `${modelName(ctx, mm)}.${prismaRelationName(ctx, mm, turbineRel)}`;
@@ -1080,7 +1345,10 @@ function translateWithOption(ctx, mm, turbineRel, val, depth = 0) {
1080
1345
  '`select` / `include` / `omit` cannot be translated. Regenerate the map with ' +
1081
1346
  '`turbine migrate-from-prisma`, or drop the projection.');
1082
1347
  }
1083
- const proj = translateProjection(ctx, target, val, depth);
1348
+ const childPlan = newReadPlan(target, false);
1349
+ const proj = translateProjection(ctx, target, val, depth, childPlan);
1350
+ if (parentPlan)
1351
+ parentPlan.children.set(turbineRel, childPlan);
1084
1352
  if (proj.select)
1085
1353
  opt.select = proj.select;
1086
1354
  // Same silent drop as the top level: a nested `omit` names the sensitive
@@ -1097,14 +1365,12 @@ function isUnfilteredCountWhere(where) {
1097
1365
  return where === undefined || ((0, filters_js_1.isPlainRecord)(where) && Object.values(where).every((v) => v === undefined));
1098
1366
  }
1099
1367
  /**
1100
- * Translate a Prisma `_count: { select: { rel: true } }` / `true` into Turbine
1101
- * `with._count`.
1102
- *
1103
- * Core counts a relation whole: `with._count` takes `true` or `{ rel: true }`.
1104
- * So a Prisma filtered count (`{ rel: { where } }`) is refused (E017) naming the
1105
- * alternative, a relation that is not on the model is E003, and so is any key
1106
- * but `select` under `_count` (a misspelled `selec` used to count EVERY relation,
1107
- * and a misspelled relation counted nothing, both without a word).
1368
+ * Validate a Prisma `_count` value and read it as the relations it counts:
1369
+ * `true` (every to-many relation) or a list of turbine relation names, each with
1370
+ * the caller's `where` when it filters anything. {@link planCounts} decides who
1371
+ * computes them. A relation that is not on the model is E003, and so is any key
1372
+ * but `select` under `_count` (a misspelled `selec` used to count EVERY
1373
+ * relation, and a misspelled relation counted nothing, both without a word).
1108
1374
  */
1109
1375
  function translateCountSelect(ctx, mm, val) {
1110
1376
  if (val === true)
@@ -1128,7 +1394,7 @@ function translateCountSelect(ctx, mm, val) {
1128
1394
  throw new errors_js_1.ValidationError(`prisma-compat: \`_count.select\` on model "${model}" takes { <relation>: true }, ` +
1129
1395
  `received ${describeValue(val.select)}.`);
1130
1396
  }
1131
- const out = {};
1397
+ const out = [];
1132
1398
  for (const [key, v] of Object.entries(val.select)) {
1133
1399
  if (v === undefined || v === false || v === null)
1134
1400
  continue;
@@ -1141,7 +1407,7 @@ function translateCountSelect(ctx, mm, val) {
1141
1407
  ` Relations: ${known.join(', ') || '(none)'}.`);
1142
1408
  }
1143
1409
  if (v === true) {
1144
- (0, filters_js_1.setOwn)(out, rel.name, true);
1410
+ out.push({ relation: rel.name });
1145
1411
  continue;
1146
1412
  }
1147
1413
  if (!(0, filters_js_1.isPlainRecord)(v)) {
@@ -1156,16 +1422,7 @@ function translateCountSelect(ctx, mm, val) {
1156
1422
  (hint ? ` Did you mean "${hint}"?` : '') +
1157
1423
  ' The only key is "where".');
1158
1424
  }
1159
- if (!isUnfilteredCountWhere(v.where)) {
1160
- const target = relTargetModel(ctx, mm, rel.name);
1161
- const targetName = target ? modelName(ctx, target) : undefined;
1162
- const delegate = targetName ? (prismaPropertyAlias(targetName) ?? targetName) : '<model>';
1163
- throw new errors_js_1.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. ' +
1164
- `Count the filtered rows through the related model instead: prisma.${delegate}.count({ where: ... }) ` +
1165
- `with the foreign key and your filter, or prisma.${delegate}.groupBy({ by: [<foreign key>], _count: true }) ` +
1166
- 'for many parents at once.');
1167
- }
1168
- (0, filters_js_1.setOwn)(out, rel.name, true);
1425
+ out.push(isUnfilteredCountWhere(v.where) ? { relation: rel.name } : { relation: rel.name, where: v.where });
1169
1426
  }
1170
1427
  return out;
1171
1428
  }
@@ -1191,7 +1448,7 @@ function translateFieldList(ctx, mm, option, val) {
1191
1448
  * `orderBy` are translated first, so the cursor step works in turbine-field
1192
1449
  * space.
1193
1450
  */
1194
- function translateReadArgs(ctx, mm, prismaArgs, kind) {
1451
+ function translateReadArgs(ctx, mm, prismaArgs, kind, plan = newReadPlan(mm, true)) {
1195
1452
  const t = {};
1196
1453
  // FIRST, so a per-call `stableRelationOrder` overrides it: the client-level
1197
1454
  // option is a default, the arg is an instruction.
@@ -1204,7 +1461,7 @@ function translateReadArgs(ctx, mm, prismaArgs, kind) {
1204
1461
  t.where = translateWhere(ctx, mm, prismaArgs.where);
1205
1462
  if (prismaArgs.orderBy !== undefined)
1206
1463
  t.orderBy = translateOrderBy(ctx, mm, prismaArgs.orderBy);
1207
- const proj = translateProjection(ctx, mm, prismaArgs);
1464
+ const proj = translateProjection(ctx, mm, prismaArgs, 0, plan);
1208
1465
  if (proj.select)
1209
1466
  t.select = proj.select;
1210
1467
  if (proj.omit)
@@ -1365,7 +1622,7 @@ function translateWriteData(ctx, mm, data, depth = 0) {
1365
1622
  const rel = (0, utils_js_1.ownLookup)(mm.relations, key);
1366
1623
  if (rel && (0, filters_js_1.isPlainRecord)(val) && Object.keys(val).some((k) => NESTED_WRITE_OPS.has(k))) {
1367
1624
  const target = relTargetModel(ctx, mm, rel.name);
1368
- (0, filters_js_1.setOwn)(out, rel.name, translateNestedWrite(ctx, target, val, depth + 1));
1625
+ (0, filters_js_1.setOwn)(out, rel.name, translateNestedWrite(ctx, target, val, depth + 1, rel.cardinality === 'one'));
1369
1626
  continue;
1370
1627
  }
1371
1628
  (0, filters_js_1.setOwn)(out, renameField(mm, key), val);
@@ -1392,13 +1649,21 @@ function isExpressionNode(value) {
1392
1649
  * changes is HOW: a typed refusal instead of a `RangeError` raised before core
1393
1650
  * is reached at all (measured: a 1,000-hop `create` chain, a 43 KB body).
1394
1651
  */
1395
- function translateNestedWrite(ctx, target, ops, depth) {
1652
+ function translateNestedWrite(ctx, target, ops, depth, toOne = false) {
1396
1653
  const out = {};
1654
+ // Rows a nested write CREATES get the target model's client defaults
1655
+ // (`cuid()` / `uuid()` ids, `@default(now())`, `@updatedAt`) and rows it
1656
+ // UPDATES get `@updatedAt`, exactly as the top-level row does: Prisma fills
1657
+ // them at every depth, and a nested row without its id reached the database
1658
+ // as NULL.
1659
+ const created = (p) => target ? translateWriteData(ctx, target, applyCreateDefaults(target, p), depth + 1) : p;
1397
1660
  for (const [op, payload] of Object.entries(ops)) {
1398
1661
  switch (op) {
1399
1662
  case 'create':
1663
+ out[op] = mapMaybeArray(payload, created);
1664
+ break;
1400
1665
  case 'createMany':
1401
- out[op] = mapMaybeArray(payload, (p) => (target ? translateWriteData(ctx, target, p, depth + 1) : p));
1666
+ out[op] = translateNestedCreateMany(payload, created);
1402
1667
  break;
1403
1668
  case 'connect':
1404
1669
  case 'disconnect':
@@ -1407,9 +1672,18 @@ function translateNestedWrite(ctx, target, ops, depth) {
1407
1672
  out[op] = mapMaybeArray(payload, (p) => (target ? translateWhere(ctx, target, p, depth + 1) : p));
1408
1673
  break;
1409
1674
  case 'deleteMany':
1675
+ out[op] = mapMaybeArray(payload, (p) => translateWhereDataPair(ctx, target, op, p, depth + 1));
1676
+ break;
1410
1677
  case 'updateMany':
1678
+ out[op] = mapMaybeArray(payload, (p) => translateWhereDataPair(ctx, target, op, p, depth + 1, true));
1679
+ break;
1411
1680
  case 'update':
1412
- out[op] = mapMaybeArray(payload, (p) => translateWhereDataPair(ctx, target, op, p, depth + 1));
1681
+ out[op] = mapMaybeArray(payload, (p) => {
1682
+ const pair = translateWhereDataPair(ctx, target, op, p, depth + 1, true);
1683
+ // Prisma's to-one `update` takes the data itself (`profile: { update:
1684
+ // { bio } }`) as well as `{ data }`; core reads `{ data }`.
1685
+ return toOne && (0, filters_js_1.isPlainRecord)(p) && !('data' in p) && !('where' in p) ? { data: pair } : pair;
1686
+ });
1413
1687
  break;
1414
1688
  case 'connectOrCreate':
1415
1689
  out[op] = mapMaybeArray(payload, (p) => translateConnectOrCreate(ctx, target, p, depth + 1));
@@ -1442,19 +1716,34 @@ function assertNestedPayloadKeys(op, p, allowed) {
1442
1716
  }
1443
1717
  }
1444
1718
  /** A `{ where?, data }` pair (nested update/updateMany), or a bare data object. */
1445
- function translateWhereDataPair(ctx, target, op, p, depth) {
1719
+ function translateWhereDataPair(ctx, target, op, p, depth, touch = false) {
1446
1720
  if (!(0, filters_js_1.isPlainRecord)(p))
1447
1721
  return p;
1722
+ const data = (d) => target ? translateWriteData(ctx, target, touch ? applyUpdateTouch(target, d) : d, depth) : d;
1448
1723
  if ('data' in p || 'where' in p) {
1449
1724
  assertNestedPayloadKeys(op, p, ['where', 'data']);
1450
1725
  const out = {};
1451
1726
  if (p.where !== undefined)
1452
1727
  out.where = target ? translateWhere(ctx, target, p.where, depth) : p.where;
1453
1728
  if (p.data !== undefined)
1454
- out.data = target ? translateWriteData(ctx, target, p.data, depth) : p.data;
1729
+ out.data = data(p.data);
1455
1730
  return out;
1456
1731
  }
1457
- return target ? translateWriteData(ctx, target, p, depth) : p;
1732
+ return data(p);
1733
+ }
1734
+ /**
1735
+ * A nested `createMany: { data, skipDuplicates }`. Its rows are translated (and
1736
+ * get client defaults) like nested `create` rows; the wrapper keys pass through
1737
+ * for core to validate.
1738
+ */
1739
+ function translateNestedCreateMany(payload, created) {
1740
+ if (!(0, filters_js_1.isPlainRecord)(payload))
1741
+ return payload;
1742
+ assertNestedPayloadKeys('createMany', payload, ['data', 'skipDuplicates']);
1743
+ const out = { ...payload };
1744
+ if (payload.data !== undefined)
1745
+ out.data = mapMaybeArray(payload.data, created);
1746
+ return out;
1458
1747
  }
1459
1748
  function translateConnectOrCreate(ctx, target, p, depth) {
1460
1749
  if (!(0, filters_js_1.isPlainRecord)(p))
@@ -1463,8 +1752,9 @@ function translateConnectOrCreate(ctx, target, p, depth) {
1463
1752
  const out = {};
1464
1753
  if (p.where !== undefined)
1465
1754
  out.where = target ? translateWhere(ctx, target, p.where, depth) : p.where;
1466
- if (p.create !== undefined)
1467
- out.create = target ? translateWriteData(ctx, target, p.create, depth) : p.create;
1755
+ if (p.create !== undefined) {
1756
+ out.create = target ? translateWriteData(ctx, target, applyCreateDefaults(target, p.create), depth) : p.create;
1757
+ }
1468
1758
  return out;
1469
1759
  }
1470
1760
  function translateUpsertNested(ctx, target, p, depth) {
@@ -1474,10 +1764,12 @@ function translateUpsertNested(ctx, target, p, depth) {
1474
1764
  const out = {};
1475
1765
  if (p.where !== undefined)
1476
1766
  out.where = target ? translateWhere(ctx, target, p.where, depth) : p.where;
1477
- if (p.create !== undefined)
1478
- out.create = target ? translateWriteData(ctx, target, p.create, depth) : p.create;
1479
- if (p.update !== undefined)
1480
- out.update = target ? translateWriteData(ctx, target, p.update, depth) : p.update;
1767
+ if (p.create !== undefined) {
1768
+ out.create = target ? translateWriteData(ctx, target, applyCreateDefaults(target, p.create), depth) : p.create;
1769
+ }
1770
+ if (p.update !== undefined) {
1771
+ out.update = target ? translateWriteData(ctx, target, applyUpdateTouch(target, p.update), depth) : p.update;
1772
+ }
1481
1773
  return out;
1482
1774
  }
1483
1775
  // --- aggregate / groupBy translation --------------------------------------
@@ -1960,6 +2252,123 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
1960
2252
  }
1961
2253
  }, batchable);
1962
2254
  };
2255
+ /**
2256
+ * One read operation. The {@link ReadPlan} filled by the translation says
2257
+ * whether this layer has counts to run (then the read and its counts share a
2258
+ * transaction, and a `$transaction([...])` array takes its sequential path)
2259
+ * and keys to trim off the reshaped rows.
2260
+ */
2261
+ const readCall = (op, args, kind, read, build, reshape) => {
2262
+ let plan = newReadPlan(mm, true);
2263
+ const finish = (raw) => {
2264
+ const shaped = reshape(raw);
2265
+ return planHasTrim(plan) ? trimPlannedRows(ctx, shaped, plan) : shaped;
2266
+ };
2267
+ const withCounts = async (table, t) => {
2268
+ const raw = await read(table(mm.table), t);
2269
+ const passthrough = {};
2270
+ if (t.skipGlobalFilters !== undefined)
2271
+ passthrough.skipGlobalFilters = t.skipGlobalFilters;
2272
+ if (t.timeout !== undefined)
2273
+ passthrough.timeout = t.timeout;
2274
+ await attachPlannedCounts(table, raw, plan, passthrough);
2275
+ return finish(raw);
2276
+ };
2277
+ return defer(op, args, () => {
2278
+ plan = newReadPlan(mm, true);
2279
+ const a = kind === 'unique' ? requireWhere(args, op) : (args ?? {});
2280
+ return translateReadArgs(ctx, mm, a, kind, plan);
2281
+ }, (qi, t) => (planHasCounts(plan) ? runInTx((table) => withCounts(table, t)) : read(qi, t).then(finish)), {
2282
+ build,
2283
+ reshape: finish,
2284
+ nested: () => planHasCounts(plan),
2285
+ execInTx: (table, t) => (planHasCounts(plan) ? withCounts(table, t) : read(table(mm.table), t).then(finish)),
2286
+ });
2287
+ };
2288
+ /**
2289
+ * A write whose `include` / `select` names a relation or `_count`. A write
2290
+ * statement returns its own row only, so these run as Prisma's semantics
2291
+ * describe them: the write, then a read of the written row by primary key with
2292
+ * the caller's projection, in ONE transaction (a delete reads first, since
2293
+ * afterwards there is nothing to read). The read is an ordinary compat read,
2294
+ * so nested and filtered counts work there too.
2295
+ */
2296
+ const projectsRelations = (a) => {
2297
+ if (!a)
2298
+ return false;
2299
+ const include = a.include;
2300
+ if ((0, filters_js_1.isPlainRecord)(include) && Object.values(include).some((v) => v !== false && v != null))
2301
+ return true;
2302
+ const select = a.select;
2303
+ if (!(0, filters_js_1.isPlainRecord)(select))
2304
+ return false;
2305
+ return Object.entries(select).some(([key, v]) => v !== false && v != null && (key === '_count' || (0, utils_js_1.ownLookup)(mm.relations, key) !== undefined));
2306
+ };
2307
+ const projectionOf = (a) => {
2308
+ const out = {};
2309
+ if (a.select !== undefined)
2310
+ out.select = a.select;
2311
+ if (a.include !== undefined)
2312
+ out.include = a.include;
2313
+ if (a.omit !== undefined)
2314
+ out.omit = a.omit;
2315
+ return out;
2316
+ };
2317
+ /** Validate the projection before anything is written (its errors would otherwise follow the write). */
2318
+ const checkReadProjection = (a) => {
2319
+ translateProjection(ctx, mm, projectionOf(a), 0, newReadPlan(mm, true));
2320
+ };
2321
+ /** The Prisma `where` naming one written row by primary key, from core's raw row. */
2322
+ const primaryKeyWhere = (op, raw) => {
2323
+ const fields = primaryKeyFields(ctx, mm);
2324
+ if (fields.length === 0 || !(0, filters_js_1.isPlainRecord)(raw)) {
2325
+ throw new errors_js_1.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 ' +
2326
+ 'separate findUnique inside the same $transaction.');
2327
+ }
2328
+ const where = {};
2329
+ for (const field of fields)
2330
+ (0, filters_js_1.setOwn)(where, prismaFieldName(ctx, mm, field), raw[field]);
2331
+ return where;
2332
+ };
2333
+ const readWritten = async (table, where, a) => {
2334
+ const plan = newReadPlan(mm, true);
2335
+ const t = translateReadArgs(ctx, mm, { where, ...projectionOf(a) }, 'unique', plan);
2336
+ const raw = await table(mm.table).findUnique(t);
2337
+ if (planHasCounts(plan))
2338
+ await attachPlannedCounts(table, raw, plan, {});
2339
+ const shaped = reshapeRowOrNull(ctx, mm, raw);
2340
+ return planHasTrim(plan) ? trimPlannedRows(ctx, shaped, plan) : shaped;
2341
+ };
2342
+ const writeThenRead = (op, a, write) => {
2343
+ if (op === 'delete') {
2344
+ return async (table) => {
2345
+ const before = await readWritten(table, a.where, a);
2346
+ await write(table(mm.table));
2347
+ return before;
2348
+ };
2349
+ }
2350
+ return async (table) => readWritten(table, primaryKeyWhere(op, await write(table(mm.table))), a);
2351
+ };
2352
+ /**
2353
+ * A write's own row, Prisma-shaped. Core returns the relations a nested write
2354
+ * touched (it reads the written tree back); a Prisma write without `include`
2355
+ * returns scalars only, so those keys are dropped rather than handed to a
2356
+ * caller who never asked for them.
2357
+ */
2358
+ const writtenRow = (raw) => {
2359
+ const row = reshapeRow(ctx, mm, raw);
2360
+ if (!(0, filters_js_1.isPlainRecord)(row))
2361
+ return row;
2362
+ let out = row;
2363
+ for (const key of Object.keys(row)) {
2364
+ if (key !== '_count' && (0, utils_js_1.ownLookup)(mm.relations, key) === undefined)
2365
+ continue;
2366
+ if (out === row)
2367
+ out = { ...row };
2368
+ delete out[key];
2369
+ }
2370
+ return out;
2371
+ };
1963
2372
  const requireWhere = (args, op) => {
1964
2373
  if (!args || args.where === undefined) {
1965
2374
  throw new errors_js_1.ValidationError(`prisma-compat: ${op} on "${modelName(ctx, mm)}" requires a \`where\`.`);
@@ -1967,28 +2376,35 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
1967
2376
  return args;
1968
2377
  };
1969
2378
  return {
1970
- 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) }),
1971
- 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) }),
1972
- 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) }),
1973
- 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) }),
1974
- 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) }),
2379
+ findMany: (args = {}) => readCall('findMany', args, 'many', (qi, t) => qi.findMany(t), (qi, t) => qi.buildFindMany(t), (raw) => reshapeRows(ctx, mm, raw)),
2380
+ findFirst: (args = {}) => readCall('findFirst', args, 'first', (qi, t) => qi.findFirst(t), (qi, t) => qi.buildFindFirst(t), (raw) => reshapeRowOrNull(ctx, mm, raw)),
2381
+ findUnique: (args) => readCall('findUnique', args, 'unique', (qi, t) => qi.findUnique(t), (qi, t) => qi.buildFindUnique(t), (raw) => reshapeRowOrNull(ctx, mm, raw)),
2382
+ findFirstOrThrow: (args = {}) => readCall('findFirstOrThrow', args, 'first', (qi, t) => qi.findFirstOrThrow(t), (qi, t) => qi.buildFindFirstOrThrow(t), (raw) => reshapeRow(ctx, mm, raw)),
2383
+ findUniqueOrThrow: (args) => readCall('findUniqueOrThrow', args, 'unique', (qi, t) => qi.findUniqueOrThrow(t), (qi, t) => qi.buildFindUniqueOrThrow(t), (raw) => reshapeRow(ctx, mm, raw)),
1975
2384
  create: (args) => {
1976
2385
  // Resolved inside the translate thunk below (so it validates before the
1977
2386
  // write runs and stays deferred), read back by every result path.
1978
2387
  let proj = NO_WRITE_PROJECTION;
1979
- const shape = (raw) => applyWriteProjection(proj, reshapeRow(ctx, mm, raw));
2388
+ const shape = (raw) => applyWriteProjection(proj, writtenRow(raw));
2389
+ const a = (args ?? {});
2390
+ const relational = projectsRelations(a);
2391
+ const projected = (t) => writeThenRead('create', a, (qi) => qi.create(t));
1980
2392
  return defer('create', args, () => {
1981
- proj = resolveWriteProjection(ctx, mm, 'create', args);
2393
+ if (relational)
2394
+ checkReadProjection(a);
2395
+ else
2396
+ proj = resolveWriteProjection(ctx, mm, 'create', a);
1982
2397
  const t = {
1983
- data: translateWriteData(ctx, mm, applyCreateDefaults(mm, args.data)),
2398
+ data: translateWriteData(ctx, mm, applyCreateDefaults(mm, a.data)),
1984
2399
  ...coreWriteProjection(mm, proj),
1985
2400
  };
1986
- (0, index_js_1.applyNativeOptions)(index_js_1.CREATE_OPTIONS, args, t);
2401
+ (0, index_js_1.applyNativeOptions)(index_js_1.CREATE_OPTIONS, a, t);
1987
2402
  return t;
1988
- }, (qi, t) => qi.create(t).then(shape), {
2403
+ }, (qi, t) => (relational ? runInTx(projected(t)) : qi.create(t).then(shape)), {
1989
2404
  build: (qi, t) => qi.buildCreate(t),
1990
2405
  reshape: shape,
1991
- nested: (t) => hasNestedKeys(ctx, mm, t.data),
2406
+ nested: (t) => relational || hasNestedKeys(ctx, mm, t.data),
2407
+ execInTx: (table, t) => (relational ? projected(t)(table) : table(mm.table).create(t).then(shape)),
1992
2408
  });
1993
2409
  },
1994
2410
  createMany: (args) => defer('createMany', args, () => {
@@ -2028,10 +2444,15 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2028
2444
  }),
2029
2445
  update: (args) => {
2030
2446
  let proj = NO_WRITE_PROJECTION;
2031
- const shape = (raw) => applyWriteProjection(proj, reshapeRow(ctx, mm, raw));
2447
+ const shape = (raw) => applyWriteProjection(proj, writtenRow(raw));
2448
+ const relational = projectsRelations(args);
2449
+ const projected = (t) => writeThenRead('update', args, (qi) => qi.update(t));
2032
2450
  return defer('update', args, () => {
2033
2451
  const a = requireWhere(args, 'update');
2034
- proj = resolveWriteProjection(ctx, mm, 'update', a);
2452
+ if (relational)
2453
+ checkReadProjection(a);
2454
+ else
2455
+ proj = resolveWriteProjection(ctx, mm, 'update', a);
2035
2456
  const t = {
2036
2457
  where: translateWhere(ctx, mm, a.where),
2037
2458
  data: translateWriteData(ctx, mm, applyUpdateTouch(mm, a.data)),
@@ -2048,10 +2469,11 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2048
2469
  };
2049
2470
  }
2050
2471
  return t;
2051
- }, (qi, t) => qi.update(t).then(shape), {
2472
+ }, (qi, t) => (relational ? runInTx(projected(t)) : qi.update(t).then(shape)), {
2052
2473
  build: (qi, t) => qi.buildUpdate(t),
2053
2474
  reshape: shape,
2054
- nested: (t) => hasNestedKeys(ctx, mm, t.data),
2475
+ nested: (t) => relational || hasNestedKeys(ctx, mm, t.data),
2476
+ execInTx: (table, t) => (relational ? projected(t)(table) : table(mm.table).update(t).then(shape)),
2055
2477
  });
2056
2478
  },
2057
2479
  updateMany: (args) => defer('updateMany', args, () => {
@@ -2071,14 +2493,24 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2071
2493
  }, (qi, t) => qi.updateMany(t), { build: (qi, t) => qi.buildUpdateMany(t), reshape: (raw) => raw }),
2072
2494
  delete: (args) => {
2073
2495
  let proj = NO_WRITE_PROJECTION;
2074
- const shape = (raw) => applyWriteProjection(proj, reshapeRow(ctx, mm, raw));
2496
+ const shape = (raw) => applyWriteProjection(proj, writtenRow(raw));
2497
+ const relational = projectsRelations(args);
2498
+ const projected = (t) => writeThenRead('delete', args, (qi) => qi.delete(t));
2075
2499
  return defer('delete', args, () => {
2076
2500
  const a = requireWhere(args, 'delete');
2077
- proj = resolveWriteProjection(ctx, mm, 'delete', a);
2501
+ if (relational)
2502
+ checkReadProjection(a);
2503
+ else
2504
+ proj = resolveWriteProjection(ctx, mm, 'delete', a);
2078
2505
  const t = { where: translateWhere(ctx, mm, a.where), ...coreWriteProjection(mm, proj) };
2079
2506
  (0, index_js_1.applyNativeOptions)(index_js_1.DELETE_OPTIONS, a, t);
2080
2507
  return t;
2081
- }, (qi, t) => qi.delete(t).then(shape), { build: (qi, t) => qi.buildDelete(t), reshape: shape });
2508
+ }, (qi, t) => (relational ? runInTx(projected(t)) : qi.delete(t).then(shape)), {
2509
+ build: (qi, t) => qi.buildDelete(t),
2510
+ reshape: shape,
2511
+ nested: () => relational,
2512
+ execInTx: (table, t) => (relational ? projected(t)(table) : table(mm.table).delete(t).then(shape)),
2513
+ });
2082
2514
  },
2083
2515
  deleteMany: (args = {}) => defer('deleteMany', args, () => {
2084
2516
  const a = args;
@@ -2092,10 +2524,15 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2092
2524
  }, (qi, t) => qi.deleteMany(t), { build: (qi, t) => qi.buildDeleteMany(t), reshape: (raw) => raw }),
2093
2525
  upsert: (args) => {
2094
2526
  let proj = NO_WRITE_PROJECTION;
2095
- const shape = (raw) => applyWriteProjection(proj, reshapeRow(ctx, mm, raw));
2527
+ const shape = (raw) => applyWriteProjection(proj, writtenRow(raw));
2528
+ const relational = projectsRelations(args);
2529
+ const projected = (t) => writeThenRead('upsert', args, (qi) => qi.upsert(t));
2096
2530
  return defer('upsert', args, () => {
2097
2531
  const a = requireWhere(args, 'upsert');
2098
- proj = resolveWriteProjection(ctx, mm, 'upsert', a);
2532
+ if (relational)
2533
+ checkReadProjection(a);
2534
+ else
2535
+ proj = resolveWriteProjection(ctx, mm, 'upsert', a);
2099
2536
  const t = {
2100
2537
  where: translateWhere(ctx, mm, a.where),
2101
2538
  create: translateWriteData(ctx, mm, applyCreateDefaults(mm, a.create)),
@@ -2108,13 +2545,13 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2108
2545
  // Core `upsert` has Prisma's semantics itself (it looks the row up by
2109
2546
  // `where` whenever one conflict statement would mean something else,
2110
2547
  // and runs nested writes), so the adapter passes it straight through.
2111
- (qi, t) => qi.upsert(t).then(shape), {
2548
+ (qi, t) => (relational ? runInTx(projected(t)) : qi.upsert(t).then(shape)), {
2112
2549
  build: (qi, t) => qi.buildUpsert(t),
2113
2550
  reshape: shape,
2114
2551
  // Batchable only when core would run it as one statement. PowDB has
2115
2552
  // no deferred statements at all, so it always takes the tx path.
2116
- nested: (t, qi) => qi.upsertNeedsLookup?.(t) ?? true,
2117
- execInTx: async (table, t) => shape(await table(mm.table).upsert(t)),
2553
+ nested: (t, qi) => relational || (qi.upsertNeedsLookup?.(t) ?? true),
2554
+ execInTx: async (table, t) => (relational ? projected(t)(table) : shape(await table(mm.table).upsert(t))),
2118
2555
  });
2119
2556
  },
2120
2557
  count: (args = {}) => {
@@ -2143,10 +2580,21 @@ function makeDelegate(ctx, mm, getQI, runInTx) {
2143
2580
  }, (qi, t) => qi.count(t), { build: (qi, t) => qi.buildCount(t), reshape: (raw) => raw });
2144
2581
  },
2145
2582
  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) }),
2146
- groupBy: (args) => defer('groupBy', args, () => translateAggregateArgs(ctx, mm, args, true), (qi, t) => qi.groupBy(t).then((rows) => rows.map((r) => reshapeGroupRow(ctx, mm, r))), {
2147
- build: (qi, t) => qi.buildGroupBy(t),
2148
- reshape: (raw) => raw.map((r) => reshapeGroupRow(ctx, mm, r)),
2149
- }),
2583
+ groupBy: (args) => {
2584
+ // Core always counts a group when `_count` is omitted (its documented
2585
+ // default); Prisma returns only the blocks the call names. The count
2586
+ // still runs (an `orderBy: { _count }` reads it), it is just not handed
2587
+ // back unasked.
2588
+ const askedForCount = (0, filters_js_1.isPlainRecord)(args) && args._count !== undefined && args._count !== false;
2589
+ const reshape = (raw) => raw.map((r) => {
2590
+ const row = reshapeGroupRow(ctx, mm, r);
2591
+ if (askedForCount || !(0, filters_js_1.isPlainRecord)(row) || !Object.hasOwn(row, '_count'))
2592
+ return row;
2593
+ const { _count: _dropped, ...rest } = row;
2594
+ return rest;
2595
+ });
2596
+ return defer('groupBy', args, () => translateAggregateArgs(ctx, mm, args, true), (qi, t) => qi.groupBy(t).then(reshape), { build: (qi, t) => qi.buildGroupBy(t), reshape });
2597
+ },
2150
2598
  };
2151
2599
  }
2152
2600
  function poolOf(db) {
@@ -2166,7 +2614,7 @@ function placeholderOf(db) {
2166
2614
  * injection-safe. `Prisma.raw(...)` fragments are the sole verbatim splice, by
2167
2615
  * contract.
2168
2616
  */
2169
- function flattenTemplate(strings, values, ph) {
2617
+ function flattenTemplate(strings, values, ph, fragmentOf) {
2170
2618
  const params = [];
2171
2619
  let text = '';
2172
2620
  const append = (segStrings, segValues) => {
@@ -2174,8 +2622,9 @@ function flattenTemplate(strings, values, ph) {
2174
2622
  text += segStrings[i];
2175
2623
  if (i < segValues.length) {
2176
2624
  const v = segValues[i];
2177
- if (isSqlFragment(v)) {
2178
- append(v.strings, v.values);
2625
+ const fragment = fragmentOf(v);
2626
+ if (fragment) {
2627
+ append(fragment.strings, fragment.values);
2179
2628
  }
2180
2629
  else {
2181
2630
  params.push(v);
@@ -2194,17 +2643,43 @@ function flattenTemplate(strings, values, ph) {
2194
2643
  * (`$queryRaw` → rows, `$executeRaw` → affected-row count). The only difference
2195
2644
  * is which connection the executor runs on.
2196
2645
  */
2197
- function makeRawSurface(exec, ph) {
2646
+ function makeRawSurface(exec, ph, fragmentOf) {
2647
+ /**
2648
+ * The statement a `$queryRaw` / `$executeRaw` call means. Prisma takes either a
2649
+ * tagged template or ONE fragment (`$queryRaw(Prisma.sql\`...\`)`). The
2650
+ * fragment form used to be read as a template whose `strings` was the
2651
+ * fragment object itself, which has no indices, so the statement sent was the
2652
+ * empty string and the call resolved to `[]` without a word.
2653
+ */
2654
+ const compose = (first, values, method) => {
2655
+ const fragment = fragmentOf(first);
2656
+ if (fragment) {
2657
+ if (values.length > 0) {
2658
+ throw new errors_js_1.ValidationError(`prisma-compat: ${method}(fragment) takes the fragment alone; ${values.length} further ` +
2659
+ 'argument(s) would be ignored. Interpolate the values inside the fragment instead.');
2660
+ }
2661
+ return flattenTemplate(fragment.strings, fragment.values, ph, fragmentOf);
2662
+ }
2663
+ // Anything else that is not a template's strings array (a plain string, an
2664
+ // object that is not a recognized fragment) would flatten to an empty or
2665
+ // character-split statement. Prisma refuses those too.
2666
+ if (!Array.isArray(first)) {
2667
+ throw new errors_js_1.ValidationError(`prisma-compat: ${method} takes a tagged template (${method}\`SELECT ...\`) or one fragment ` +
2668
+ `(${method}(Prisma.sql\`SELECT ...\`)), received ${describeValue(first)}. ` +
2669
+ `For SQL text built at runtime use ${method}Unsafe(text, ...values).`);
2670
+ }
2671
+ return flattenTemplate(first, values, ph, fragmentOf);
2672
+ };
2198
2673
  return {
2199
2674
  $queryRaw: async (strings, ...values) => {
2200
- const { text, params } = flattenTemplate(strings, values, ph);
2675
+ const { text, params } = compose(strings, values, '$queryRaw');
2201
2676
  return (await exec(text, params, '$queryRaw')).rows;
2202
2677
  },
2203
2678
  $queryRawUnsafe: async (sql, ...params) => {
2204
2679
  return (await exec(sql, params, '$queryRawUnsafe')).rows;
2205
2680
  },
2206
2681
  $executeRaw: async (strings, ...values) => {
2207
- const { text, params } = flattenTemplate(strings, values, ph);
2682
+ const { text, params } = compose(strings, values, '$executeRaw');
2208
2683
  return (await exec(text, params, '$executeRaw')).rowCount ?? 0;
2209
2684
  },
2210
2685
  $executeRawUnsafe: async (sql, ...params) => {
@@ -2213,6 +2688,33 @@ function makeRawSurface(exec, ph) {
2213
2688
  };
2214
2689
  }
2215
2690
  // ---------------------------------------------------------------------------
2691
+ // Core interop: the Turbine client under a compat client
2692
+ // ---------------------------------------------------------------------------
2693
+ /**
2694
+ * Every compat client and transaction client this module builds, mapped to the
2695
+ * core client or core transaction it runs on. A WeakMap rather than a property,
2696
+ * so nothing is added to a surface whose every key is a model name or a Prisma
2697
+ * `$` member, and a hand-made lookalike object is never mistaken for one.
2698
+ */
2699
+ const CORE_OF = new WeakMap();
2700
+ /** Each compat client's way of wrapping a core transaction it did not open. */
2701
+ const BIND_OF = new WeakMap();
2702
+ function turbineOf(compat) {
2703
+ const core = typeof compat === 'object' && compat !== null ? CORE_OF.get(compat) : undefined;
2704
+ if (core === undefined) {
2705
+ throw new errors_js_1.ValidationError('prisma-compat: turbineOf takes a client made by createPrismaCompatClient, or the `tx` one of its ' +
2706
+ '$transaction callbacks receives.');
2707
+ }
2708
+ return core;
2709
+ }
2710
+ function bindTransaction(compat, tx) {
2711
+ const bind = typeof compat === 'object' && compat !== null ? BIND_OF.get(compat) : undefined;
2712
+ if (!bind) {
2713
+ throw new errors_js_1.ValidationError('prisma-compat: bindTransaction takes a client made by createPrismaCompatClient (not a transaction client).');
2714
+ }
2715
+ return bind(tx);
2716
+ }
2717
+ // ---------------------------------------------------------------------------
2216
2718
  // createPrismaCompatClient
2217
2719
  // ---------------------------------------------------------------------------
2218
2720
  /**
@@ -2442,6 +2944,7 @@ function createPrismaCompatClient(client, map, options = {}) {
2442
2944
  stablePkOrder: options.stablePkOrder ?? false,
2443
2945
  prismaErrorCodes: options.prismaErrorCodes ?? false,
2444
2946
  },
2947
+ fragmentOf: options.prismaNamespace === undefined ? ownFragment : foreignFragmentReader(options.prismaNamespace),
2445
2948
  };
2446
2949
  // Every model the client exposes: the map's Prisma models, plus the implicit
2447
2950
  // many-to-many junction tables (see below). Both delegate loops (base and
@@ -2470,6 +2973,24 @@ function createPrismaCompatClient(client, map, options = {}) {
2470
2973
  baseDelegates.set(prismaModel, makeDelegate(ctx, mm, () => db.table(mm.table), (fn) => db.$transaction((tx) => fn((n) => tx.table(n)))));
2471
2974
  }
2472
2975
  const ph = placeholderOf(db);
2976
+ // `$connect` / `$disconnect` used to be no-ops, so a script that ended with
2977
+ // `await prisma.$disconnect()` kept the pool open and never exited. One
2978
+ // closing promise per wrapped client: every extended client shares it, and a
2979
+ // second call resolves with the first instead of ending the pool twice.
2980
+ let closing;
2981
+ const lifecycle = {
2982
+ connect: async () => {
2983
+ if (typeof db.connect === 'function')
2984
+ await db.connect();
2985
+ },
2986
+ disconnect: () => {
2987
+ closing ??= (async () => {
2988
+ if (typeof db.disconnect === 'function')
2989
+ await db.disconnect();
2990
+ })();
2991
+ return closing;
2992
+ },
2993
+ };
2473
2994
  // Prefer the client's own raw seam, which emits a `$on('query')` event; a
2474
2995
  // client without one (an older core, a test stub) runs on the pool as before.
2475
2996
  const runRaw = async (text, params, action) => {
@@ -2517,6 +3038,34 @@ function createPrismaCompatClient(client, map, options = {}) {
2517
3038
  * transaction. Absent, it is a TypeError at the call site instead.
2518
3039
  */
2519
3040
  const build = (exts) => {
3041
+ /**
3042
+ * The transaction-scoped compat client over ONE core transaction: a delegate
3043
+ * per model (both spellings), extended like the base ones, plus the raw
3044
+ * surface on the transaction's own connection. The callback `$transaction`
3045
+ * and {@link bindTransaction} both build it here, so a transaction this
3046
+ * layer opened and one it was handed cannot differ.
3047
+ */
3048
+ const txClientFor = (tx) => {
3049
+ const txDelegates = {};
3050
+ for (const [prismaModel, mm] of delegateModels) {
3051
+ (0, filters_js_1.setOwn)(txDelegates, prismaModel, extendDelegate(makeDelegate(ctx, mm, () => tx.table(mm.table), (fn) => fn((n) => tx.table(n))), prismaModel, exts));
3052
+ const alias = prismaPropertyAlias(prismaModel);
3053
+ if (alias && !Object.hasOwn(map.models, alias) && !Object.hasOwn(txDelegates, alias)) {
3054
+ (0, filters_js_1.setOwn)(txDelegates, alias, (0, utils_js_1.ownLookup)(txDelegates, prismaModel));
3055
+ }
3056
+ }
3057
+ // Raw SQL on the transaction's own connection. Prisma's tx client
3058
+ // carries these four, and code that mixes `$transaction` with raw SQL is
3059
+ // the common case in a migrated codebase. No model can shadow them: a
3060
+ // Prisma model name cannot start with `$`, and junction accessors skip
3061
+ // every CLIENT_RESERVED_KEYS name.
3062
+ const txClient = {
3063
+ ...txDelegates,
3064
+ ...makeRawSurface(txRunRaw(tx), ph, ctx.fragmentOf),
3065
+ };
3066
+ CORE_OF.set(txClient, tx);
3067
+ return txClient;
3068
+ };
2520
3069
  // Delegates bound to the base client, extended where the extension has
2521
3070
  // members for them. `baseDelegates` is built ONCE (outside), so a client
2522
3071
  // whose extension only adds `client` members shares the very same delegate
@@ -2572,23 +3121,7 @@ function createPrismaCompatClient(client, map, options = {}) {
2572
3121
  }
2573
3122
  // Callback form: hand the user a compat client bound to the tx connection.
2574
3123
  const fn = arg;
2575
- return db.$transaction((tx) => {
2576
- const txDelegates = {};
2577
- for (const [prismaModel, mm] of delegateModels) {
2578
- (0, filters_js_1.setOwn)(txDelegates, prismaModel, extendDelegate(makeDelegate(ctx, mm, () => tx.table(mm.table), (fn) => fn((n) => tx.table(n))), prismaModel, exts));
2579
- const alias = prismaPropertyAlias(prismaModel);
2580
- if (alias && !Object.hasOwn(map.models, alias) && !Object.hasOwn(txDelegates, alias)) {
2581
- (0, filters_js_1.setOwn)(txDelegates, alias, (0, utils_js_1.ownLookup)(txDelegates, prismaModel));
2582
- }
2583
- }
2584
- // Raw SQL on the transaction's own connection. Prisma's tx client
2585
- // carries these four, and code that mixes `$transaction` with raw SQL is
2586
- // the common case in a migrated codebase. No model can shadow them: a
2587
- // Prisma model name cannot start with `$`, and junction accessors skip
2588
- // every CLIENT_RESERVED_KEYS name.
2589
- const txClient = { ...txDelegates, ...makeRawSurface(txRunRaw(tx), ph) };
2590
- return fn(txClient);
2591
- }, txOptions);
3124
+ return db.$transaction((tx) => fn(txClientFor(tx)), txOptions);
2592
3125
  }),
2593
3126
  $extends: ((extension) => {
2594
3127
  // Prisma's callback form: `client.$extends(fn)` IS `fn(client)`.
@@ -2596,9 +3129,9 @@ function createPrismaCompatClient(client, map, options = {}) {
2596
3129
  return extension(result);
2597
3130
  return build(applyExtension(exts, extension, modelKeys, clientKeys));
2598
3131
  }),
2599
- ...makeRawSurface(runRaw, ph),
2600
- $connect: async () => { },
2601
- $disconnect: async () => { },
3132
+ ...makeRawSurface(runRaw, ph, ctx.fragmentOf),
3133
+ $connect: () => lifecycle.connect(),
3134
+ $disconnect: () => lifecycle.disconnect(),
2602
3135
  };
2603
3136
  // Assemble the result: model delegates keyed by Prisma model name, plus the
2604
3137
  // client-level base methods. A plain object suffices, every model is a known
@@ -2616,6 +3149,14 @@ function createPrismaCompatClient(client, map, options = {}) {
2616
3149
  // Extension `client` members last: every name was checked against the real
2617
3150
  // client keys in applyExtension, so this can never overwrite a delegate.
2618
3151
  Object.assign(result, exts.client);
3152
+ CORE_OF.set(result, client);
3153
+ BIND_OF.set(result, (tx) => {
3154
+ if (tx === client || typeof tx?.table !== 'function') {
3155
+ throw new errors_js_1.ValidationError('prisma-compat: bindTransaction takes the core transaction client a `$transaction(async (tx) => ...)` ' +
3156
+ 'callback receives on the TurbineClient this compat client wraps.');
3157
+ }
3158
+ return txClientFor(tx);
3159
+ });
2619
3160
  return result;
2620
3161
  };
2621
3162
  return build(EMPTY_EXTENSIONS);