prisma-sql 1.76.0 → 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) : {};
@@ -2302,7 +2315,7 @@ var CORRELATED_WHERE_PENALTY = 3;
2302
2315
  var DEFAULT_FAN = 10;
2303
2316
  var DEFAULT_PARENT_COUNT = 50;
2304
2317
  var MIN_STATS_COVERAGE = 0.1;
2305
- var SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH = 1;
2318
+ var SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH = 2;
2306
2319
  function setRoundtripRowEquivalent(value) {
2307
2320
  globalRoundtripRowEquivalent = value;
2308
2321
  }
@@ -2345,15 +2358,26 @@ function hasPaginationArgs(value) {
2345
2358
  const obj = value;
2346
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));
2347
2360
  }
2348
- function buildCostTree(includeSpec, model, schemas, depth = 0) {
2361
+ function buildCostTree(includeSpec, model, schemas, depth = 0, modelMap) {
2349
2362
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return [];
2350
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2363
+ const relations = resolveIncludeRelations(
2364
+ includeSpec,
2365
+ model,
2366
+ schemas,
2367
+ modelMap
2368
+ );
2351
2369
  const nodes = [];
2352
2370
  for (const rel of relations) {
2353
2371
  const fan = rel.isList ? getFanOut(model.name, rel.relName) : 1;
2354
2372
  const take = rel.isList ? readTake(rel.value) : 1;
2355
2373
  const eff = Math.min(fan, take);
2356
- 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
+ ) : [];
2357
2381
  nodes.push({
2358
2382
  name: rel.relName,
2359
2383
  fan,
@@ -2417,17 +2441,23 @@ function computeCorrelatedCost(nodes, parentCount) {
2417
2441
  return R + parentCount * subqueryCost(nodes);
2418
2442
  }
2419
2443
  function hasOnlyToOneRelations(includeSpec, model) {
2444
+ const indices = getFieldIndices(model);
2420
2445
  for (const [relName, value] of Object.entries(includeSpec)) {
2421
2446
  if (value === false) continue;
2422
- const field = model.fields.find((f) => f.name === relName);
2447
+ const field = indices.allFieldsByName.get(relName);
2423
2448
  if (!(field == null ? void 0 : field.isRelation)) continue;
2424
2449
  if (isListField(field)) return false;
2425
2450
  }
2426
2451
  return true;
2427
2452
  }
2428
- function countIncludeDepth(includeSpec, model, schemas, depth = 0) {
2453
+ function countIncludeDepth(includeSpec, model, schemas, depth = 0, modelMap) {
2429
2454
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return 0;
2430
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2455
+ const relations = resolveIncludeRelations(
2456
+ includeSpec,
2457
+ model,
2458
+ schemas,
2459
+ modelMap
2460
+ );
2431
2461
  let maxDepth = 0;
2432
2462
  for (const rel of relations) {
2433
2463
  let childDepth = 1;
@@ -2436,27 +2466,34 @@ function countIncludeDepth(includeSpec, model, schemas, depth = 0) {
2436
2466
  rel.nestedSpec,
2437
2467
  rel.relModel,
2438
2468
  schemas,
2439
- depth + 1
2469
+ depth + 1,
2470
+ modelMap
2440
2471
  );
2441
2472
  }
2442
2473
  if (childDepth > maxDepth) maxDepth = childDepth;
2443
2474
  }
2444
2475
  return maxDepth;
2445
2476
  }
2446
- function hasChildPaginationAnywhere(includeSpec, model, schemas, depth = 0) {
2477
+ function hasChildPaginationAnywhere(includeSpec, model, schemas, depth = 0, modelMap) {
2447
2478
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return false;
2448
2479
  for (const [, value] of Object.entries(includeSpec)) {
2449
2480
  if (value === false) continue;
2450
2481
  if (hasPaginationArgs(value)) return true;
2451
2482
  }
2452
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2483
+ const relations = resolveIncludeRelations(
2484
+ includeSpec,
2485
+ model,
2486
+ schemas,
2487
+ modelMap
2488
+ );
2453
2489
  for (const rel of relations) {
2454
2490
  if (Object.keys(rel.nestedSpec).length > 0) {
2455
2491
  if (hasChildPaginationAnywhere(
2456
2492
  rel.nestedSpec,
2457
2493
  rel.relModel,
2458
2494
  schemas,
2459
- depth + 1
2495
+ depth + 1,
2496
+ modelMap
2460
2497
  )) {
2461
2498
  return true;
2462
2499
  }
@@ -2473,7 +2510,8 @@ function pickIncludeStrategy(params) {
2473
2510
  takeValue,
2474
2511
  canFlatJoin,
2475
2512
  hasChildPagination,
2476
- debug
2513
+ debug,
2514
+ modelMap
2477
2515
  } = params;
2478
2516
  if (Object.keys(includeSpec).length === 0) return "where-in";
2479
2517
  if (canFlatJoin && hasOnlyToOneRelations(includeSpec, model)) {
@@ -2483,7 +2521,7 @@ function pickIncludeStrategy(params) {
2483
2521
  }
2484
2522
  const isSingleParent = method === "findFirst" || method === "findUnique";
2485
2523
  if (isSingleParent && canFlatJoin) {
2486
- const depth = countIncludeDepth(includeSpec, model, schemas);
2524
+ const depth = countIncludeDepth(includeSpec, model, schemas, 0, modelMap);
2487
2525
  if (depth <= SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH) {
2488
2526
  if (debug)
2489
2527
  console.log(
@@ -2492,7 +2530,7 @@ function pickIncludeStrategy(params) {
2492
2530
  return "flat-join";
2493
2531
  }
2494
2532
  }
2495
- const costTree = buildCostTree(includeSpec, model, schemas);
2533
+ const costTree = buildCostTree(includeSpec, model, schemas, 0, modelMap);
2496
2534
  const treeDepth = maxDepthFromTree(costTree);
2497
2535
  if (hasChildPagination && treeDepth >= 2) {
2498
2536
  if (debug)
@@ -2600,13 +2638,13 @@ function createAliasCounter() {
2600
2638
  }
2601
2639
  };
2602
2640
  }
2603
- function getRelationModel(parentModel, relationName, schemas) {
2641
+ function getRelationModel(parentModel, relationName, schemas, modelMap) {
2604
2642
  const indices = getFieldIndices(parentModel);
2605
2643
  const field = indices.allFieldsByName.get(relationName);
2606
2644
  if (!(field == null ? void 0 : field.isRelation) || !field.relatedModel) {
2607
2645
  throw new Error(`Invalid relation ${relationName} on ${parentModel.name}`);
2608
2646
  }
2609
- const relModel = schemas.find((m) => m.name === field.relatedModel);
2647
+ const relModel = modelMap ? modelMap.get(field.relatedModel) : schemas.find((m) => m.name === field.relatedModel);
2610
2648
  if (!relModel) {
2611
2649
  throw new Error(`Related model ${field.relatedModel} not found`);
2612
2650
  }
@@ -2643,8 +2681,13 @@ function countActiveEntries(spec) {
2643
2681
  }
2644
2682
  return count;
2645
2683
  }
2646
- function canUseFlatJoinForAll(includeSpec, model, schemas, debug) {
2647
- 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
+ );
2648
2691
  if (relations.length < countActiveEntries(includeSpec)) {
2649
2692
  return false;
2650
2693
  }
@@ -2666,14 +2709,20 @@ function canUseFlatJoinForAll(includeSpec, model, schemas, debug) {
2666
2709
  return false;
2667
2710
  }
2668
2711
  if (Object.keys(rel.nestedSpec).length > 0) {
2669
- if (!canUseFlatJoinForAll(rel.nestedSpec, rel.relModel, schemas)) {
2712
+ if (!canUseFlatJoinForAll(
2713
+ rel.nestedSpec,
2714
+ rel.relModel,
2715
+ schemas,
2716
+ debug,
2717
+ modelMap
2718
+ )) {
2670
2719
  return false;
2671
2720
  }
2672
2721
  }
2673
2722
  }
2674
2723
  return true;
2675
2724
  }
2676
- function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialect, prefix, aliasCounter, depth = 0) {
2725
+ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialect, prefix, aliasCounter, depth = 0, modelMap) {
2677
2726
  if (depth > LIMITS.MAX_NESTED_JOIN_DEPTH) {
2678
2727
  throw new Error(
2679
2728
  `Nested joins exceeded maximum depth of ${LIMITS.MAX_NESTED_JOIN_DEPTH} at prefix '${prefix}'`
@@ -2687,7 +2736,7 @@ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialec
2687
2736
  const indices = getFieldIndices(parentModel);
2688
2737
  const field = indices.allFieldsByName.get(relName);
2689
2738
  if (!isValidRelationField(field)) continue;
2690
- const relModel = getRelationModel(parentModel, relName, schemas);
2739
+ const relModel = getRelationModel(parentModel, relName, schemas, modelMap);
2691
2740
  const relTable = buildTableReference(
2692
2741
  SQL_TEMPLATES.PUBLIC_SCHEMA,
2693
2742
  relModel.tableName,
@@ -2728,7 +2777,8 @@ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialec
2728
2777
  dialect,
2729
2778
  nestedPrefix,
2730
2779
  aliasCounter,
2731
- depth + 1
2780
+ depth + 1,
2781
+ modelMap
2732
2782
  );
2733
2783
  joins.push(...deeper.joins);
2734
2784
  selects.push(...deeper.selects);
@@ -2784,6 +2834,8 @@ function buildFlatJoinSql(spec) {
2784
2834
  requiresReduction: false,
2785
2835
  includeSpec: {}
2786
2836
  };
2837
+ const modelMap = /* @__PURE__ */ new Map();
2838
+ for (const m of schemas) modelMap.set(m.name, m);
2787
2839
  const includeSpec = extractRelationEntries(args, model).reduce(
2788
2840
  (acc, { name, value }) => {
2789
2841
  acc[name] = value;
@@ -2794,7 +2846,7 @@ function buildFlatJoinSql(spec) {
2794
2846
  if (Object.keys(includeSpec).length === 0) {
2795
2847
  return emptyResult;
2796
2848
  }
2797
- if (!canUseFlatJoinForAll(includeSpec, model, schemas)) {
2849
+ if (!canUseFlatJoinForAll(includeSpec, model, schemas, false, modelMap)) {
2798
2850
  return emptyResult;
2799
2851
  }
2800
2852
  const { cleanWhere, params } = extractReferencedParams(
@@ -2830,7 +2882,8 @@ function buildFlatJoinSql(spec) {
2830
2882
  dialect,
2831
2883
  "",
2832
2884
  aliasCounter,
2833
- 0
2885
+ 0,
2886
+ modelMap
2834
2887
  );
2835
2888
  if (built.joins.length === 0) {
2836
2889
  return emptyResult;
@@ -3834,8 +3887,8 @@ function buildOperator(expr, op, val, ctx, mode, fieldType) {
3834
3887
  });
3835
3888
  }
3836
3889
  var MAX_PARAM_INDEX = Number.MAX_SAFE_INTEGER - 1e3;
3837
- var _a2;
3838
- 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";
3839
3892
  function assertSameLength(params, mappings) {
3840
3893
  if (params.length !== mappings.length) {
3841
3894
  throw new Error(
@@ -3895,7 +3948,7 @@ function validateMappings(mappings) {
3895
3948
  }
3896
3949
  }
3897
3950
  function validateState(params, mappings, index) {
3898
- if (IS_PRODUCTION2) {
3951
+ if (IS_PRODUCTION3) {
3899
3952
  assertSameLength(params, mappings);
3900
3953
  assertValidNextIndex(index);
3901
3954
  return;
@@ -3953,6 +4006,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3953
4006
  if (frozen) {
3954
4007
  params = params.slice();
3955
4008
  mappings = mappings.slice();
4009
+ dynamicNameToIndex = new Map(dynamicNameToIndex);
3956
4010
  frozen = false;
3957
4011
  }
3958
4012
  }
@@ -3969,6 +4023,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3969
4023
  const dn = validateDynamicName(dynamicName);
3970
4024
  const existing = dynamicNameToIndex.get(dn);
3971
4025
  if (existing !== void 0) return formatPosition(existing);
4026
+ ensureMutable();
3972
4027
  const position = index;
3973
4028
  dynamicNameToIndex.set(dn, position);
3974
4029
  return registerParam(void 0, { index: position, dynamicName: dn });
@@ -3999,7 +4054,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3999
4054
  index,
4000
4055
  params,
4001
4056
  mappings,
4002
- dynamicNameIndex: new Map(dynamicNameToIndex)
4057
+ dynamicNameIndex: dynamicNameToIndex
4003
4058
  };
4004
4059
  cachedSnapshot = snap;
4005
4060
  dirty = false;
@@ -4054,10 +4109,10 @@ function toPublicResult(clause, joins, params) {
4054
4109
 
4055
4110
  // src/builder/where.ts
4056
4111
  function buildWhereClause(where, options) {
4057
- var _a3, _b, _c, _d, _e;
4112
+ var _a4, _b, _c, _d, _e;
4058
4113
  assertSafeAlias(options.alias);
4059
4114
  const dialect = options.dialect || getGlobalDialect();
4060
- const params = (_a3 = options.params) != null ? _a3 : createParamStore(1, dialect);
4115
+ const params = (_a4 = options.params) != null ? _a4 : createParamStore(1, dialect);
4061
4116
  const ctx = {
4062
4117
  alias: options.alias,
4063
4118
  model: options.model,
@@ -4140,12 +4195,13 @@ function reindexWhereParams(whereClause, specParams, collector) {
4140
4195
  }
4141
4196
  return clean;
4142
4197
  }
4143
- function getRelationModel2(parentModel, relationName, schemas) {
4144
- var _a3;
4198
+ function getRelationModel2(parentModel, relationName, schemas, modelMap) {
4199
+ var _a4, _b;
4145
4200
  const indices = getFieldIndices(parentModel);
4146
4201
  const field = indices.allFieldsByName.get(relationName);
4147
4202
  if (!(field == null ? void 0 : field.isRelation) || !field.relatedModel) return null;
4148
- 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;
4149
4205
  }
4150
4206
  function extractOrderByInput(relArgs) {
4151
4207
  if (!isPlainObject(relArgs)) return void 0;
@@ -4190,7 +4246,12 @@ function buildLateralForRelation(relationName, relArgs, field, relModel, parentM
4190
4246
  const nestedIndices = getFieldIndices(relModel);
4191
4247
  const nestedField = nestedIndices.allFieldsByName.get(nestedName);
4192
4248
  if (!nestedField || !isValidRelationField(nestedField)) continue;
4193
- const nestedModel = getRelationModel2(relModel, nestedName, ctx.schemas);
4249
+ const nestedModel = getRelationModel2(
4250
+ relModel,
4251
+ nestedName,
4252
+ ctx.schemas,
4253
+ ctx.modelMap
4254
+ );
4194
4255
  if (!nestedModel) continue;
4195
4256
  const nested = buildLateralForRelation(
4196
4257
  nestedName,
@@ -4293,12 +4354,12 @@ function buildLateralForRelation(relationName, relArgs, field, relModel, parentM
4293
4354
  }
4294
4355
  const joinSql = `LEFT JOIN LATERAL (${outerSql}) ${latAlias} ON true`;
4295
4356
  const fieldTypes = selectedFields.map((fieldName) => {
4296
- var _a3;
4357
+ var _a4;
4297
4358
  const f = indices.scalarFields.get(fieldName);
4298
4359
  if (!f) return null;
4299
4360
  return {
4300
4361
  fieldName: f.name,
4301
- type: String((_a3 = f.type) != null ? _a3 : "").toLowerCase()
4362
+ type: String((_a4 = f.type) != null ? _a4 : "").toLowerCase()
4302
4363
  };
4303
4364
  }).filter(Boolean);
4304
4365
  const meta = {
@@ -4316,8 +4377,13 @@ function countActiveEntries2(spec) {
4316
4377
  }
4317
4378
  return count;
4318
4379
  }
4319
- function canUseLateralJoin(includeSpec, parentModel, schemas) {
4320
- 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
+ );
4321
4387
  if (relations.length < countActiveEntries2(includeSpec)) {
4322
4388
  return false;
4323
4389
  }
@@ -4326,14 +4392,14 @@ function canUseLateralJoin(includeSpec, parentModel, schemas) {
4326
4392
  if (!keys || keys.childKeys.length === 0 || keys.parentKeys.length === 0)
4327
4393
  return false;
4328
4394
  if (Object.keys(rel.nestedSpec).length > 0) {
4329
- if (!canUseLateralJoin(rel.nestedSpec, rel.relModel, schemas))
4395
+ if (!canUseLateralJoin(rel.nestedSpec, rel.relModel, schemas, modelMap))
4330
4396
  return false;
4331
4397
  }
4332
4398
  }
4333
4399
  return true;
4334
4400
  }
4335
4401
  function buildLateralJoinSql(spec) {
4336
- var _a3;
4402
+ var _a4;
4337
4403
  const {
4338
4404
  from,
4339
4405
  whereClause,
@@ -4353,6 +4419,8 @@ function buildLateralJoinSql(spec) {
4353
4419
  isLateral: false,
4354
4420
  lateralMeta: []
4355
4421
  };
4422
+ const modelMap = /* @__PURE__ */ new Map();
4423
+ for (const m of schemas) modelMap.set(m.name, m);
4356
4424
  const entries = extractRelationEntries(args, model);
4357
4425
  const includeSpec = {};
4358
4426
  for (const e of entries) {
@@ -4379,7 +4447,8 @@ function buildLateralJoinSql(spec) {
4379
4447
  schemas,
4380
4448
  dialect,
4381
4449
  aliasCounter,
4382
- collector
4450
+ collector,
4451
+ modelMap
4383
4452
  };
4384
4453
  const lateralJoins = [];
4385
4454
  const lateralSelects = [];
@@ -4389,7 +4458,7 @@ function buildLateralJoinSql(spec) {
4389
4458
  const indices = getFieldIndices(model);
4390
4459
  const field = indices.allFieldsByName.get(relName);
4391
4460
  if (!field || !isValidRelationField(field)) continue;
4392
- const relModel = getRelationModel2(model, relName, schemas);
4461
+ const relModel = getRelationModel2(model, relName, schemas, modelMap);
4393
4462
  if (!relModel) continue;
4394
4463
  const result = buildLateralForRelation(
4395
4464
  relName,
@@ -4407,7 +4476,7 @@ function buildLateralJoinSql(spec) {
4407
4476
  lateralMeta.push(result.meta);
4408
4477
  }
4409
4478
  if (lateralJoins.length === 0) return emptyResult;
4410
- const baseSelect = ((_a3 = spec.select) != null ? _a3 : "").trim();
4479
+ const baseSelect = ((_a4 = spec.select) != null ? _a4 : "").trim();
4411
4480
  const allSelects = [baseSelect, ...lateralSelects].filter((s) => s && s.trim().length > 0).join(", ");
4412
4481
  if (!allSelects) {
4413
4482
  return emptyResult;
@@ -4527,9 +4596,9 @@ function renderOrderBySimple(entries, alias) {
4527
4596
  return out.join(SQL_SEPARATORS.ORDER_BY);
4528
4597
  }
4529
4598
  function ensureIdTiebreakerEntries(entries, model) {
4530
- var _a3, _b;
4531
- const idField = (_b = (_a3 = model == null ? void 0 : model.fields) == null ? void 0 : _a3.find) == null ? void 0 : _b.call(
4532
- _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,
4533
4602
  (f) => f.name === DEFAULT_PRIMARY_KEY2 && !f.isRelation
4534
4603
  );
4535
4604
  if (!idField) return entries;
@@ -4571,14 +4640,14 @@ function buildJoinsSql(...joinGroups) {
4571
4640
  return all.length > 0 ? " " + all.join(" ") : "";
4572
4641
  }
4573
4642
  function buildSqliteDistinctQuery(spec, selectWithIncludes, countJoins) {
4574
- var _a3, _b;
4643
+ var _a4, _b;
4575
4644
  const { includes, from, whereClause, whereJoins, distinct, model } = spec;
4576
4645
  if (!isNotNullish(distinct) || !isNonEmptyArray(distinct)) {
4577
4646
  throw new Error("buildSqliteDistinctQuery requires distinct fields");
4578
4647
  }
4579
4648
  const scalarNames = parseSimpleScalarSelect(spec.select, from.alias);
4580
4649
  const includeNames = includes.map((i) => i.name);
4581
- 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]);
4582
4651
  const outerSelectCols = buildOutputColumns(
4583
4652
  scalarNames,
4584
4653
  includeNames,
@@ -4678,12 +4747,12 @@ function resolveCountSelect(countSelectRaw, model) {
4678
4747
  return null;
4679
4748
  }
4680
4749
  function buildIncludeColumns(spec) {
4681
- var _a3, _b, _c, _d, _e;
4750
+ var _a4, _b, _c, _d, _e;
4682
4751
  const { select, includes, dialect, model, schemas, from, params } = spec;
4683
4752
  const baseSelect = (select != null ? select : "").trim();
4684
4753
  let countCols = "";
4685
4754
  let countJoins = [];
4686
- 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];
4687
4756
  if (countSelectRaw) {
4688
4757
  const resolvedCountSelect = resolveCountSelect(countSelectRaw, model);
4689
4758
  if (resolvedCountSelect && Object.keys(resolvedCountSelect).length > 0) {
@@ -4865,9 +4934,22 @@ function constructFinalSql(spec) {
4865
4934
  isNotNullish(pagination.take);
4866
4935
  const takeValue = typeof pagination.take === "number" ? pagination.take : null;
4867
4936
  if (dialect === "postgres" && hasIncludes) {
4868
- const canFlatJoin = canUseFlatJoinForAll(includeSpec, model, schemas);
4869
- canUseLateralJoin(includeSpec, model, schemas);
4870
- const hasChildPag = 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
+ );
4871
4953
  const strategy = pickIncludeStrategy({
4872
4954
  includeSpec,
4873
4955
  model,
@@ -4876,7 +4958,8 @@ function constructFinalSql(spec) {
4876
4958
  args,
4877
4959
  takeValue,
4878
4960
  canFlatJoin,
4879
- hasChildPagination: hasChildPag
4961
+ hasChildPagination: hasChildPag,
4962
+ modelMap
4880
4963
  });
4881
4964
  if (strategy === "flat-join") {
4882
4965
  const flatResult = buildFlatJoinSql(spec);
@@ -5000,8 +5083,8 @@ function buildDefaultScalarFields(model, alias) {
5000
5083
  return out;
5001
5084
  }
5002
5085
  function getDefaultSelectCached(model, alias) {
5003
- var _a3;
5004
- 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);
5005
5088
  }
5006
5089
  function cacheDefaultSelect(model, alias, sql) {
5007
5090
  let cache = DEFAULT_SELECT_CACHE.get(model);
@@ -5283,7 +5366,8 @@ function buildSelectWithNestedIncludes(relArgs, relModel, relAlias, ctx) {
5283
5366
  ctx.schemas,
5284
5367
  relAlias,
5285
5368
  ctx.params,
5286
- ctx.dialect
5369
+ ctx.dialect,
5370
+ ctx.schemaByName
5287
5371
  );
5288
5372
  if (!countBuild.jsonPairs) return baseSelect2;
5289
5373
  countJoins.push(...countBuild.joins);
@@ -5671,7 +5755,9 @@ function resolveTableRef(model, dialect) {
5671
5755
  return buildTableReference(schema, tableName, dialect);
5672
5756
  }
5673
5757
  function findRelationField(model, fieldName) {
5674
- 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;
5675
5761
  }
5676
5762
  function nextJoinAlias(ctx) {
5677
5763
  let alias;
@@ -5698,7 +5784,7 @@ function resolveRelationOrderByChain(relationFieldName, value, currentModel, cur
5698
5784
  `Relation field '${relationFieldName}' not found on model ${currentModel.name}`
5699
5785
  );
5700
5786
  }
5701
- const relatedModel = getModelByName(ctx.schemas, field.relatedModel);
5787
+ const relatedModel = ctx.modelMap.get(field.relatedModel);
5702
5788
  if (!relatedModel) {
5703
5789
  throw new Error(
5704
5790
  `Related model '${field.relatedModel}' not found for relation '${relationFieldName}'`
@@ -5764,12 +5850,14 @@ function buildOrderByWithRelations(orderBy, alias, dialect, model, schemas) {
5764
5850
  const relationSet = getRelationFieldSet(model);
5765
5851
  const scalarSet = getScalarFieldSet(model);
5766
5852
  const orderFragments = [];
5853
+ const modelMap = /* @__PURE__ */ new Map();
5854
+ for (const m of schemas) modelMap.set(m.name, m);
5767
5855
  const ctx = {
5768
- schemas,
5769
5856
  dialect,
5770
5857
  joins: [],
5771
5858
  usedAliases: /* @__PURE__ */ new Set(),
5772
- aliasCounter: { value: 0 }
5859
+ aliasCounter: { value: 0 },
5860
+ modelMap
5773
5861
  };
5774
5862
  for (const [fieldName, value] of expanded) {
5775
5863
  if (scalarSet.has(fieldName)) {
@@ -5824,11 +5912,11 @@ function mapFirstOrderByByField(existing) {
5824
5912
  return m;
5825
5913
  }
5826
5914
  function buildPostgresDistinctOrderBy(distinctFields, existing) {
5827
- var _a3;
5915
+ var _a4;
5828
5916
  const firstByField = mapFirstOrderByByField(existing);
5829
5917
  const next = [];
5830
5918
  for (const f of distinctFields) {
5831
- next.push((_a3 = firstByField.get(f)) != null ? _a3 : { [f]: "asc" });
5919
+ next.push((_a4 = firstByField.get(f)) != null ? _a4 : { [f]: "asc" });
5832
5920
  }
5833
5921
  const distinctSet = new Set(distinctFields);
5834
5922
  for (const obj of existing) {
@@ -6868,10 +6956,10 @@ function isPrismaMethod(v) {
6868
6956
  return v === "findMany" || v === "findFirst" || v === "findUnique" || v === "aggregate" || v === "groupBy" || v === "count";
6869
6957
  }
6870
6958
  function resolveMethod(directive) {
6871
- var _a3, _b;
6959
+ var _a4, _b;
6872
6960
  const m = directive == null ? void 0 : directive.method;
6873
6961
  if (isPrismaMethod(m)) return m;
6874
- 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;
6875
6963
  if (isPrismaMethod(pm)) return pm;
6876
6964
  return "findMany";
6877
6965
  }
@@ -7036,7 +7124,7 @@ function extractIncludeSpec2(processed, modelDef) {
7036
7124
  return includeSpec;
7037
7125
  }
7038
7126
  function buildAndNormalizeSql(args) {
7039
- var _a3;
7127
+ var _a4;
7040
7128
  const {
7041
7129
  method,
7042
7130
  processed,
@@ -7062,7 +7150,7 @@ function buildAndNormalizeSql(args) {
7062
7150
  sqlResult.paramMappings,
7063
7151
  dialect
7064
7152
  );
7065
- 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);
7066
7154
  return {
7067
7155
  sql: normalized.sql,
7068
7156
  paramMappings: normalized.paramMappings,
@@ -7087,8 +7175,8 @@ function finalizeDirective(args) {
7087
7175
  skipWhereIn
7088
7176
  } = args;
7089
7177
  const params = normalizedMappings.map((m) => {
7090
- var _a3;
7091
- return (_a3 = m.value) != null ? _a3 : void 0;
7178
+ var _a4;
7179
+ return (_a4 = m.value) != null ? _a4 : void 0;
7092
7180
  });
7093
7181
  validateParamConsistencyByDialect(normalizedSql, params, dialect);
7094
7182
  const { staticParams, dynamicKeys, paramOrder } = buildParamsFromMappings(normalizedMappings);
@@ -7558,21 +7646,13 @@ function makeAlias(name) {
7558
7646
  const safe = /^[a-z_]/.test(base) ? base : `_${base}`;
7559
7647
  return SQL_RESERVED_WORDS.has(safe) ? `${safe}_t` : safe;
7560
7648
  }
7561
- function canonicalizeReplacer(key, value) {
7649
+ function bigintReplacer(_key, value) {
7562
7650
  if (typeof value === "bigint") return `__bigint__${value.toString()}`;
7563
- if (value && typeof value === "object" && !Array.isArray(value)) {
7564
- const obj = value;
7565
- const sorted = {};
7566
- for (const k of Object.keys(obj).sort()) {
7567
- sorted[k] = obj[k];
7568
- }
7569
- return sorted;
7570
- }
7571
7651
  return value;
7572
7652
  }
7573
7653
  function canonicalizeQuery(modelName, method, args, dialect) {
7574
7654
  if (!args) return `${dialect}:${modelName}:${method}:{}`;
7575
- return `${dialect}:${modelName}:${method}:${JSON.stringify(args, canonicalizeReplacer)}`;
7655
+ return `${dialect}:${modelName}:${method}:${JSON.stringify(args, bigintReplacer)}`;
7576
7656
  }
7577
7657
  function buildSQLFull(model, models, method, args, dialect) {
7578
7658
  const tableName = buildTableReference(
@@ -7756,10 +7836,10 @@ function getRowTransformer(method) {
7756
7836
 
7757
7837
  // src/result-transformers.ts
7758
7838
  function transformQueryResults(method, results) {
7759
- var _a3, _b;
7839
+ var _a4, _b;
7760
7840
  if (method === "findFirst" || method === "findUnique") {
7761
7841
  if (Array.isArray(results)) {
7762
- return (_a3 = results[0]) != null ? _a3 : null;
7842
+ return (_a4 = results[0]) != null ? _a4 : null;
7763
7843
  }
7764
7844
  }
7765
7845
  if (method === "aggregate") {
@@ -7868,10 +7948,10 @@ function createTransactionExecutor(deps) {
7868
7948
  function isListField2(field) {
7869
7949
  return typeof field.type === "string" && field.type.endsWith("[]");
7870
7950
  }
7871
- function resolveRelation(model, relName, allModels) {
7951
+ function resolveRelation(model, relName, allModels, modelMap) {
7872
7952
  const field = model.fields.find((f) => f.name === relName);
7873
7953
  if (!field || !field.isRelation || !field.relatedModel) return null;
7874
- const relModel = allModels.find((m) => m.name === field.relatedModel);
7954
+ const relModel = modelMap ? modelMap.get(field.relatedModel) : allModels.find((m) => m.name === field.relatedModel);
7875
7955
  if (!relModel) return null;
7876
7956
  return { field, relModel };
7877
7957
  }
@@ -7903,23 +7983,11 @@ function buildWhereInSegment(name, relArgs, field, relModel) {
7903
7983
  perParentSkip: pagination.skip
7904
7984
  };
7905
7985
  }
7906
- function deepClone(obj) {
7907
- if (obj === null || typeof obj !== "object") return obj;
7908
- if (obj instanceof Date) return new Date(obj.getTime());
7909
- if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags);
7910
- if (Array.isArray(obj)) return obj.map((item) => deepClone(item));
7911
- const cloned = {};
7912
- for (const key in obj) {
7913
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
7914
- cloned[key] = deepClone(obj[key]);
7915
- }
7916
- }
7917
- return cloned;
7918
- }
7919
7986
  function removeRelationsFromArgs(args, names) {
7920
7987
  if (!args) return args;
7921
- const filtered = deepClone(args);
7988
+ const filtered = __spreadValues({}, args);
7922
7989
  if (filtered.include && isPlainObject(filtered.include)) {
7990
+ filtered.include = __spreadValues({}, filtered.include);
7923
7991
  for (const name of names) {
7924
7992
  delete filtered.include[name];
7925
7993
  }
@@ -7928,6 +7996,7 @@ function removeRelationsFromArgs(args, names) {
7928
7996
  }
7929
7997
  }
7930
7998
  if (filtered.select && isPlainObject(filtered.select)) {
7999
+ filtered.select = __spreadValues({}, filtered.select);
7931
8000
  for (const name of names) {
7932
8001
  delete filtered.select[name];
7933
8002
  }
@@ -7972,14 +8041,28 @@ function planQueryStrategy(params) {
7972
8041
  if (dialect === "postgres") {
7973
8042
  const includeSpec = extractIncludeSpec3(args, model);
7974
8043
  if (Object.keys(includeSpec).length > 0) {
8044
+ const modelMap2 = getOrCreateModelMap(allModels);
7975
8045
  isPlainObject(args) && "take" in args && args.take != null;
7976
8046
  const takeValue = isPlainObject(args) && typeof args.take === "number" ? args.take : null;
7977
- const canFlatJoin = canUseFlatJoinForAll(includeSpec, model, allModels);
7978
- canUseLateralJoin(includeSpec, model, allModels);
8047
+ const canFlatJoin = canUseFlatJoinForAll(
8048
+ includeSpec,
8049
+ model,
8050
+ allModels,
8051
+ false,
8052
+ modelMap2
8053
+ );
8054
+ canUseLateralJoin(
8055
+ includeSpec,
8056
+ model,
8057
+ allModels,
8058
+ modelMap2
8059
+ );
7979
8060
  const hasChildPag = hasChildPaginationAnywhere(
7980
8061
  includeSpec,
7981
8062
  model,
7982
- allModels
8063
+ allModels,
8064
+ 0,
8065
+ modelMap2
7983
8066
  );
7984
8067
  const strategy = pickIncludeStrategy({
7985
8068
  includeSpec,
@@ -7990,7 +8073,8 @@ function planQueryStrategy(params) {
7990
8073
  takeValue,
7991
8074
  canFlatJoin,
7992
8075
  hasChildPagination: hasChildPag,
7993
- debug
8076
+ debug,
8077
+ modelMap: modelMap2
7994
8078
  });
7995
8079
  if (debug) {
7996
8080
  console.log(` [planner] ${model.name}: strategy=${strategy}`);
@@ -8000,10 +8084,11 @@ function planQueryStrategy(params) {
8000
8084
  }
8001
8085
  }
8002
8086
  }
8087
+ const modelMap = getOrCreateModelMap(allModels);
8003
8088
  const whereInSegments = [];
8004
8089
  const toRemove = /* @__PURE__ */ new Set();
8005
8090
  for (const entry of entries) {
8006
- const resolved = resolveRelation(model, entry.name, allModels);
8091
+ const resolved = resolveRelation(model, entry.name, allModels, modelMap);
8007
8092
  if (!resolved) continue;
8008
8093
  const segment = buildWhereInSegment(
8009
8094
  entry.name,
@@ -8266,7 +8351,7 @@ function needsPerParentPagination(segment) {
8266
8351
  return segment.isList && (segment.perParentSkip != null && segment.perParentSkip > 0 || segment.perParentTake != null);
8267
8352
  }
8268
8353
  function stitchChildrenToParents(children, segment, parentKeyIndex) {
8269
- var _a3;
8354
+ var _a4;
8270
8355
  const grouped = /* @__PURE__ */ new Map();
8271
8356
  for (const child of children) {
8272
8357
  const childKey = child[segment.fkFieldName];
@@ -8297,20 +8382,28 @@ function stitchChildrenToParents(children, segment, parentKeyIndex) {
8297
8382
  parent[segment.relationName].push(child);
8298
8383
  }
8299
8384
  } else {
8300
- parent[segment.relationName] = (_a3 = sliced[0]) != null ? _a3 : null;
8385
+ parent[segment.relationName] = (_a4 = sliced[0]) != null ? _a4 : null;
8301
8386
  }
8302
8387
  }
8303
8388
  }
8304
8389
  }
8305
8390
  function buildChildArgs(relArgs, fkFieldName, uniqueIds, stripPagination) {
8306
- const base = relArgs === true || typeof relArgs !== "object" || relArgs === null ? {} : __spreadValues({}, relArgs);
8307
- if (stripPagination) {
8308
- delete base.take;
8309
- 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;
8310
8404
  }
8311
- const existingWhere = base.where;
8312
8405
  const inCondition = { [fkFieldName]: { in: uniqueIds } };
8313
- base.where = existingWhere ? { AND: [existingWhere, inCondition] } : inCondition;
8406
+ base.where = source && source.where ? { AND: [source.where, inCondition] } : inCondition;
8314
8407
  return base;
8315
8408
  }
8316
8409
  function ensureFkInSelect(childArgs, fkFieldName) {
@@ -8822,9 +8915,9 @@ function wrapQueryForMethod(method, cteName, resultAlias) {
8822
8915
  }
8823
8916
  }
8824
8917
  function isAllCountQueries(queries, keys) {
8825
- var _a3;
8918
+ var _a4;
8826
8919
  for (const key of keys) {
8827
- 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;
8828
8921
  }
8829
8922
  return true;
8830
8923
  }
@@ -8967,8 +9060,8 @@ function buildMergedCountBatchSql(queries, keys, aliasesByKey, modelMap, models,
8967
9060
  const fromSql = rewrittenSubs.join(" CROSS JOIN ");
8968
9061
  const sql = `SELECT ${selectParts.join(", ")} FROM ${fromSql}`;
8969
9062
  const aliases = keys.map((k) => {
8970
- var _a3;
8971
- return (_a3 = aliasesByKey.get(k)) != null ? _a3 : "";
9063
+ var _a4;
9064
+ return (_a4 = aliasesByKey.get(k)) != null ? _a4 : "";
8972
9065
  });
8973
9066
  return { sql, params: finalParams, keys, aliases };
8974
9067
  }
@@ -9326,11 +9419,11 @@ function parseBatchValue(rawValue, method, modelName, modelMap) {
9326
9419
  }
9327
9420
  }
9328
9421
  function parseBatchResults(row, keys, queries, aliases, modelMap) {
9329
- var _a3;
9422
+ var _a4;
9330
9423
  const results = {};
9331
9424
  for (let i = 0; i < keys.length; i++) {
9332
9425
  const key = keys[i];
9333
- 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;
9334
9427
  const rawValue = row[columnKey];
9335
9428
  const query = queries[key];
9336
9429
  results[key] = parseBatchValue(
@@ -9452,8 +9545,8 @@ var createCoreReducer = (config) => {
9452
9545
  return {
9453
9546
  processRow,
9454
9547
  getParent: (key) => {
9455
- var _a3;
9456
- return (_a3 = parentMap.get(key)) != null ? _a3 : null;
9548
+ var _a4;
9549
+ return (_a4 = parentMap.get(key)) != null ? _a4 : null;
9457
9550
  },
9458
9551
  getAllParents: () => Array.from(parentMap.values()),
9459
9552
  getParentMap: () => parentMap