prisma-sql 1.75.12 → 1.76.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -386,9 +386,6 @@ var SQL_KEYWORDS = /* @__PURE__ */ new Set([
386
386
  ]);
387
387
  var SQL_RESERVED_WORDS = SQL_KEYWORDS;
388
388
  var DEFAULT_WHERE_CLAUSE = "1=1";
389
- var SPECIAL_FIELDS = Object.freeze({
390
- ID: "id"
391
- });
392
389
  var SQL_TEMPLATES = Object.freeze({
393
390
  PUBLIC_SCHEMA: "public",
394
391
  WHERE: "WHERE",
@@ -524,29 +521,6 @@ function hasRequiredKeywords(sql) {
524
521
  return hasSelect && hasFrom && upper.indexOf("SELECT") < upper.indexOf("FROM");
525
522
  }
526
523
 
527
- // src/builder/shared/errors.ts
528
- var SqlBuilderError = class extends Error {
529
- constructor(message, code, context) {
530
- super(message);
531
- this.name = "SqlBuilderError";
532
- this.code = code;
533
- this.context = context;
534
- }
535
- };
536
- function createError(message, ctx, code = "VALIDATION_ERROR") {
537
- const parts = [message];
538
- if (isNonEmptyArray(ctx.path)) {
539
- parts.push(`Path: ${ctx.path.join(".")}`);
540
- }
541
- if (isNotNullish(ctx.modelName)) {
542
- parts.push(`Model: ${ctx.modelName}`);
543
- }
544
- if (isNonEmptyArray(ctx.availableFields)) {
545
- parts.push(`Available fields: ${ctx.availableFields.join(", ")}`);
546
- }
547
- return new SqlBuilderError(parts.join("\n"), code, ctx);
548
- }
549
-
550
524
  // src/builder/shared/validators/sql-validators.ts
551
525
  function isValidWhereClause(clause) {
552
526
  return isNotNullish(clause) && clause.trim().length > 0 && clause !== DEFAULT_WHERE_CLAUSE;
@@ -689,8 +663,11 @@ function needsQuoting(identifier) {
689
663
  }
690
664
 
691
665
  // src/builder/shared/sql-utils.ts
666
+ var _a2;
667
+ var IS_PRODUCTION2 = typeof process !== "undefined" && ((_a2 = process.env) == null ? void 0 : _a2.NODE_ENV) === "production";
692
668
  var COL_EXPR_CACHE = /* @__PURE__ */ new WeakMap();
693
669
  var COL_WITH_ALIAS_CACHE = /* @__PURE__ */ new WeakMap();
670
+ var TABLE_REF_CACHE = /* @__PURE__ */ new Map();
694
671
  function containsControlChars(s) {
695
672
  for (let i = 0; i < s.length; i++) {
696
673
  const code = s.charCodeAt(i);
@@ -925,20 +902,33 @@ function buildTableReference(schemaName, tableName, dialect) {
925
902
  "buildTableReference: tableName is required and cannot be empty"
926
903
  );
927
904
  }
928
- if (containsControlChars(tableName)) {
929
- throw new Error(
930
- "buildTableReference: tableName contains invalid characters"
931
- );
932
- }
933
905
  const d = dialect != null ? dialect : "postgres";
934
906
  if (d === "sqlite") {
935
- return quote(tableName);
907
+ const cacheKey2 = `\0${tableName}\0sqlite`;
908
+ let cached2 = TABLE_REF_CACHE.get(cacheKey2);
909
+ if (cached2) return cached2;
910
+ if (containsControlChars(tableName)) {
911
+ throw new Error(
912
+ "buildTableReference: tableName contains invalid characters"
913
+ );
914
+ }
915
+ cached2 = quote(tableName);
916
+ TABLE_REF_CACHE.set(cacheKey2, cached2);
917
+ return cached2;
936
918
  }
937
919
  if (isEmptyString(schemaName)) {
938
920
  throw new Error(
939
921
  "buildTableReference: schemaName is required and cannot be empty"
940
922
  );
941
923
  }
924
+ const cacheKey = `${schemaName}\0${tableName}\0${d}`;
925
+ let cached = TABLE_REF_CACHE.get(cacheKey);
926
+ if (cached) return cached;
927
+ if (containsControlChars(tableName)) {
928
+ throw new Error(
929
+ "buildTableReference: tableName contains invalid characters"
930
+ );
931
+ }
942
932
  if (containsControlChars(schemaName)) {
943
933
  throw new Error(
944
934
  "buildTableReference: schemaName contains invalid characters"
@@ -946,9 +936,12 @@ function buildTableReference(schemaName, tableName, dialect) {
946
936
  }
947
937
  const safeSchema = schemaName.replace(/"/g, '""');
948
938
  const safeTable = tableName.replace(/"/g, '""');
949
- return `"${safeSchema}"."${safeTable}"`;
939
+ cached = `"${safeSchema}"."${safeTable}"`;
940
+ TABLE_REF_CACHE.set(cacheKey, cached);
941
+ return cached;
950
942
  }
951
943
  function assertSafeAlias(alias) {
944
+ if (IS_PRODUCTION2) return;
952
945
  if (typeof alias !== "string") {
953
946
  throw new Error(`Invalid alias: expected string, got ${typeof alias}`);
954
947
  }
@@ -993,6 +986,7 @@ function assertSafeAlias(alias) {
993
986
  }
994
987
  }
995
988
  function assertSafeTableRef(tableRef) {
989
+ if (IS_PRODUCTION2) return;
996
990
  assertSafeQualifiedName(tableRef);
997
991
  }
998
992
  function normalizeKeyList(input) {
@@ -1023,7 +1017,7 @@ function normalizeField(field) {
1023
1017
  return field;
1024
1018
  }
1025
1019
  function getFieldIndices(model) {
1026
- var _a3;
1020
+ var _a4;
1027
1021
  let cached = FIELD_INDICES_CACHE.get(model);
1028
1022
  if (cached) return cached;
1029
1023
  const scalarFields = /* @__PURE__ */ new Map();
@@ -1044,7 +1038,7 @@ function getFieldIndices(model) {
1044
1038
  } else {
1045
1039
  scalarFields.set(field.name, field);
1046
1040
  scalarNames.push(field.name);
1047
- const fieldType = String((_a3 = field.type) != null ? _a3 : "").toLowerCase();
1041
+ const fieldType = String((_a4 = field.type) != null ? _a4 : "").toLowerCase();
1048
1042
  if (fieldType === "json") {
1049
1043
  jsonFields.add(field.name);
1050
1044
  }
@@ -1058,12 +1052,16 @@ function getFieldIndices(model) {
1058
1052
  quotedColumns.set(field.name, quote(columnName));
1059
1053
  }
1060
1054
  }
1055
+ const scalarFieldSet = new Set(scalarNames);
1056
+ const relationFieldSet = new Set(relationNames);
1061
1057
  cached = Object.freeze({
1062
1058
  scalarFields,
1063
1059
  relationFields,
1064
1060
  allFieldsByName,
1065
1061
  scalarNames,
1066
1062
  relationNames,
1063
+ scalarFieldSet,
1064
+ relationFieldSet,
1067
1065
  jsonFields,
1068
1066
  pkFields,
1069
1067
  columnMap,
@@ -1073,10 +1071,10 @@ function getFieldIndices(model) {
1073
1071
  return cached;
1074
1072
  }
1075
1073
  function getRelationFieldSet(model) {
1076
- return new Set(getFieldIndices(model).relationNames);
1074
+ return getFieldIndices(model).relationFieldSet;
1077
1075
  }
1078
1076
  function getScalarFieldSet(model) {
1079
- return new Set(getFieldIndices(model).scalarNames);
1077
+ return getFieldIndices(model).scalarFieldSet;
1080
1078
  }
1081
1079
  function getColumnMap(model) {
1082
1080
  return getFieldIndices(model).columnMap;
@@ -1111,6 +1109,34 @@ function maybeParseJson(value, jsonSet, fieldName) {
1111
1109
  }
1112
1110
  }
1113
1111
 
1112
+ // src/builder/shared/relation-key-utils.ts
1113
+ var RELATION_KEYS_CACHE = /* @__PURE__ */ new WeakMap();
1114
+ function computeRelationKeys(field, context) {
1115
+ const fkFields = normalizeKeyList(field.foreignKey);
1116
+ if (fkFields.length === 0) {
1117
+ throw new Error(
1118
+ `Relation '${field.name}' is missing foreignKey for ${context}`
1119
+ );
1120
+ }
1121
+ const refs = normalizeKeyList(field.references);
1122
+ const refFields = refs.length > 0 ? refs : fkFields.length === 1 ? ["id"] : [];
1123
+ if (refFields.length !== fkFields.length) {
1124
+ throw new Error(
1125
+ `Relation '${field.name}' references count (${refFields.length}) doesn't match foreignKey count (${fkFields.length}) (context: ${context})`
1126
+ );
1127
+ }
1128
+ const childKeys = field.isForeignKeyLocal ? refFields : fkFields;
1129
+ const parentKeys = field.isForeignKeyLocal ? fkFields : refFields;
1130
+ return { childKeys, parentKeys };
1131
+ }
1132
+ function resolveRelationKeys(field, context = "include") {
1133
+ let cached = RELATION_KEYS_CACHE.get(field);
1134
+ if (cached) return cached;
1135
+ cached = computeRelationKeys(field, context);
1136
+ RELATION_KEYS_CACHE.set(field, cached);
1137
+ return cached;
1138
+ }
1139
+
1114
1140
  // src/builder/joins.ts
1115
1141
  function isRelationField(fieldName, model) {
1116
1142
  return getRelationFieldSet(model).has(fieldName);
@@ -1129,38 +1155,14 @@ function isValidRelationField(field) {
1129
1155
  if (refs.length !== fk.length) return false;
1130
1156
  return true;
1131
1157
  }
1132
- function getReferenceFieldNames(field, foreignKeyCount) {
1133
- const refs = normalizeKeyList(field.references);
1134
- if (refs.length === 0) {
1135
- if (foreignKeyCount === 1) return [SPECIAL_FIELDS.ID];
1136
- return [];
1137
- }
1138
- if (refs.length !== foreignKeyCount) return [];
1139
- return refs;
1140
- }
1141
1158
  function joinCondition(field, parentModel, childModel, parentAlias, childAlias) {
1142
1159
  assertSafeAlias(parentAlias);
1143
1160
  assertSafeAlias(childAlias);
1144
- const fkFields = normalizeKeyList(field.foreignKey);
1145
- if (fkFields.length === 0) {
1146
- throw createError(
1147
- `Relation '${field.name}' is missing foreignKey. This indicates a schema parsing error. Relations must specify fields/references.`,
1148
- { field: field.name }
1149
- );
1150
- }
1151
- const refFields = getReferenceFieldNames(field, fkFields.length);
1152
- if (refFields.length !== fkFields.length) {
1153
- throw createError(
1154
- `Relation '${field.name}' is missing references (or references count does not match foreignKey count). This is required to support non-id and composite keys.`,
1155
- { field: field.name }
1156
- );
1157
- }
1161
+ const { childKeys, parentKeys } = resolveRelationKeys(field, "include");
1158
1162
  const parts = [];
1159
- for (let i = 0; i < fkFields.length; i++) {
1160
- const fk = fkFields[i];
1161
- const ref = refFields[i];
1162
- const left = field.isForeignKeyLocal ? `${childAlias}.${quoteColumn(childModel, ref)}` : `${childAlias}.${quoteColumn(childModel, fk)}`;
1163
- const right = field.isForeignKeyLocal ? `${parentAlias}.${quoteColumn(parentModel, fk)}` : `${parentAlias}.${quoteColumn(parentModel, ref)}`;
1163
+ for (let i = 0; i < parentKeys.length; i++) {
1164
+ const left = field.isForeignKeyLocal ? `${childAlias}.${quoteColumn(childModel, childKeys[i])}` : `${childAlias}.${quoteColumn(childModel, childKeys[i])}`;
1165
+ const right = field.isForeignKeyLocal ? `${parentAlias}.${quoteColumn(parentModel, parentKeys[i])}` : `${parentAlias}.${quoteColumn(parentModel, parentKeys[i])}`;
1164
1166
  parts.push(`${left} = ${right}`);
1165
1167
  }
1166
1168
  return parts.length === 1 ? parts[0] : `(${parts.join(" AND ")})`;
@@ -1169,13 +1171,13 @@ function getModelByName(schemas, name) {
1169
1171
  return schemas.find((m) => m.name === name);
1170
1172
  }
1171
1173
  function normalizeIntLike(name, v, opts = {}) {
1172
- var _a3, _b;
1174
+ var _a4, _b;
1173
1175
  if (!isNotNullish(v)) return void 0;
1174
1176
  if (isDynamicParameter(v)) return v;
1175
1177
  if (typeof v !== "number" || !Number.isFinite(v) || !Number.isInteger(v)) {
1176
1178
  throw new Error(`${name} must be an integer`);
1177
1179
  }
1178
- const min = (_a3 = opts.min) != null ? _a3 : 0;
1180
+ const min = (_a4 = opts.min) != null ? _a4 : 0;
1179
1181
  const allowZero = (_b = opts.allowZero) != null ? _b : true;
1180
1182
  if (!allowZero && v === 0) {
1181
1183
  throw new Error(`${name} must be > 0`);
@@ -1321,6 +1323,14 @@ function reverseOrderByInput(orderBy) {
1321
1323
  var normalizePairs = (pairs, parseValue) => {
1322
1324
  const result = [];
1323
1325
  for (const [field, rawValue] of pairs) {
1326
+ if (typeof rawValue === "string") {
1327
+ const lower = rawValue.toLowerCase();
1328
+ if (lower !== "asc" && lower !== "desc") {
1329
+ throw new Error(
1330
+ `Invalid orderBy direction '${rawValue}' for field '${field}'. Must be 'asc' or 'desc'`
1331
+ );
1332
+ }
1333
+ }
1324
1334
  if (!isScalarOrderByValue(rawValue)) continue;
1325
1335
  const parsed = parseValue(rawValue, field);
1326
1336
  result.push({
@@ -1402,6 +1412,29 @@ function ensureDeterministicOrderByInput(args) {
1402
1412
  return addTiebreaker(orderBy, tiebreaker);
1403
1413
  }
1404
1414
 
1415
+ // src/builder/shared/errors.ts
1416
+ var SqlBuilderError = class extends Error {
1417
+ constructor(message, code, context) {
1418
+ super(message);
1419
+ this.name = "SqlBuilderError";
1420
+ this.code = code;
1421
+ this.context = context;
1422
+ }
1423
+ };
1424
+ function createError(message, ctx, code = "VALIDATION_ERROR") {
1425
+ const parts = [message];
1426
+ if (isNonEmptyArray(ctx.path)) {
1427
+ parts.push(`Path: ${ctx.path.join(".")}`);
1428
+ }
1429
+ if (isNotNullish(ctx.modelName)) {
1430
+ parts.push(`Model: ${ctx.modelName}`);
1431
+ }
1432
+ if (isNonEmptyArray(ctx.availableFields)) {
1433
+ parts.push(`Available fields: ${ctx.availableFields.join(", ")}`);
1434
+ }
1435
+ return new SqlBuilderError(parts.join("\n"), code, ctx);
1436
+ }
1437
+
1405
1438
  // src/builder/shared/primary-key-utils.ts
1406
1439
  var FIELD_BY_NAME_CACHE = /* @__PURE__ */ new WeakMap();
1407
1440
  function normalizeField2(field) {
@@ -1686,7 +1719,7 @@ function assertCursorAndOrderFieldsScalar(model, cursor, orderEntries) {
1686
1719
  }
1687
1720
  }
1688
1721
  function buildCursorCondition(cursor, orderBy, tableName, alias, params, dialect, model) {
1689
- var _a3;
1722
+ var _a4;
1690
1723
  assertSafeTableRef(tableName);
1691
1724
  assertSafeAlias(alias);
1692
1725
  const d = dialect != null ? dialect : getGlobalDialect();
@@ -1781,7 +1814,7 @@ function buildCursorCondition(cursor, orderBy, tableName, alias, params, dialect
1781
1814
  const e = finalOrderEntries[level];
1782
1815
  const c = col(alias, e.field, model);
1783
1816
  const cursorField = cteName + "." + quoteColumn(model, e.field);
1784
- const nulls = (_a3 = e.nulls) != null ? _a3 : defaultNullsFor(d, e.direction);
1817
+ const nulls = (_a4 = e.nulls) != null ? _a4 : defaultNullsFor(d, e.direction);
1785
1818
  andParts.push(buildCursorInequalityExpr(c, e.direction, nulls, cursorField));
1786
1819
  orClauses.push("(" + andParts.join(SQL_SEPARATORS.CONDITION_AND) + ")");
1787
1820
  }
@@ -1901,34 +1934,6 @@ function createAliasGenerator(maxAliases = 1e4) {
1901
1934
  };
1902
1935
  }
1903
1936
 
1904
- // src/builder/shared/relation-key-utils.ts
1905
- var RELATION_KEYS_CACHE = /* @__PURE__ */ new WeakMap();
1906
- function computeRelationKeys(field, context) {
1907
- const fkFields = normalizeKeyList(field.foreignKey);
1908
- if (fkFields.length === 0) {
1909
- throw new Error(
1910
- `Relation '${field.name}' is missing foreignKey for ${context}`
1911
- );
1912
- }
1913
- const refs = normalizeKeyList(field.references);
1914
- const refFields = refs.length > 0 ? refs : fkFields.length === 1 ? ["id"] : [];
1915
- if (refFields.length !== fkFields.length) {
1916
- throw new Error(
1917
- `Relation '${field.name}' references count (${refFields.length}) doesn't match foreignKey count (${fkFields.length}) (context: ${context})`
1918
- );
1919
- }
1920
- const childKeys = field.isForeignKeyLocal ? refFields : fkFields;
1921
- const parentKeys = field.isForeignKeyLocal ? fkFields : refFields;
1922
- return { childKeys, parentKeys };
1923
- }
1924
- function resolveRelationKeys(field, context = "include") {
1925
- let cached = RELATION_KEYS_CACHE.get(field);
1926
- if (cached) return cached;
1927
- cached = computeRelationKeys(field, context);
1928
- RELATION_KEYS_CACHE.set(field, cached);
1929
- return cached;
1930
- }
1931
-
1932
1937
  // src/builder/shared/fk-join-utils.ts
1933
1938
  var FK_COLUMN_PREFIX = "__fk";
1934
1939
  function fkColumnName(index) {
@@ -2114,7 +2119,7 @@ function resolveCountRelationOrThrow(relName, model, schemaByName) {
2114
2119
  `_count.${relName} references unknown relation on model ${model.name}`
2115
2120
  );
2116
2121
  }
2117
- const field = model.fields.find((f) => f.name === relName);
2122
+ const field = getFieldIndices(model).allFieldsByName.get(relName);
2118
2123
  if (!field) {
2119
2124
  throw new Error(
2120
2125
  `_count.${relName} references unknown relation on model ${model.name}`
@@ -2191,12 +2196,11 @@ function buildCountJoinAndPair(args) {
2191
2196
  pairSql: `${sqlStringLiteral(args.relName)}, COALESCE(${joinAlias}.${COUNT_COLUMN}, 0)`
2192
2197
  };
2193
2198
  }
2194
- function buildRelationCountSql(countSelect, model, schemas, parentAlias, _params, dialect) {
2199
+ function buildRelationCountSql(countSelect, model, schemas, parentAlias, _params, dialect, modelMap) {
2195
2200
  const joins = [];
2196
2201
  const pairs = [];
2197
2202
  const aliasGen = createAliasGenerator();
2198
- const schemaByName = /* @__PURE__ */ new Map();
2199
- for (const m of schemas) schemaByName.set(m.name, m);
2203
+ const schemaByName = modelMap != null ? modelMap : new Map(schemas.map((m) => [m.name, m]));
2200
2204
  for (const [relName, shouldCount] of Object.entries(countSelect)) {
2201
2205
  if (!shouldCount) continue;
2202
2206
  const resolved = resolveCountRelationOrThrow(relName, model, schemaByName);
@@ -2270,14 +2274,23 @@ function extractNestedIncludeSpec(relArgs, relModel) {
2270
2274
  }
2271
2275
 
2272
2276
  // src/builder/shared/include-tree-walker.ts
2273
- function resolveIncludeRelations(includeSpec, model, schemas) {
2274
- const modelMap = new Map(schemas.map((m) => [m.name, m]));
2277
+ var MODEL_MAP_CACHE = /* @__PURE__ */ new WeakMap();
2278
+ function getOrCreateModelMap(schemas) {
2279
+ let map = MODEL_MAP_CACHE.get(schemas);
2280
+ if (map) return map;
2281
+ map = /* @__PURE__ */ new Map();
2282
+ for (const m of schemas) map.set(m.name, m);
2283
+ MODEL_MAP_CACHE.set(schemas, map);
2284
+ return map;
2285
+ }
2286
+ function resolveIncludeRelations(includeSpec, model, schemas, modelMap) {
2287
+ const map = modelMap != null ? modelMap : getOrCreateModelMap(schemas);
2275
2288
  const results = [];
2276
2289
  for (const [relName, value] of Object.entries(includeSpec)) {
2277
2290
  if (value === false) continue;
2278
- const field = model.fields.find((f) => f.name === relName);
2291
+ const field = getFieldIndices(model).allFieldsByName.get(relName);
2279
2292
  if (!(field == null ? void 0 : field.isRelation) || !field.relatedModel) continue;
2280
- const relModel = modelMap.get(field.relatedModel);
2293
+ const relModel = map.get(field.relatedModel);
2281
2294
  if (!relModel) continue;
2282
2295
  const isList = typeof field.type === "string" && field.type.endsWith("[]");
2283
2296
  const nestedSpec = isPlainObject(value) ? extractNestedIncludeSpec(value, relModel) : {};
@@ -2292,8 +2305,6 @@ function resolveIncludeRelations(includeSpec, model, schemas) {
2292
2305
  }
2293
2306
  return results;
2294
2307
  }
2295
-
2296
- // src/builder/select/strategy-estimator.ts
2297
2308
  var globalRelationStats;
2298
2309
  var globalRoundtripRowEquivalent = 73;
2299
2310
  var CORRELATED_S_BOUNDED = 0.5;
@@ -2302,7 +2313,7 @@ var CORRELATED_WHERE_PENALTY = 3;
2302
2313
  var DEFAULT_FAN = 10;
2303
2314
  var DEFAULT_PARENT_COUNT = 50;
2304
2315
  var MIN_STATS_COVERAGE = 0.1;
2305
- var SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH = 1;
2316
+ var SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH = 2;
2306
2317
  function setRoundtripRowEquivalent(value) {
2307
2318
  globalRoundtripRowEquivalent = value;
2308
2319
  }
@@ -2322,11 +2333,14 @@ function getFanOut(modelName, relName) {
2322
2333
  if (!relStat || relStat.coverage < MIN_STATS_COVERAGE) return DEFAULT_FAN;
2323
2334
  return relStat.avg;
2324
2335
  }
2336
+ var DYNAMIC_TAKE_ESTIMATE = 10;
2325
2337
  function readTake(relArgs) {
2326
2338
  if (!isPlainObject(relArgs)) return Infinity;
2327
2339
  const obj = relArgs;
2328
2340
  if ("take" in obj && typeof obj.take === "number" && obj.take > 0)
2329
2341
  return obj.take;
2342
+ if ("take" in obj && obj.take != null && isDynamicParameter(obj.take))
2343
+ return DYNAMIC_TAKE_ESTIMATE;
2330
2344
  return Infinity;
2331
2345
  }
2332
2346
  function hasWhereClause(relArgs) {
@@ -2340,17 +2354,28 @@ function isListField(field) {
2340
2354
  function hasPaginationArgs(value) {
2341
2355
  if (!isPlainObject(value)) return false;
2342
2356
  const obj = value;
2343
- return "take" in obj && obj.take != null || "skip" in obj && typeof obj.skip === "number" && obj.skip > 0;
2357
+ return "take" in obj && obj.take != null || "skip" in obj && obj.skip != null && (typeof obj.skip === "number" && obj.skip > 0 || isDynamicParameter(obj.skip));
2344
2358
  }
2345
- function buildCostTree(includeSpec, model, schemas, depth = 0) {
2359
+ function buildCostTree(includeSpec, model, schemas, depth = 0, modelMap) {
2346
2360
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return [];
2347
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2361
+ const relations = resolveIncludeRelations(
2362
+ includeSpec,
2363
+ model,
2364
+ schemas,
2365
+ modelMap
2366
+ );
2348
2367
  const nodes = [];
2349
2368
  for (const rel of relations) {
2350
2369
  const fan = rel.isList ? getFanOut(model.name, rel.relName) : 1;
2351
2370
  const take = rel.isList ? readTake(rel.value) : 1;
2352
2371
  const eff = Math.min(fan, take);
2353
- const children = Object.keys(rel.nestedSpec).length > 0 ? buildCostTree(rel.nestedSpec, rel.relModel, schemas, depth + 1) : [];
2372
+ const children = Object.keys(rel.nestedSpec).length > 0 ? buildCostTree(
2373
+ rel.nestedSpec,
2374
+ rel.relModel,
2375
+ schemas,
2376
+ depth + 1,
2377
+ modelMap
2378
+ ) : [];
2354
2379
  nodes.push({
2355
2380
  name: rel.relName,
2356
2381
  fan,
@@ -2414,17 +2439,23 @@ function computeCorrelatedCost(nodes, parentCount) {
2414
2439
  return R + parentCount * subqueryCost(nodes);
2415
2440
  }
2416
2441
  function hasOnlyToOneRelations(includeSpec, model) {
2442
+ const indices = getFieldIndices(model);
2417
2443
  for (const [relName, value] of Object.entries(includeSpec)) {
2418
2444
  if (value === false) continue;
2419
- const field = model.fields.find((f) => f.name === relName);
2445
+ const field = indices.allFieldsByName.get(relName);
2420
2446
  if (!(field == null ? void 0 : field.isRelation)) continue;
2421
2447
  if (isListField(field)) return false;
2422
2448
  }
2423
2449
  return true;
2424
2450
  }
2425
- function countIncludeDepth(includeSpec, model, schemas, depth = 0) {
2451
+ function countIncludeDepth(includeSpec, model, schemas, depth = 0, modelMap) {
2426
2452
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return 0;
2427
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2453
+ const relations = resolveIncludeRelations(
2454
+ includeSpec,
2455
+ model,
2456
+ schemas,
2457
+ modelMap
2458
+ );
2428
2459
  let maxDepth = 0;
2429
2460
  for (const rel of relations) {
2430
2461
  let childDepth = 1;
@@ -2433,27 +2464,34 @@ function countIncludeDepth(includeSpec, model, schemas, depth = 0) {
2433
2464
  rel.nestedSpec,
2434
2465
  rel.relModel,
2435
2466
  schemas,
2436
- depth + 1
2467
+ depth + 1,
2468
+ modelMap
2437
2469
  );
2438
2470
  }
2439
2471
  if (childDepth > maxDepth) maxDepth = childDepth;
2440
2472
  }
2441
2473
  return maxDepth;
2442
2474
  }
2443
- function hasChildPaginationAnywhere(includeSpec, model, schemas, depth = 0) {
2475
+ function hasChildPaginationAnywhere(includeSpec, model, schemas, depth = 0, modelMap) {
2444
2476
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return false;
2445
2477
  for (const [, value] of Object.entries(includeSpec)) {
2446
2478
  if (value === false) continue;
2447
2479
  if (hasPaginationArgs(value)) return true;
2448
2480
  }
2449
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2481
+ const relations = resolveIncludeRelations(
2482
+ includeSpec,
2483
+ model,
2484
+ schemas,
2485
+ modelMap
2486
+ );
2450
2487
  for (const rel of relations) {
2451
2488
  if (Object.keys(rel.nestedSpec).length > 0) {
2452
2489
  if (hasChildPaginationAnywhere(
2453
2490
  rel.nestedSpec,
2454
2491
  rel.relModel,
2455
2492
  schemas,
2456
- depth + 1
2493
+ depth + 1,
2494
+ modelMap
2457
2495
  )) {
2458
2496
  return true;
2459
2497
  }
@@ -2462,7 +2500,17 @@ function hasChildPaginationAnywhere(includeSpec, model, schemas, depth = 0) {
2462
2500
  return false;
2463
2501
  }
2464
2502
  function pickIncludeStrategy(params) {
2465
- const { includeSpec, model, schemas, method, takeValue, canFlatJoin, debug } = params;
2503
+ const {
2504
+ includeSpec,
2505
+ model,
2506
+ schemas,
2507
+ method,
2508
+ takeValue,
2509
+ canFlatJoin,
2510
+ hasChildPagination,
2511
+ debug,
2512
+ modelMap
2513
+ } = params;
2466
2514
  if (Object.keys(includeSpec).length === 0) return "where-in";
2467
2515
  if (canFlatJoin && hasOnlyToOneRelations(includeSpec, model)) {
2468
2516
  if (debug)
@@ -2471,7 +2519,7 @@ function pickIncludeStrategy(params) {
2471
2519
  }
2472
2520
  const isSingleParent = method === "findFirst" || method === "findUnique";
2473
2521
  if (isSingleParent && canFlatJoin) {
2474
- const depth = countIncludeDepth(includeSpec, model, schemas);
2522
+ const depth = countIncludeDepth(includeSpec, model, schemas, 0, modelMap);
2475
2523
  if (depth <= SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH) {
2476
2524
  if (debug)
2477
2525
  console.log(
@@ -2480,8 +2528,37 @@ function pickIncludeStrategy(params) {
2480
2528
  return "flat-join";
2481
2529
  }
2482
2530
  }
2483
- const costTree = buildCostTree(includeSpec, model, schemas);
2531
+ const costTree = buildCostTree(includeSpec, model, schemas, 0, modelMap);
2484
2532
  const treeDepth = maxDepthFromTree(costTree);
2533
+ if (hasChildPagination && treeDepth >= 2) {
2534
+ if (debug)
2535
+ console.log(
2536
+ ` [strategy] ${model.name}: childPagination + depth=${treeDepth} \u2265 2 \u2192 fallback`
2537
+ );
2538
+ return "fallback";
2539
+ }
2540
+ if (hasChildPagination && treeDepth === 1) {
2541
+ if (anyChildHasWhere(costTree)) {
2542
+ if (debug)
2543
+ console.log(
2544
+ ` [strategy] ${model.name}: childPagination + depth=1 + childWhere \u2192 where-in`
2545
+ );
2546
+ return "where-in";
2547
+ }
2548
+ const hasSelectNarrowing = isPlainObject(params.args) && isPlainObject(params.args.select);
2549
+ if (hasSelectNarrowing) {
2550
+ if (debug)
2551
+ console.log(
2552
+ ` [strategy] ${model.name}: childPagination + depth=1 + selectNarrowing \u2192 fallback`
2553
+ );
2554
+ return "fallback";
2555
+ }
2556
+ if (debug)
2557
+ console.log(
2558
+ ` [strategy] ${model.name}: childPagination + depth=1 \u2192 where-in`
2559
+ );
2560
+ return "where-in";
2561
+ }
2485
2562
  if (treeDepth === 1 && anyChildHasWhere(costTree)) {
2486
2563
  if (debug)
2487
2564
  console.log(` [strategy] ${model.name}: depth-1 + childWhere \u2192 where-in`);
@@ -2559,13 +2636,13 @@ function createAliasCounter() {
2559
2636
  }
2560
2637
  };
2561
2638
  }
2562
- function getRelationModel(parentModel, relationName, schemas) {
2639
+ function getRelationModel(parentModel, relationName, schemas, modelMap) {
2563
2640
  const indices = getFieldIndices(parentModel);
2564
2641
  const field = indices.allFieldsByName.get(relationName);
2565
2642
  if (!(field == null ? void 0 : field.isRelation) || !field.relatedModel) {
2566
2643
  throw new Error(`Invalid relation ${relationName} on ${parentModel.name}`);
2567
2644
  }
2568
- const relModel = schemas.find((m) => m.name === field.relatedModel);
2645
+ const relModel = modelMap ? modelMap.get(field.relatedModel) : schemas.find((m) => m.name === field.relatedModel);
2569
2646
  if (!relModel) {
2570
2647
  throw new Error(`Related model ${field.relatedModel} not found`);
2571
2648
  }
@@ -2602,8 +2679,13 @@ function countActiveEntries(spec) {
2602
2679
  }
2603
2680
  return count;
2604
2681
  }
2605
- function canUseFlatJoinForAll(includeSpec, model, schemas, debug) {
2606
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2682
+ function canUseFlatJoinForAll(includeSpec, model, schemas, debug, modelMap) {
2683
+ const relations = resolveIncludeRelations(
2684
+ includeSpec,
2685
+ model,
2686
+ schemas,
2687
+ modelMap
2688
+ );
2607
2689
  if (relations.length < countActiveEntries(includeSpec)) {
2608
2690
  return false;
2609
2691
  }
@@ -2625,14 +2707,20 @@ function canUseFlatJoinForAll(includeSpec, model, schemas, debug) {
2625
2707
  return false;
2626
2708
  }
2627
2709
  if (Object.keys(rel.nestedSpec).length > 0) {
2628
- if (!canUseFlatJoinForAll(rel.nestedSpec, rel.relModel, schemas)) {
2710
+ if (!canUseFlatJoinForAll(
2711
+ rel.nestedSpec,
2712
+ rel.relModel,
2713
+ schemas,
2714
+ debug,
2715
+ modelMap
2716
+ )) {
2629
2717
  return false;
2630
2718
  }
2631
2719
  }
2632
2720
  }
2633
2721
  return true;
2634
2722
  }
2635
- function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialect, prefix, aliasCounter, depth = 0) {
2723
+ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialect, prefix, aliasCounter, depth = 0, modelMap) {
2636
2724
  if (depth > LIMITS.MAX_NESTED_JOIN_DEPTH) {
2637
2725
  throw new Error(
2638
2726
  `Nested joins exceeded maximum depth of ${LIMITS.MAX_NESTED_JOIN_DEPTH} at prefix '${prefix}'`
@@ -2646,7 +2734,7 @@ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialec
2646
2734
  const indices = getFieldIndices(parentModel);
2647
2735
  const field = indices.allFieldsByName.get(relName);
2648
2736
  if (!isValidRelationField(field)) continue;
2649
- const relModel = getRelationModel(parentModel, relName, schemas);
2737
+ const relModel = getRelationModel(parentModel, relName, schemas, modelMap);
2650
2738
  const relTable = buildTableReference(
2651
2739
  SQL_TEMPLATES.PUBLIC_SCHEMA,
2652
2740
  relModel.tableName,
@@ -2687,7 +2775,8 @@ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialec
2687
2775
  dialect,
2688
2776
  nestedPrefix,
2689
2777
  aliasCounter,
2690
- depth + 1
2778
+ depth + 1,
2779
+ modelMap
2691
2780
  );
2692
2781
  joins.push(...deeper.joins);
2693
2782
  selects.push(...deeper.selects);
@@ -2743,6 +2832,8 @@ function buildFlatJoinSql(spec) {
2743
2832
  requiresReduction: false,
2744
2833
  includeSpec: {}
2745
2834
  };
2835
+ const modelMap = /* @__PURE__ */ new Map();
2836
+ for (const m of schemas) modelMap.set(m.name, m);
2746
2837
  const includeSpec = extractRelationEntries(args, model).reduce(
2747
2838
  (acc, { name, value }) => {
2748
2839
  acc[name] = value;
@@ -2753,7 +2844,7 @@ function buildFlatJoinSql(spec) {
2753
2844
  if (Object.keys(includeSpec).length === 0) {
2754
2845
  return emptyResult;
2755
2846
  }
2756
- if (!canUseFlatJoinForAll(includeSpec, model, schemas)) {
2847
+ if (!canUseFlatJoinForAll(includeSpec, model, schemas, false, modelMap)) {
2757
2848
  return emptyResult;
2758
2849
  }
2759
2850
  const { cleanWhere, params } = extractReferencedParams(
@@ -2789,7 +2880,8 @@ function buildFlatJoinSql(spec) {
2789
2880
  dialect,
2790
2881
  "",
2791
2882
  aliasCounter,
2792
- 0
2883
+ 0,
2884
+ modelMap
2793
2885
  );
2794
2886
  if (built.joins.length === 0) {
2795
2887
  return emptyResult;
@@ -3793,8 +3885,8 @@ function buildOperator(expr, op, val, ctx, mode, fieldType) {
3793
3885
  });
3794
3886
  }
3795
3887
  var MAX_PARAM_INDEX = Number.MAX_SAFE_INTEGER - 1e3;
3796
- var _a2;
3797
- var IS_PRODUCTION2 = typeof process !== "undefined" && ((_a2 = process.env) == null ? void 0 : _a2.NODE_ENV) === "production";
3888
+ var _a3;
3889
+ var IS_PRODUCTION3 = typeof process !== "undefined" && ((_a3 = process.env) == null ? void 0 : _a3.NODE_ENV) === "production";
3798
3890
  function assertSameLength(params, mappings) {
3799
3891
  if (params.length !== mappings.length) {
3800
3892
  throw new Error(
@@ -3854,7 +3946,7 @@ function validateMappings(mappings) {
3854
3946
  }
3855
3947
  }
3856
3948
  function validateState(params, mappings, index) {
3857
- if (IS_PRODUCTION2) {
3949
+ if (IS_PRODUCTION3) {
3858
3950
  assertSameLength(params, mappings);
3859
3951
  assertValidNextIndex(index);
3860
3952
  return;
@@ -3912,6 +4004,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3912
4004
  if (frozen) {
3913
4005
  params = params.slice();
3914
4006
  mappings = mappings.slice();
4007
+ dynamicNameToIndex = new Map(dynamicNameToIndex);
3915
4008
  frozen = false;
3916
4009
  }
3917
4010
  }
@@ -3928,6 +4021,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3928
4021
  const dn = validateDynamicName(dynamicName);
3929
4022
  const existing = dynamicNameToIndex.get(dn);
3930
4023
  if (existing !== void 0) return formatPosition(existing);
4024
+ ensureMutable();
3931
4025
  const position = index;
3932
4026
  dynamicNameToIndex.set(dn, position);
3933
4027
  return registerParam(void 0, { index: position, dynamicName: dn });
@@ -3958,7 +4052,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3958
4052
  index,
3959
4053
  params,
3960
4054
  mappings,
3961
- dynamicNameIndex: new Map(dynamicNameToIndex)
4055
+ dynamicNameIndex: dynamicNameToIndex
3962
4056
  };
3963
4057
  cachedSnapshot = snap;
3964
4058
  dirty = false;
@@ -4013,10 +4107,10 @@ function toPublicResult(clause, joins, params) {
4013
4107
 
4014
4108
  // src/builder/where.ts
4015
4109
  function buildWhereClause(where, options) {
4016
- var _a3, _b, _c, _d, _e;
4110
+ var _a4, _b, _c, _d, _e;
4017
4111
  assertSafeAlias(options.alias);
4018
4112
  const dialect = options.dialect || getGlobalDialect();
4019
- const params = (_a3 = options.params) != null ? _a3 : createParamStore(1, dialect);
4113
+ const params = (_a4 = options.params) != null ? _a4 : createParamStore(1, dialect);
4020
4114
  const ctx = {
4021
4115
  alias: options.alias,
4022
4116
  model: options.model,
@@ -4099,12 +4193,13 @@ function reindexWhereParams(whereClause, specParams, collector) {
4099
4193
  }
4100
4194
  return clean;
4101
4195
  }
4102
- function getRelationModel2(parentModel, relationName, schemas) {
4103
- var _a3;
4196
+ function getRelationModel2(parentModel, relationName, schemas, modelMap) {
4197
+ var _a4, _b;
4104
4198
  const indices = getFieldIndices(parentModel);
4105
4199
  const field = indices.allFieldsByName.get(relationName);
4106
4200
  if (!(field == null ? void 0 : field.isRelation) || !field.relatedModel) return null;
4107
- return (_a3 = schemas.find((m) => m.name === field.relatedModel)) != null ? _a3 : null;
4201
+ if (modelMap) return (_a4 = modelMap.get(field.relatedModel)) != null ? _a4 : null;
4202
+ return (_b = schemas.find((m) => m.name === field.relatedModel)) != null ? _b : null;
4108
4203
  }
4109
4204
  function extractOrderByInput(relArgs) {
4110
4205
  if (!isPlainObject(relArgs)) return void 0;
@@ -4149,7 +4244,12 @@ function buildLateralForRelation(relationName, relArgs, field, relModel, parentM
4149
4244
  const nestedIndices = getFieldIndices(relModel);
4150
4245
  const nestedField = nestedIndices.allFieldsByName.get(nestedName);
4151
4246
  if (!nestedField || !isValidRelationField(nestedField)) continue;
4152
- const nestedModel = getRelationModel2(relModel, nestedName, ctx.schemas);
4247
+ const nestedModel = getRelationModel2(
4248
+ relModel,
4249
+ nestedName,
4250
+ ctx.schemas,
4251
+ ctx.modelMap
4252
+ );
4153
4253
  if (!nestedModel) continue;
4154
4254
  const nested = buildLateralForRelation(
4155
4255
  nestedName,
@@ -4252,12 +4352,12 @@ function buildLateralForRelation(relationName, relArgs, field, relModel, parentM
4252
4352
  }
4253
4353
  const joinSql = `LEFT JOIN LATERAL (${outerSql}) ${latAlias} ON true`;
4254
4354
  const fieldTypes = selectedFields.map((fieldName) => {
4255
- var _a3;
4355
+ var _a4;
4256
4356
  const f = indices.scalarFields.get(fieldName);
4257
4357
  if (!f) return null;
4258
4358
  return {
4259
4359
  fieldName: f.name,
4260
- type: String((_a3 = f.type) != null ? _a3 : "").toLowerCase()
4360
+ type: String((_a4 = f.type) != null ? _a4 : "").toLowerCase()
4261
4361
  };
4262
4362
  }).filter(Boolean);
4263
4363
  const meta = {
@@ -4275,8 +4375,13 @@ function countActiveEntries2(spec) {
4275
4375
  }
4276
4376
  return count;
4277
4377
  }
4278
- function canUseLateralJoin(includeSpec, parentModel, schemas) {
4279
- const relations = resolveIncludeRelations(includeSpec, parentModel, schemas);
4378
+ function canUseLateralJoin(includeSpec, parentModel, schemas, modelMap) {
4379
+ const relations = resolveIncludeRelations(
4380
+ includeSpec,
4381
+ parentModel,
4382
+ schemas,
4383
+ modelMap
4384
+ );
4280
4385
  if (relations.length < countActiveEntries2(includeSpec)) {
4281
4386
  return false;
4282
4387
  }
@@ -4285,14 +4390,14 @@ function canUseLateralJoin(includeSpec, parentModel, schemas) {
4285
4390
  if (!keys || keys.childKeys.length === 0 || keys.parentKeys.length === 0)
4286
4391
  return false;
4287
4392
  if (Object.keys(rel.nestedSpec).length > 0) {
4288
- if (!canUseLateralJoin(rel.nestedSpec, rel.relModel, schemas))
4393
+ if (!canUseLateralJoin(rel.nestedSpec, rel.relModel, schemas, modelMap))
4289
4394
  return false;
4290
4395
  }
4291
4396
  }
4292
4397
  return true;
4293
4398
  }
4294
4399
  function buildLateralJoinSql(spec) {
4295
- var _a3;
4400
+ var _a4;
4296
4401
  const {
4297
4402
  from,
4298
4403
  whereClause,
@@ -4312,6 +4417,8 @@ function buildLateralJoinSql(spec) {
4312
4417
  isLateral: false,
4313
4418
  lateralMeta: []
4314
4419
  };
4420
+ const modelMap = /* @__PURE__ */ new Map();
4421
+ for (const m of schemas) modelMap.set(m.name, m);
4315
4422
  const entries = extractRelationEntries(args, model);
4316
4423
  const includeSpec = {};
4317
4424
  for (const e of entries) {
@@ -4338,7 +4445,8 @@ function buildLateralJoinSql(spec) {
4338
4445
  schemas,
4339
4446
  dialect,
4340
4447
  aliasCounter,
4341
- collector
4448
+ collector,
4449
+ modelMap
4342
4450
  };
4343
4451
  const lateralJoins = [];
4344
4452
  const lateralSelects = [];
@@ -4348,7 +4456,7 @@ function buildLateralJoinSql(spec) {
4348
4456
  const indices = getFieldIndices(model);
4349
4457
  const field = indices.allFieldsByName.get(relName);
4350
4458
  if (!field || !isValidRelationField(field)) continue;
4351
- const relModel = getRelationModel2(model, relName, schemas);
4459
+ const relModel = getRelationModel2(model, relName, schemas, modelMap);
4352
4460
  if (!relModel) continue;
4353
4461
  const result = buildLateralForRelation(
4354
4462
  relName,
@@ -4366,7 +4474,7 @@ function buildLateralJoinSql(spec) {
4366
4474
  lateralMeta.push(result.meta);
4367
4475
  }
4368
4476
  if (lateralJoins.length === 0) return emptyResult;
4369
- const baseSelect = ((_a3 = spec.select) != null ? _a3 : "").trim();
4477
+ const baseSelect = ((_a4 = spec.select) != null ? _a4 : "").trim();
4370
4478
  const allSelects = [baseSelect, ...lateralSelects].filter((s) => s && s.trim().length > 0).join(", ");
4371
4479
  if (!allSelects) {
4372
4480
  return emptyResult;
@@ -4486,9 +4594,9 @@ function renderOrderBySimple(entries, alias) {
4486
4594
  return out.join(SQL_SEPARATORS.ORDER_BY);
4487
4595
  }
4488
4596
  function ensureIdTiebreakerEntries(entries, model) {
4489
- var _a3, _b;
4490
- const idField = (_b = (_a3 = model == null ? void 0 : model.fields) == null ? void 0 : _a3.find) == null ? void 0 : _b.call(
4491
- _a3,
4597
+ var _a4, _b;
4598
+ const idField = (_b = (_a4 = model == null ? void 0 : model.fields) == null ? void 0 : _a4.find) == null ? void 0 : _b.call(
4599
+ _a4,
4492
4600
  (f) => f.name === DEFAULT_PRIMARY_KEY2 && !f.isRelation
4493
4601
  );
4494
4602
  if (!idField) return entries;
@@ -4530,14 +4638,14 @@ function buildJoinsSql(...joinGroups) {
4530
4638
  return all.length > 0 ? " " + all.join(" ") : "";
4531
4639
  }
4532
4640
  function buildSqliteDistinctQuery(spec, selectWithIncludes, countJoins) {
4533
- var _a3, _b;
4641
+ var _a4, _b;
4534
4642
  const { includes, from, whereClause, whereJoins, distinct, model } = spec;
4535
4643
  if (!isNotNullish(distinct) || !isNonEmptyArray(distinct)) {
4536
4644
  throw new Error("buildSqliteDistinctQuery requires distinct fields");
4537
4645
  }
4538
4646
  const scalarNames = parseSimpleScalarSelect(spec.select, from.alias);
4539
4647
  const includeNames = includes.map((i) => i.name);
4540
- const hasCount = Boolean((_b = (_a3 = spec.args) == null ? void 0 : _a3.select) == null ? void 0 : _b[COUNT_SELECT_KEY]);
4648
+ const hasCount = Boolean((_b = (_a4 = spec.args) == null ? void 0 : _a4.select) == null ? void 0 : _b[COUNT_SELECT_KEY]);
4541
4649
  const outerSelectCols = buildOutputColumns(
4542
4650
  scalarNames,
4543
4651
  includeNames,
@@ -4637,12 +4745,12 @@ function resolveCountSelect(countSelectRaw, model) {
4637
4745
  return null;
4638
4746
  }
4639
4747
  function buildIncludeColumns(spec) {
4640
- var _a3, _b, _c, _d, _e;
4748
+ var _a4, _b, _c, _d, _e;
4641
4749
  const { select, includes, dialect, model, schemas, from, params } = spec;
4642
4750
  const baseSelect = (select != null ? select : "").trim();
4643
4751
  let countCols = "";
4644
4752
  let countJoins = [];
4645
- const countSelectRaw = (_e = (_b = (_a3 = spec.args) == null ? void 0 : _a3.select) == null ? void 0 : _b[COUNT_SELECT_KEY]) != null ? _e : (_d = (_c = spec.args) == null ? void 0 : _c.include) == null ? void 0 : _d[COUNT_SELECT_KEY];
4753
+ const countSelectRaw = (_e = (_b = (_a4 = spec.args) == null ? void 0 : _a4.select) == null ? void 0 : _b[COUNT_SELECT_KEY]) != null ? _e : (_d = (_c = spec.args) == null ? void 0 : _c.include) == null ? void 0 : _d[COUNT_SELECT_KEY];
4646
4754
  if (countSelectRaw) {
4647
4755
  const resolvedCountSelect = resolveCountSelect(countSelectRaw, model);
4648
4756
  if (resolvedCountSelect && Object.keys(resolvedCountSelect).length > 0) {
@@ -4824,16 +4932,33 @@ function constructFinalSql(spec) {
4824
4932
  isNotNullish(pagination.take);
4825
4933
  const takeValue = typeof pagination.take === "number" ? pagination.take : null;
4826
4934
  if (dialect === "postgres" && hasIncludes) {
4827
- const canFlatJoin = canUseFlatJoinForAll(includeSpec, model, schemas);
4828
- canUseLateralJoin(includeSpec, model, schemas);
4829
- hasChildPaginationAnywhere(includeSpec, model, schemas);
4935
+ const modelMap = getOrCreateModelMap(schemas);
4936
+ const canFlatJoin = canUseFlatJoinForAll(
4937
+ includeSpec,
4938
+ model,
4939
+ schemas,
4940
+ false,
4941
+ modelMap
4942
+ );
4943
+ canUseLateralJoin(includeSpec, model, schemas, modelMap);
4944
+ const hasChildPag = hasChildPaginationAnywhere(
4945
+ includeSpec,
4946
+ model,
4947
+ schemas,
4948
+ 0,
4949
+ modelMap
4950
+ );
4830
4951
  const strategy = pickIncludeStrategy({
4831
4952
  includeSpec,
4832
4953
  model,
4833
4954
  schemas,
4834
4955
  method,
4956
+ args,
4835
4957
  takeValue,
4836
- canFlatJoin});
4958
+ canFlatJoin,
4959
+ hasChildPagination: hasChildPag,
4960
+ modelMap
4961
+ });
4837
4962
  if (strategy === "flat-join") {
4838
4963
  const flatResult = buildFlatJoinSql(spec);
4839
4964
  if (flatResult.sql) {
@@ -4956,8 +5081,8 @@ function buildDefaultScalarFields(model, alias) {
4956
5081
  return out;
4957
5082
  }
4958
5083
  function getDefaultSelectCached(model, alias) {
4959
- var _a3;
4960
- return (_a3 = DEFAULT_SELECT_CACHE.get(model)) == null ? void 0 : _a3.get(alias);
5084
+ var _a4;
5085
+ return (_a4 = DEFAULT_SELECT_CACHE.get(model)) == null ? void 0 : _a4.get(alias);
4961
5086
  }
4962
5087
  function cacheDefaultSelect(model, alias, sql) {
4963
5088
  let cache = DEFAULT_SELECT_CACHE.get(model);
@@ -5239,7 +5364,8 @@ function buildSelectWithNestedIncludes(relArgs, relModel, relAlias, ctx) {
5239
5364
  ctx.schemas,
5240
5365
  relAlias,
5241
5366
  ctx.params,
5242
- ctx.dialect
5367
+ ctx.dialect,
5368
+ ctx.schemaByName
5243
5369
  );
5244
5370
  if (!countBuild.jsonPairs) return baseSelect2;
5245
5371
  countJoins.push(...countBuild.joins);
@@ -5627,7 +5753,9 @@ function resolveTableRef(model, dialect) {
5627
5753
  return buildTableReference(schema, tableName, dialect);
5628
5754
  }
5629
5755
  function findRelationField(model, fieldName) {
5630
- return model.fields.find((f) => f.name === fieldName && f.isRelation);
5756
+ const field = getFieldIndices(model).allFieldsByName.get(fieldName);
5757
+ if (!field || !field.isRelation) return void 0;
5758
+ return field;
5631
5759
  }
5632
5760
  function nextJoinAlias(ctx) {
5633
5761
  let alias;
@@ -5654,7 +5782,7 @@ function resolveRelationOrderByChain(relationFieldName, value, currentModel, cur
5654
5782
  `Relation field '${relationFieldName}' not found on model ${currentModel.name}`
5655
5783
  );
5656
5784
  }
5657
- const relatedModel = getModelByName(ctx.schemas, field.relatedModel);
5785
+ const relatedModel = ctx.modelMap.get(field.relatedModel);
5658
5786
  if (!relatedModel) {
5659
5787
  throw new Error(
5660
5788
  `Related model '${field.relatedModel}' not found for relation '${relationFieldName}'`
@@ -5720,12 +5848,14 @@ function buildOrderByWithRelations(orderBy, alias, dialect, model, schemas) {
5720
5848
  const relationSet = getRelationFieldSet(model);
5721
5849
  const scalarSet = getScalarFieldSet(model);
5722
5850
  const orderFragments = [];
5851
+ const modelMap = /* @__PURE__ */ new Map();
5852
+ for (const m of schemas) modelMap.set(m.name, m);
5723
5853
  const ctx = {
5724
- schemas,
5725
5854
  dialect,
5726
5855
  joins: [],
5727
5856
  usedAliases: /* @__PURE__ */ new Set(),
5728
- aliasCounter: { value: 0 }
5857
+ aliasCounter: { value: 0 },
5858
+ modelMap
5729
5859
  };
5730
5860
  for (const [fieldName, value] of expanded) {
5731
5861
  if (scalarSet.has(fieldName)) {
@@ -5780,11 +5910,11 @@ function mapFirstOrderByByField(existing) {
5780
5910
  return m;
5781
5911
  }
5782
5912
  function buildPostgresDistinctOrderBy(distinctFields, existing) {
5783
- var _a3;
5913
+ var _a4;
5784
5914
  const firstByField = mapFirstOrderByByField(existing);
5785
5915
  const next = [];
5786
5916
  for (const f of distinctFields) {
5787
- next.push((_a3 = firstByField.get(f)) != null ? _a3 : { [f]: "asc" });
5917
+ next.push((_a4 = firstByField.get(f)) != null ? _a4 : { [f]: "asc" });
5788
5918
  }
5789
5919
  const distinctSet = new Set(distinctFields);
5790
5920
  for (const obj of existing) {
@@ -6824,10 +6954,10 @@ function isPrismaMethod(v) {
6824
6954
  return v === "findMany" || v === "findFirst" || v === "findUnique" || v === "aggregate" || v === "groupBy" || v === "count";
6825
6955
  }
6826
6956
  function resolveMethod(directive) {
6827
- var _a3, _b;
6957
+ var _a4, _b;
6828
6958
  const m = directive == null ? void 0 : directive.method;
6829
6959
  if (isPrismaMethod(m)) return m;
6830
- const pm = (_b = (_a3 = directive == null ? void 0 : directive.query) == null ? void 0 : _a3.processed) == null ? void 0 : _b.method;
6960
+ const pm = (_b = (_a4 = directive == null ? void 0 : directive.query) == null ? void 0 : _a4.processed) == null ? void 0 : _b.method;
6831
6961
  if (isPrismaMethod(pm)) return pm;
6832
6962
  return "findMany";
6833
6963
  }
@@ -6992,7 +7122,7 @@ function extractIncludeSpec2(processed, modelDef) {
6992
7122
  return includeSpec;
6993
7123
  }
6994
7124
  function buildAndNormalizeSql(args) {
6995
- var _a3;
7125
+ var _a4;
6996
7126
  const {
6997
7127
  method,
6998
7128
  processed,
@@ -7018,7 +7148,7 @@ function buildAndNormalizeSql(args) {
7018
7148
  sqlResult.paramMappings,
7019
7149
  dialect
7020
7150
  );
7021
- const includeSpec = (_a3 = sqlResult.includeSpec && isPlainObject(sqlResult.includeSpec) ? sqlResult.includeSpec : null) != null ? _a3 : extractIncludeSpec2(processed, modelDef);
7151
+ const includeSpec = (_a4 = sqlResult.includeSpec && isPlainObject(sqlResult.includeSpec) ? sqlResult.includeSpec : null) != null ? _a4 : extractIncludeSpec2(processed, modelDef);
7022
7152
  return {
7023
7153
  sql: normalized.sql,
7024
7154
  paramMappings: normalized.paramMappings,
@@ -7043,8 +7173,8 @@ function finalizeDirective(args) {
7043
7173
  skipWhereIn
7044
7174
  } = args;
7045
7175
  const params = normalizedMappings.map((m) => {
7046
- var _a3;
7047
- return (_a3 = m.value) != null ? _a3 : void 0;
7176
+ var _a4;
7177
+ return (_a4 = m.value) != null ? _a4 : void 0;
7048
7178
  });
7049
7179
  validateParamConsistencyByDialect(normalizedSql, params, dialect);
7050
7180
  const { staticParams, dynamicKeys, paramOrder } = buildParamsFromMappings(normalizedMappings);
@@ -7514,21 +7644,13 @@ function makeAlias(name) {
7514
7644
  const safe = /^[a-z_]/.test(base) ? base : `_${base}`;
7515
7645
  return SQL_RESERVED_WORDS.has(safe) ? `${safe}_t` : safe;
7516
7646
  }
7517
- function canonicalizeReplacer(key, value) {
7647
+ function bigintReplacer(_key, value) {
7518
7648
  if (typeof value === "bigint") return `__bigint__${value.toString()}`;
7519
- if (value && typeof value === "object" && !Array.isArray(value)) {
7520
- const obj = value;
7521
- const sorted = {};
7522
- for (const k of Object.keys(obj).sort()) {
7523
- sorted[k] = obj[k];
7524
- }
7525
- return sorted;
7526
- }
7527
7649
  return value;
7528
7650
  }
7529
7651
  function canonicalizeQuery(modelName, method, args, dialect) {
7530
7652
  if (!args) return `${dialect}:${modelName}:${method}:{}`;
7531
- return `${dialect}:${modelName}:${method}:${JSON.stringify(args, canonicalizeReplacer)}`;
7653
+ return `${dialect}:${modelName}:${method}:${JSON.stringify(args, bigintReplacer)}`;
7532
7654
  }
7533
7655
  function buildSQLFull(model, models, method, args, dialect) {
7534
7656
  const tableName = buildTableReference(
@@ -7712,10 +7834,10 @@ function getRowTransformer(method) {
7712
7834
 
7713
7835
  // src/result-transformers.ts
7714
7836
  function transformQueryResults(method, results) {
7715
- var _a3, _b;
7837
+ var _a4, _b;
7716
7838
  if (method === "findFirst" || method === "findUnique") {
7717
7839
  if (Array.isArray(results)) {
7718
- return (_a3 = results[0]) != null ? _a3 : null;
7840
+ return (_a4 = results[0]) != null ? _a4 : null;
7719
7841
  }
7720
7842
  }
7721
7843
  if (method === "aggregate") {
@@ -7824,10 +7946,10 @@ function createTransactionExecutor(deps) {
7824
7946
  function isListField2(field) {
7825
7947
  return typeof field.type === "string" && field.type.endsWith("[]");
7826
7948
  }
7827
- function resolveRelation(model, relName, allModels) {
7949
+ function resolveRelation(model, relName, allModels, modelMap) {
7828
7950
  const field = model.fields.find((f) => f.name === relName);
7829
7951
  if (!field || !field.isRelation || !field.relatedModel) return null;
7830
- const relModel = allModels.find((m) => m.name === field.relatedModel);
7952
+ const relModel = modelMap ? modelMap.get(field.relatedModel) : allModels.find((m) => m.name === field.relatedModel);
7831
7953
  if (!relModel) return null;
7832
7954
  return { field, relModel };
7833
7955
  }
@@ -7859,23 +7981,11 @@ function buildWhereInSegment(name, relArgs, field, relModel) {
7859
7981
  perParentSkip: pagination.skip
7860
7982
  };
7861
7983
  }
7862
- function deepClone(obj) {
7863
- if (obj === null || typeof obj !== "object") return obj;
7864
- if (obj instanceof Date) return new Date(obj.getTime());
7865
- if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags);
7866
- if (Array.isArray(obj)) return obj.map((item) => deepClone(item));
7867
- const cloned = {};
7868
- for (const key in obj) {
7869
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
7870
- cloned[key] = deepClone(obj[key]);
7871
- }
7872
- }
7873
- return cloned;
7874
- }
7875
7984
  function removeRelationsFromArgs(args, names) {
7876
7985
  if (!args) return args;
7877
- const filtered = deepClone(args);
7986
+ const filtered = __spreadValues({}, args);
7878
7987
  if (filtered.include && isPlainObject(filtered.include)) {
7988
+ filtered.include = __spreadValues({}, filtered.include);
7879
7989
  for (const name of names) {
7880
7990
  delete filtered.include[name];
7881
7991
  }
@@ -7884,6 +7994,7 @@ function removeRelationsFromArgs(args, names) {
7884
7994
  }
7885
7995
  }
7886
7996
  if (filtered.select && isPlainObject(filtered.select)) {
7997
+ filtered.select = __spreadValues({}, filtered.select);
7887
7998
  for (const name of names) {
7888
7999
  delete filtered.select[name];
7889
8000
  }
@@ -7928,23 +8039,40 @@ function planQueryStrategy(params) {
7928
8039
  if (dialect === "postgres") {
7929
8040
  const includeSpec = extractIncludeSpec3(args, model);
7930
8041
  if (Object.keys(includeSpec).length > 0) {
8042
+ const modelMap2 = getOrCreateModelMap(allModels);
7931
8043
  isPlainObject(args) && "take" in args && args.take != null;
7932
8044
  const takeValue = isPlainObject(args) && typeof args.take === "number" ? args.take : null;
7933
- const canFlatJoin = canUseFlatJoinForAll(includeSpec, model, allModels);
7934
- canUseLateralJoin(includeSpec, model, allModels);
7935
- hasChildPaginationAnywhere(
8045
+ const canFlatJoin = canUseFlatJoinForAll(
8046
+ includeSpec,
8047
+ model,
8048
+ allModels,
8049
+ false,
8050
+ modelMap2
8051
+ );
8052
+ canUseLateralJoin(
7936
8053
  includeSpec,
7937
8054
  model,
7938
- allModels
8055
+ allModels,
8056
+ modelMap2
8057
+ );
8058
+ const hasChildPag = hasChildPaginationAnywhere(
8059
+ includeSpec,
8060
+ model,
8061
+ allModels,
8062
+ 0,
8063
+ modelMap2
7939
8064
  );
7940
8065
  const strategy = pickIncludeStrategy({
7941
8066
  includeSpec,
7942
8067
  model,
7943
8068
  schemas: allModels,
7944
8069
  method: params.method,
8070
+ args,
7945
8071
  takeValue,
7946
8072
  canFlatJoin,
7947
- debug
8073
+ hasChildPagination: hasChildPag,
8074
+ debug,
8075
+ modelMap: modelMap2
7948
8076
  });
7949
8077
  if (debug) {
7950
8078
  console.log(` [planner] ${model.name}: strategy=${strategy}`);
@@ -7954,10 +8082,11 @@ function planQueryStrategy(params) {
7954
8082
  }
7955
8083
  }
7956
8084
  }
8085
+ const modelMap = getOrCreateModelMap(allModels);
7957
8086
  const whereInSegments = [];
7958
8087
  const toRemove = /* @__PURE__ */ new Set();
7959
8088
  for (const entry of entries) {
7960
- const resolved = resolveRelation(model, entry.name, allModels);
8089
+ const resolved = resolveRelation(model, entry.name, allModels, modelMap);
7961
8090
  if (!resolved) continue;
7962
8091
  const segment = buildWhereInSegment(
7963
8092
  entry.name,
@@ -8220,7 +8349,7 @@ function needsPerParentPagination(segment) {
8220
8349
  return segment.isList && (segment.perParentSkip != null && segment.perParentSkip > 0 || segment.perParentTake != null);
8221
8350
  }
8222
8351
  function stitchChildrenToParents(children, segment, parentKeyIndex) {
8223
- var _a3;
8352
+ var _a4;
8224
8353
  const grouped = /* @__PURE__ */ new Map();
8225
8354
  for (const child of children) {
8226
8355
  const childKey = child[segment.fkFieldName];
@@ -8251,20 +8380,28 @@ function stitchChildrenToParents(children, segment, parentKeyIndex) {
8251
8380
  parent[segment.relationName].push(child);
8252
8381
  }
8253
8382
  } else {
8254
- parent[segment.relationName] = (_a3 = sliced[0]) != null ? _a3 : null;
8383
+ parent[segment.relationName] = (_a4 = sliced[0]) != null ? _a4 : null;
8255
8384
  }
8256
8385
  }
8257
8386
  }
8258
8387
  }
8259
8388
  function buildChildArgs(relArgs, fkFieldName, uniqueIds, stripPagination) {
8260
- const base = relArgs === true || typeof relArgs !== "object" || relArgs === null ? {} : __spreadValues({}, relArgs);
8261
- if (stripPagination) {
8262
- delete base.take;
8263
- delete base.skip;
8389
+ const isObject = relArgs !== true && typeof relArgs === "object" && relArgs !== null;
8390
+ const source = isObject ? relArgs : null;
8391
+ const base = {};
8392
+ if (source) {
8393
+ if (source.select !== void 0) base.select = source.select;
8394
+ if (source.include !== void 0) base.include = source.include;
8395
+ if (source.orderBy !== void 0) base.orderBy = source.orderBy;
8396
+ if (!stripPagination) {
8397
+ if (source.take !== void 0) base.take = source.take;
8398
+ if (source.skip !== void 0) base.skip = source.skip;
8399
+ }
8400
+ if (source.cursor !== void 0) base.cursor = source.cursor;
8401
+ if (source.distinct !== void 0) base.distinct = source.distinct;
8264
8402
  }
8265
- const existingWhere = base.where;
8266
8403
  const inCondition = { [fkFieldName]: { in: uniqueIds } };
8267
- base.where = existingWhere ? { AND: [existingWhere, inCondition] } : inCondition;
8404
+ base.where = source && source.where ? { AND: [source.where, inCondition] } : inCondition;
8268
8405
  return base;
8269
8406
  }
8270
8407
  function ensureFkInSelect(childArgs, fkFieldName) {
@@ -8776,9 +8913,9 @@ function wrapQueryForMethod(method, cteName, resultAlias) {
8776
8913
  }
8777
8914
  }
8778
8915
  function isAllCountQueries(queries, keys) {
8779
- var _a3;
8916
+ var _a4;
8780
8917
  for (const key of keys) {
8781
- if (((_a3 = queries[key]) == null ? void 0 : _a3.method) !== "count") return false;
8918
+ if (((_a4 = queries[key]) == null ? void 0 : _a4.method) !== "count") return false;
8782
8919
  }
8783
8920
  return true;
8784
8921
  }
@@ -8921,8 +9058,8 @@ function buildMergedCountBatchSql(queries, keys, aliasesByKey, modelMap, models,
8921
9058
  const fromSql = rewrittenSubs.join(" CROSS JOIN ");
8922
9059
  const sql = `SELECT ${selectParts.join(", ")} FROM ${fromSql}`;
8923
9060
  const aliases = keys.map((k) => {
8924
- var _a3;
8925
- return (_a3 = aliasesByKey.get(k)) != null ? _a3 : "";
9061
+ var _a4;
9062
+ return (_a4 = aliasesByKey.get(k)) != null ? _a4 : "";
8926
9063
  });
8927
9064
  return { sql, params: finalParams, keys, aliases };
8928
9065
  }
@@ -9280,11 +9417,11 @@ function parseBatchValue(rawValue, method, modelName, modelMap) {
9280
9417
  }
9281
9418
  }
9282
9419
  function parseBatchResults(row, keys, queries, aliases, modelMap) {
9283
- var _a3;
9420
+ var _a4;
9284
9421
  const results = {};
9285
9422
  for (let i = 0; i < keys.length; i++) {
9286
9423
  const key = keys[i];
9287
- const columnKey = (_a3 = aliases == null ? void 0 : aliases[i]) != null ? _a3 : key;
9424
+ const columnKey = (_a4 = aliases == null ? void 0 : aliases[i]) != null ? _a4 : key;
9288
9425
  const rawValue = row[columnKey];
9289
9426
  const query = queries[key];
9290
9427
  results[key] = parseBatchValue(
@@ -9406,8 +9543,8 @@ var createCoreReducer = (config) => {
9406
9543
  return {
9407
9544
  processRow,
9408
9545
  getParent: (key) => {
9409
- var _a3;
9410
- return (_a3 = parentMap.get(key)) != null ? _a3 : null;
9546
+ var _a4;
9547
+ return (_a4 = parentMap.get(key)) != null ? _a4 : null;
9411
9548
  },
9412
9549
  getAllParents: () => Array.from(parentMap.values()),
9413
9550
  getParentMap: () => parentMap