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