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.js CHANGED
@@ -386,9 +386,6 @@ var SQL_KEYWORDS = /* @__PURE__ */ new Set([
386
386
  ]);
387
387
  var SQL_RESERVED_WORDS = SQL_KEYWORDS;
388
388
  var DEFAULT_WHERE_CLAUSE = "1=1";
389
- var SPECIAL_FIELDS = Object.freeze({
390
- ID: "id"
391
- });
392
389
  var SQL_TEMPLATES = Object.freeze({
393
390
  PUBLIC_SCHEMA: "public",
394
391
  WHERE: "WHERE",
@@ -524,29 +521,6 @@ function hasRequiredKeywords(sql) {
524
521
  return hasSelect && hasFrom && upper.indexOf("SELECT") < upper.indexOf("FROM");
525
522
  }
526
523
 
527
- // src/builder/shared/errors.ts
528
- var SqlBuilderError = class extends Error {
529
- constructor(message, code, context) {
530
- super(message);
531
- this.name = "SqlBuilderError";
532
- this.code = code;
533
- this.context = context;
534
- }
535
- };
536
- function createError(message, ctx, code = "VALIDATION_ERROR") {
537
- const parts = [message];
538
- if (isNonEmptyArray(ctx.path)) {
539
- parts.push(`Path: ${ctx.path.join(".")}`);
540
- }
541
- if (isNotNullish(ctx.modelName)) {
542
- parts.push(`Model: ${ctx.modelName}`);
543
- }
544
- if (isNonEmptyArray(ctx.availableFields)) {
545
- parts.push(`Available fields: ${ctx.availableFields.join(", ")}`);
546
- }
547
- return new SqlBuilderError(parts.join("\n"), code, ctx);
548
- }
549
-
550
524
  // src/builder/shared/validators/sql-validators.ts
551
525
  function isValidWhereClause(clause) {
552
526
  return isNotNullish(clause) && clause.trim().length > 0 && clause !== DEFAULT_WHERE_CLAUSE;
@@ -689,8 +663,11 @@ function needsQuoting(identifier) {
689
663
  }
690
664
 
691
665
  // src/builder/shared/sql-utils.ts
666
+ var _a2;
667
+ var IS_PRODUCTION2 = typeof process !== "undefined" && ((_a2 = process.env) == null ? void 0 : _a2.NODE_ENV) === "production";
692
668
  var COL_EXPR_CACHE = /* @__PURE__ */ new WeakMap();
693
669
  var COL_WITH_ALIAS_CACHE = /* @__PURE__ */ new WeakMap();
670
+ var TABLE_REF_CACHE = /* @__PURE__ */ new Map();
694
671
  function containsControlChars(s) {
695
672
  for (let i = 0; i < s.length; i++) {
696
673
  const code = s.charCodeAt(i);
@@ -925,20 +902,33 @@ function buildTableReference(schemaName, tableName, dialect) {
925
902
  "buildTableReference: tableName is required and cannot be empty"
926
903
  );
927
904
  }
928
- if (containsControlChars(tableName)) {
929
- throw new Error(
930
- "buildTableReference: tableName contains invalid characters"
931
- );
932
- }
933
905
  const d = dialect != null ? dialect : "postgres";
934
906
  if (d === "sqlite") {
935
- return quote(tableName);
907
+ const cacheKey2 = `\0${tableName}\0sqlite`;
908
+ let cached2 = TABLE_REF_CACHE.get(cacheKey2);
909
+ if (cached2) return cached2;
910
+ if (containsControlChars(tableName)) {
911
+ throw new Error(
912
+ "buildTableReference: tableName contains invalid characters"
913
+ );
914
+ }
915
+ cached2 = quote(tableName);
916
+ TABLE_REF_CACHE.set(cacheKey2, cached2);
917
+ return cached2;
936
918
  }
937
919
  if (isEmptyString(schemaName)) {
938
920
  throw new Error(
939
921
  "buildTableReference: schemaName is required and cannot be empty"
940
922
  );
941
923
  }
924
+ const cacheKey = `${schemaName}\0${tableName}\0${d}`;
925
+ let cached = TABLE_REF_CACHE.get(cacheKey);
926
+ if (cached) return cached;
927
+ if (containsControlChars(tableName)) {
928
+ throw new Error(
929
+ "buildTableReference: tableName contains invalid characters"
930
+ );
931
+ }
942
932
  if (containsControlChars(schemaName)) {
943
933
  throw new Error(
944
934
  "buildTableReference: schemaName contains invalid characters"
@@ -946,9 +936,12 @@ function buildTableReference(schemaName, tableName, dialect) {
946
936
  }
947
937
  const safeSchema = schemaName.replace(/"/g, '""');
948
938
  const safeTable = tableName.replace(/"/g, '""');
949
- return `"${safeSchema}"."${safeTable}"`;
939
+ cached = `"${safeSchema}"."${safeTable}"`;
940
+ TABLE_REF_CACHE.set(cacheKey, cached);
941
+ return cached;
950
942
  }
951
943
  function assertSafeAlias(alias) {
944
+ if (IS_PRODUCTION2) return;
952
945
  if (typeof alias !== "string") {
953
946
  throw new Error(`Invalid alias: expected string, got ${typeof alias}`);
954
947
  }
@@ -993,6 +986,7 @@ function assertSafeAlias(alias) {
993
986
  }
994
987
  }
995
988
  function assertSafeTableRef(tableRef) {
989
+ if (IS_PRODUCTION2) return;
996
990
  assertSafeQualifiedName(tableRef);
997
991
  }
998
992
  function normalizeKeyList(input) {
@@ -1023,7 +1017,7 @@ function normalizeField(field) {
1023
1017
  return field;
1024
1018
  }
1025
1019
  function getFieldIndices(model) {
1026
- var _a3;
1020
+ var _a4;
1027
1021
  let cached = FIELD_INDICES_CACHE.get(model);
1028
1022
  if (cached) return cached;
1029
1023
  const scalarFields = /* @__PURE__ */ new Map();
@@ -1044,7 +1038,7 @@ function getFieldIndices(model) {
1044
1038
  } else {
1045
1039
  scalarFields.set(field.name, field);
1046
1040
  scalarNames.push(field.name);
1047
- const fieldType = String((_a3 = field.type) != null ? _a3 : "").toLowerCase();
1041
+ const fieldType = String((_a4 = field.type) != null ? _a4 : "").toLowerCase();
1048
1042
  if (fieldType === "json") {
1049
1043
  jsonFields.add(field.name);
1050
1044
  }
@@ -1058,12 +1052,16 @@ function getFieldIndices(model) {
1058
1052
  quotedColumns.set(field.name, quote(columnName));
1059
1053
  }
1060
1054
  }
1055
+ const scalarFieldSet = new Set(scalarNames);
1056
+ const relationFieldSet = new Set(relationNames);
1061
1057
  cached = Object.freeze({
1062
1058
  scalarFields,
1063
1059
  relationFields,
1064
1060
  allFieldsByName,
1065
1061
  scalarNames,
1066
1062
  relationNames,
1063
+ scalarFieldSet,
1064
+ relationFieldSet,
1067
1065
  jsonFields,
1068
1066
  pkFields,
1069
1067
  columnMap,
@@ -1073,10 +1071,10 @@ function getFieldIndices(model) {
1073
1071
  return cached;
1074
1072
  }
1075
1073
  function getRelationFieldSet(model) {
1076
- return new Set(getFieldIndices(model).relationNames);
1074
+ return getFieldIndices(model).relationFieldSet;
1077
1075
  }
1078
1076
  function getScalarFieldSet(model) {
1079
- return new Set(getFieldIndices(model).scalarNames);
1077
+ return getFieldIndices(model).scalarFieldSet;
1080
1078
  }
1081
1079
  function getColumnMap(model) {
1082
1080
  return getFieldIndices(model).columnMap;
@@ -1111,6 +1109,34 @@ function maybeParseJson(value, jsonSet, fieldName) {
1111
1109
  }
1112
1110
  }
1113
1111
 
1112
+ // src/builder/shared/relation-key-utils.ts
1113
+ var RELATION_KEYS_CACHE = /* @__PURE__ */ new WeakMap();
1114
+ function computeRelationKeys(field, context) {
1115
+ const fkFields = normalizeKeyList(field.foreignKey);
1116
+ if (fkFields.length === 0) {
1117
+ throw new Error(
1118
+ `Relation '${field.name}' is missing foreignKey for ${context}`
1119
+ );
1120
+ }
1121
+ const refs = normalizeKeyList(field.references);
1122
+ const refFields = refs.length > 0 ? refs : fkFields.length === 1 ? ["id"] : [];
1123
+ if (refFields.length !== fkFields.length) {
1124
+ throw new Error(
1125
+ `Relation '${field.name}' references count (${refFields.length}) doesn't match foreignKey count (${fkFields.length}) (context: ${context})`
1126
+ );
1127
+ }
1128
+ const childKeys = field.isForeignKeyLocal ? refFields : fkFields;
1129
+ const parentKeys = field.isForeignKeyLocal ? fkFields : refFields;
1130
+ return { childKeys, parentKeys };
1131
+ }
1132
+ function resolveRelationKeys(field, context = "include") {
1133
+ let cached = RELATION_KEYS_CACHE.get(field);
1134
+ if (cached) return cached;
1135
+ cached = computeRelationKeys(field, context);
1136
+ RELATION_KEYS_CACHE.set(field, cached);
1137
+ return cached;
1138
+ }
1139
+
1114
1140
  // src/builder/joins.ts
1115
1141
  function isRelationField(fieldName, model) {
1116
1142
  return getRelationFieldSet(model).has(fieldName);
@@ -1129,38 +1155,14 @@ function isValidRelationField(field) {
1129
1155
  if (refs.length !== fk.length) return false;
1130
1156
  return true;
1131
1157
  }
1132
- function getReferenceFieldNames(field, foreignKeyCount) {
1133
- const refs = normalizeKeyList(field.references);
1134
- if (refs.length === 0) {
1135
- if (foreignKeyCount === 1) return [SPECIAL_FIELDS.ID];
1136
- return [];
1137
- }
1138
- if (refs.length !== foreignKeyCount) return [];
1139
- return refs;
1140
- }
1141
1158
  function joinCondition(field, parentModel, childModel, parentAlias, childAlias) {
1142
1159
  assertSafeAlias(parentAlias);
1143
1160
  assertSafeAlias(childAlias);
1144
- const fkFields = normalizeKeyList(field.foreignKey);
1145
- if (fkFields.length === 0) {
1146
- throw createError(
1147
- `Relation '${field.name}' is missing foreignKey. This indicates a schema parsing error. Relations must specify fields/references.`,
1148
- { field: field.name }
1149
- );
1150
- }
1151
- const refFields = getReferenceFieldNames(field, fkFields.length);
1152
- if (refFields.length !== fkFields.length) {
1153
- throw createError(
1154
- `Relation '${field.name}' is missing references (or references count does not match foreignKey count). This is required to support non-id and composite keys.`,
1155
- { field: field.name }
1156
- );
1157
- }
1161
+ const { childKeys, parentKeys } = resolveRelationKeys(field, "include");
1158
1162
  const parts = [];
1159
- for (let i = 0; i < fkFields.length; i++) {
1160
- const fk = fkFields[i];
1161
- const ref = refFields[i];
1162
- const left = field.isForeignKeyLocal ? `${childAlias}.${quoteColumn(childModel, ref)}` : `${childAlias}.${quoteColumn(childModel, fk)}`;
1163
- const right = field.isForeignKeyLocal ? `${parentAlias}.${quoteColumn(parentModel, fk)}` : `${parentAlias}.${quoteColumn(parentModel, ref)}`;
1163
+ for (let i = 0; i < parentKeys.length; i++) {
1164
+ const left = field.isForeignKeyLocal ? `${childAlias}.${quoteColumn(childModel, childKeys[i])}` : `${childAlias}.${quoteColumn(childModel, childKeys[i])}`;
1165
+ const right = field.isForeignKeyLocal ? `${parentAlias}.${quoteColumn(parentModel, parentKeys[i])}` : `${parentAlias}.${quoteColumn(parentModel, parentKeys[i])}`;
1164
1166
  parts.push(`${left} = ${right}`);
1165
1167
  }
1166
1168
  return parts.length === 1 ? parts[0] : `(${parts.join(" AND ")})`;
@@ -1169,13 +1171,13 @@ function getModelByName(schemas, name) {
1169
1171
  return schemas.find((m) => m.name === name);
1170
1172
  }
1171
1173
  function normalizeIntLike(name, v, opts = {}) {
1172
- var _a3, _b;
1174
+ var _a4, _b;
1173
1175
  if (!isNotNullish(v)) return void 0;
1174
1176
  if (isDynamicParameter(v)) return v;
1175
1177
  if (typeof v !== "number" || !Number.isFinite(v) || !Number.isInteger(v)) {
1176
1178
  throw new Error(`${name} must be an integer`);
1177
1179
  }
1178
- const min = (_a3 = opts.min) != null ? _a3 : 0;
1180
+ const min = (_a4 = opts.min) != null ? _a4 : 0;
1179
1181
  const allowZero = (_b = opts.allowZero) != null ? _b : true;
1180
1182
  if (!allowZero && v === 0) {
1181
1183
  throw new Error(`${name} must be > 0`);
@@ -1321,6 +1323,14 @@ function reverseOrderByInput(orderBy) {
1321
1323
  var normalizePairs = (pairs, parseValue) => {
1322
1324
  const result = [];
1323
1325
  for (const [field, rawValue] of pairs) {
1326
+ if (typeof rawValue === "string") {
1327
+ const lower = rawValue.toLowerCase();
1328
+ if (lower !== "asc" && lower !== "desc") {
1329
+ throw new Error(
1330
+ `Invalid orderBy direction '${rawValue}' for field '${field}'. Must be 'asc' or 'desc'`
1331
+ );
1332
+ }
1333
+ }
1324
1334
  if (!isScalarOrderByValue(rawValue)) continue;
1325
1335
  const parsed = parseValue(rawValue, field);
1326
1336
  result.push({
@@ -1402,6 +1412,29 @@ function ensureDeterministicOrderByInput(args) {
1402
1412
  return addTiebreaker(orderBy, tiebreaker);
1403
1413
  }
1404
1414
 
1415
+ // src/builder/shared/errors.ts
1416
+ var SqlBuilderError = class extends Error {
1417
+ constructor(message, code, context) {
1418
+ super(message);
1419
+ this.name = "SqlBuilderError";
1420
+ this.code = code;
1421
+ this.context = context;
1422
+ }
1423
+ };
1424
+ function createError(message, ctx, code = "VALIDATION_ERROR") {
1425
+ const parts = [message];
1426
+ if (isNonEmptyArray(ctx.path)) {
1427
+ parts.push(`Path: ${ctx.path.join(".")}`);
1428
+ }
1429
+ if (isNotNullish(ctx.modelName)) {
1430
+ parts.push(`Model: ${ctx.modelName}`);
1431
+ }
1432
+ if (isNonEmptyArray(ctx.availableFields)) {
1433
+ parts.push(`Available fields: ${ctx.availableFields.join(", ")}`);
1434
+ }
1435
+ return new SqlBuilderError(parts.join("\n"), code, ctx);
1436
+ }
1437
+
1405
1438
  // src/builder/shared/primary-key-utils.ts
1406
1439
  var FIELD_BY_NAME_CACHE = /* @__PURE__ */ new WeakMap();
1407
1440
  function normalizeField2(field) {
@@ -1686,7 +1719,7 @@ function assertCursorAndOrderFieldsScalar(model, cursor, orderEntries) {
1686
1719
  }
1687
1720
  }
1688
1721
  function buildCursorCondition(cursor, orderBy, tableName, alias, params, dialect, model) {
1689
- var _a3;
1722
+ var _a4;
1690
1723
  assertSafeTableRef(tableName);
1691
1724
  assertSafeAlias(alias);
1692
1725
  const d = dialect != null ? dialect : getGlobalDialect();
@@ -1781,7 +1814,7 @@ function buildCursorCondition(cursor, orderBy, tableName, alias, params, dialect
1781
1814
  const e = finalOrderEntries[level];
1782
1815
  const c = col(alias, e.field, model);
1783
1816
  const cursorField = cteName + "." + quoteColumn(model, e.field);
1784
- const nulls = (_a3 = e.nulls) != null ? _a3 : defaultNullsFor(d, e.direction);
1817
+ const nulls = (_a4 = e.nulls) != null ? _a4 : defaultNullsFor(d, e.direction);
1785
1818
  andParts.push(buildCursorInequalityExpr(c, e.direction, nulls, cursorField));
1786
1819
  orClauses.push("(" + andParts.join(SQL_SEPARATORS.CONDITION_AND) + ")");
1787
1820
  }
@@ -1901,34 +1934,6 @@ function createAliasGenerator(maxAliases = 1e4) {
1901
1934
  };
1902
1935
  }
1903
1936
 
1904
- // src/builder/shared/relation-key-utils.ts
1905
- var RELATION_KEYS_CACHE = /* @__PURE__ */ new WeakMap();
1906
- function computeRelationKeys(field, context) {
1907
- const fkFields = normalizeKeyList(field.foreignKey);
1908
- if (fkFields.length === 0) {
1909
- throw new Error(
1910
- `Relation '${field.name}' is missing foreignKey for ${context}`
1911
- );
1912
- }
1913
- const refs = normalizeKeyList(field.references);
1914
- const refFields = refs.length > 0 ? refs : fkFields.length === 1 ? ["id"] : [];
1915
- if (refFields.length !== fkFields.length) {
1916
- throw new Error(
1917
- `Relation '${field.name}' references count (${refFields.length}) doesn't match foreignKey count (${fkFields.length}) (context: ${context})`
1918
- );
1919
- }
1920
- const childKeys = field.isForeignKeyLocal ? refFields : fkFields;
1921
- const parentKeys = field.isForeignKeyLocal ? fkFields : refFields;
1922
- return { childKeys, parentKeys };
1923
- }
1924
- function resolveRelationKeys(field, context = "include") {
1925
- let cached = RELATION_KEYS_CACHE.get(field);
1926
- if (cached) return cached;
1927
- cached = computeRelationKeys(field, context);
1928
- RELATION_KEYS_CACHE.set(field, cached);
1929
- return cached;
1930
- }
1931
-
1932
1937
  // src/builder/shared/fk-join-utils.ts
1933
1938
  var FK_COLUMN_PREFIX = "__fk";
1934
1939
  function fkColumnName(index) {
@@ -2114,7 +2119,7 @@ function resolveCountRelationOrThrow(relName, model, schemaByName) {
2114
2119
  `_count.${relName} references unknown relation on model ${model.name}`
2115
2120
  );
2116
2121
  }
2117
- const field = model.fields.find((f) => f.name === relName);
2122
+ const field = getFieldIndices(model).allFieldsByName.get(relName);
2118
2123
  if (!field) {
2119
2124
  throw new Error(
2120
2125
  `_count.${relName} references unknown relation on model ${model.name}`
@@ -2191,12 +2196,11 @@ function buildCountJoinAndPair(args) {
2191
2196
  pairSql: `${sqlStringLiteral(args.relName)}, COALESCE(${joinAlias}.${COUNT_COLUMN}, 0)`
2192
2197
  };
2193
2198
  }
2194
- function buildRelationCountSql(countSelect, model, schemas, parentAlias, _params, dialect) {
2199
+ function buildRelationCountSql(countSelect, model, schemas, parentAlias, _params, dialect, modelMap) {
2195
2200
  const joins = [];
2196
2201
  const pairs = [];
2197
2202
  const aliasGen = createAliasGenerator();
2198
- const schemaByName = /* @__PURE__ */ new Map();
2199
- for (const m of schemas) schemaByName.set(m.name, m);
2203
+ const schemaByName = modelMap != null ? modelMap : new Map(schemas.map((m) => [m.name, m]));
2200
2204
  for (const [relName, shouldCount] of Object.entries(countSelect)) {
2201
2205
  if (!shouldCount) continue;
2202
2206
  const resolved = resolveCountRelationOrThrow(relName, model, schemaByName);
@@ -2270,14 +2274,23 @@ function extractNestedIncludeSpec(relArgs, relModel) {
2270
2274
  }
2271
2275
 
2272
2276
  // src/builder/shared/include-tree-walker.ts
2273
- function resolveIncludeRelations(includeSpec, model, schemas) {
2274
- const modelMap = new Map(schemas.map((m) => [m.name, m]));
2277
+ var MODEL_MAP_CACHE = /* @__PURE__ */ new WeakMap();
2278
+ function getOrCreateModelMap(schemas) {
2279
+ let map = MODEL_MAP_CACHE.get(schemas);
2280
+ if (map) return map;
2281
+ map = /* @__PURE__ */ new Map();
2282
+ for (const m of schemas) map.set(m.name, m);
2283
+ MODEL_MAP_CACHE.set(schemas, map);
2284
+ return map;
2285
+ }
2286
+ function resolveIncludeRelations(includeSpec, model, schemas, modelMap) {
2287
+ const map = modelMap != null ? modelMap : getOrCreateModelMap(schemas);
2275
2288
  const results = [];
2276
2289
  for (const [relName, value] of Object.entries(includeSpec)) {
2277
2290
  if (value === false) continue;
2278
- const field = model.fields.find((f) => f.name === relName);
2291
+ const field = getFieldIndices(model).allFieldsByName.get(relName);
2279
2292
  if (!(field == null ? void 0 : field.isRelation) || !field.relatedModel) continue;
2280
- const relModel = modelMap.get(field.relatedModel);
2293
+ const relModel = map.get(field.relatedModel);
2281
2294
  if (!relModel) continue;
2282
2295
  const isList = typeof field.type === "string" && field.type.endsWith("[]");
2283
2296
  const nestedSpec = isPlainObject(value) ? extractNestedIncludeSpec(value, relModel) : {};
@@ -2300,7 +2313,7 @@ var CORRELATED_WHERE_PENALTY = 3;
2300
2313
  var DEFAULT_FAN = 10;
2301
2314
  var DEFAULT_PARENT_COUNT = 50;
2302
2315
  var MIN_STATS_COVERAGE = 0.1;
2303
- var SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH = 1;
2316
+ var SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH = 2;
2304
2317
  function setRoundtripRowEquivalent(value) {
2305
2318
  globalRoundtripRowEquivalent = value;
2306
2319
  }
@@ -2343,15 +2356,26 @@ function hasPaginationArgs(value) {
2343
2356
  const obj = value;
2344
2357
  return "take" in obj && obj.take != null || "skip" in obj && obj.skip != null && (typeof obj.skip === "number" && obj.skip > 0 || isDynamicParameter(obj.skip));
2345
2358
  }
2346
- function buildCostTree(includeSpec, model, schemas, depth = 0) {
2359
+ function buildCostTree(includeSpec, model, schemas, depth = 0, modelMap) {
2347
2360
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return [];
2348
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2361
+ const relations = resolveIncludeRelations(
2362
+ includeSpec,
2363
+ model,
2364
+ schemas,
2365
+ modelMap
2366
+ );
2349
2367
  const nodes = [];
2350
2368
  for (const rel of relations) {
2351
2369
  const fan = rel.isList ? getFanOut(model.name, rel.relName) : 1;
2352
2370
  const take = rel.isList ? readTake(rel.value) : 1;
2353
2371
  const eff = Math.min(fan, take);
2354
- const children = Object.keys(rel.nestedSpec).length > 0 ? buildCostTree(rel.nestedSpec, rel.relModel, schemas, depth + 1) : [];
2372
+ const children = Object.keys(rel.nestedSpec).length > 0 ? buildCostTree(
2373
+ rel.nestedSpec,
2374
+ rel.relModel,
2375
+ schemas,
2376
+ depth + 1,
2377
+ modelMap
2378
+ ) : [];
2355
2379
  nodes.push({
2356
2380
  name: rel.relName,
2357
2381
  fan,
@@ -2415,17 +2439,23 @@ function computeCorrelatedCost(nodes, parentCount) {
2415
2439
  return R + parentCount * subqueryCost(nodes);
2416
2440
  }
2417
2441
  function hasOnlyToOneRelations(includeSpec, model) {
2442
+ const indices = getFieldIndices(model);
2418
2443
  for (const [relName, value] of Object.entries(includeSpec)) {
2419
2444
  if (value === false) continue;
2420
- const field = model.fields.find((f) => f.name === relName);
2445
+ const field = indices.allFieldsByName.get(relName);
2421
2446
  if (!(field == null ? void 0 : field.isRelation)) continue;
2422
2447
  if (isListField(field)) return false;
2423
2448
  }
2424
2449
  return true;
2425
2450
  }
2426
- function countIncludeDepth(includeSpec, model, schemas, depth = 0) {
2451
+ function countIncludeDepth(includeSpec, model, schemas, depth = 0, modelMap) {
2427
2452
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return 0;
2428
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2453
+ const relations = resolveIncludeRelations(
2454
+ includeSpec,
2455
+ model,
2456
+ schemas,
2457
+ modelMap
2458
+ );
2429
2459
  let maxDepth = 0;
2430
2460
  for (const rel of relations) {
2431
2461
  let childDepth = 1;
@@ -2434,27 +2464,34 @@ function countIncludeDepth(includeSpec, model, schemas, depth = 0) {
2434
2464
  rel.nestedSpec,
2435
2465
  rel.relModel,
2436
2466
  schemas,
2437
- depth + 1
2467
+ depth + 1,
2468
+ modelMap
2438
2469
  );
2439
2470
  }
2440
2471
  if (childDepth > maxDepth) maxDepth = childDepth;
2441
2472
  }
2442
2473
  return maxDepth;
2443
2474
  }
2444
- function hasChildPaginationAnywhere(includeSpec, model, schemas, depth = 0) {
2475
+ function hasChildPaginationAnywhere(includeSpec, model, schemas, depth = 0, modelMap) {
2445
2476
  if (depth > LIMITS.MAX_INCLUDE_DEPTH) return false;
2446
2477
  for (const [, value] of Object.entries(includeSpec)) {
2447
2478
  if (value === false) continue;
2448
2479
  if (hasPaginationArgs(value)) return true;
2449
2480
  }
2450
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2481
+ const relations = resolveIncludeRelations(
2482
+ includeSpec,
2483
+ model,
2484
+ schemas,
2485
+ modelMap
2486
+ );
2451
2487
  for (const rel of relations) {
2452
2488
  if (Object.keys(rel.nestedSpec).length > 0) {
2453
2489
  if (hasChildPaginationAnywhere(
2454
2490
  rel.nestedSpec,
2455
2491
  rel.relModel,
2456
2492
  schemas,
2457
- depth + 1
2493
+ depth + 1,
2494
+ modelMap
2458
2495
  )) {
2459
2496
  return true;
2460
2497
  }
@@ -2471,7 +2508,8 @@ function pickIncludeStrategy(params) {
2471
2508
  takeValue,
2472
2509
  canFlatJoin,
2473
2510
  hasChildPagination,
2474
- debug
2511
+ debug,
2512
+ modelMap
2475
2513
  } = params;
2476
2514
  if (Object.keys(includeSpec).length === 0) return "where-in";
2477
2515
  if (canFlatJoin && hasOnlyToOneRelations(includeSpec, model)) {
@@ -2481,7 +2519,7 @@ function pickIncludeStrategy(params) {
2481
2519
  }
2482
2520
  const isSingleParent = method === "findFirst" || method === "findUnique";
2483
2521
  if (isSingleParent && canFlatJoin) {
2484
- const depth = countIncludeDepth(includeSpec, model, schemas);
2522
+ const depth = countIncludeDepth(includeSpec, model, schemas, 0, modelMap);
2485
2523
  if (depth <= SINGLE_PARENT_MAX_FLAT_JOIN_DEPTH) {
2486
2524
  if (debug)
2487
2525
  console.log(
@@ -2490,7 +2528,7 @@ function pickIncludeStrategy(params) {
2490
2528
  return "flat-join";
2491
2529
  }
2492
2530
  }
2493
- const costTree = buildCostTree(includeSpec, model, schemas);
2531
+ const costTree = buildCostTree(includeSpec, model, schemas, 0, modelMap);
2494
2532
  const treeDepth = maxDepthFromTree(costTree);
2495
2533
  if (hasChildPagination && treeDepth >= 2) {
2496
2534
  if (debug)
@@ -2598,13 +2636,13 @@ function createAliasCounter() {
2598
2636
  }
2599
2637
  };
2600
2638
  }
2601
- function getRelationModel(parentModel, relationName, schemas) {
2639
+ function getRelationModel(parentModel, relationName, schemas, modelMap) {
2602
2640
  const indices = getFieldIndices(parentModel);
2603
2641
  const field = indices.allFieldsByName.get(relationName);
2604
2642
  if (!(field == null ? void 0 : field.isRelation) || !field.relatedModel) {
2605
2643
  throw new Error(`Invalid relation ${relationName} on ${parentModel.name}`);
2606
2644
  }
2607
- const relModel = schemas.find((m) => m.name === field.relatedModel);
2645
+ const relModel = modelMap ? modelMap.get(field.relatedModel) : schemas.find((m) => m.name === field.relatedModel);
2608
2646
  if (!relModel) {
2609
2647
  throw new Error(`Related model ${field.relatedModel} not found`);
2610
2648
  }
@@ -2641,8 +2679,13 @@ function countActiveEntries(spec) {
2641
2679
  }
2642
2680
  return count;
2643
2681
  }
2644
- function canUseFlatJoinForAll(includeSpec, model, schemas, debug) {
2645
- const relations = resolveIncludeRelations(includeSpec, model, schemas);
2682
+ function canUseFlatJoinForAll(includeSpec, model, schemas, debug, modelMap) {
2683
+ const relations = resolveIncludeRelations(
2684
+ includeSpec,
2685
+ model,
2686
+ schemas,
2687
+ modelMap
2688
+ );
2646
2689
  if (relations.length < countActiveEntries(includeSpec)) {
2647
2690
  return false;
2648
2691
  }
@@ -2664,14 +2707,20 @@ function canUseFlatJoinForAll(includeSpec, model, schemas, debug) {
2664
2707
  return false;
2665
2708
  }
2666
2709
  if (Object.keys(rel.nestedSpec).length > 0) {
2667
- if (!canUseFlatJoinForAll(rel.nestedSpec, rel.relModel, schemas)) {
2710
+ if (!canUseFlatJoinForAll(
2711
+ rel.nestedSpec,
2712
+ rel.relModel,
2713
+ schemas,
2714
+ debug,
2715
+ modelMap
2716
+ )) {
2668
2717
  return false;
2669
2718
  }
2670
2719
  }
2671
2720
  }
2672
2721
  return true;
2673
2722
  }
2674
- function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialect, prefix, aliasCounter, depth = 0) {
2723
+ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialect, prefix, aliasCounter, depth = 0, modelMap) {
2675
2724
  if (depth > LIMITS.MAX_NESTED_JOIN_DEPTH) {
2676
2725
  throw new Error(
2677
2726
  `Nested joins exceeded maximum depth of ${LIMITS.MAX_NESTED_JOIN_DEPTH} at prefix '${prefix}'`
@@ -2685,7 +2734,7 @@ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialec
2685
2734
  const indices = getFieldIndices(parentModel);
2686
2735
  const field = indices.allFieldsByName.get(relName);
2687
2736
  if (!isValidRelationField(field)) continue;
2688
- const relModel = getRelationModel(parentModel, relName, schemas);
2737
+ const relModel = getRelationModel(parentModel, relName, schemas, modelMap);
2689
2738
  const relTable = buildTableReference(
2690
2739
  SQL_TEMPLATES.PUBLIC_SCHEMA,
2691
2740
  relModel.tableName,
@@ -2726,7 +2775,8 @@ function buildNestedJoins(parentModel, parentAlias, includeSpec, schemas, dialec
2726
2775
  dialect,
2727
2776
  nestedPrefix,
2728
2777
  aliasCounter,
2729
- depth + 1
2778
+ depth + 1,
2779
+ modelMap
2730
2780
  );
2731
2781
  joins.push(...deeper.joins);
2732
2782
  selects.push(...deeper.selects);
@@ -2782,6 +2832,8 @@ function buildFlatJoinSql(spec) {
2782
2832
  requiresReduction: false,
2783
2833
  includeSpec: {}
2784
2834
  };
2835
+ const modelMap = /* @__PURE__ */ new Map();
2836
+ for (const m of schemas) modelMap.set(m.name, m);
2785
2837
  const includeSpec = extractRelationEntries(args, model).reduce(
2786
2838
  (acc, { name, value }) => {
2787
2839
  acc[name] = value;
@@ -2792,7 +2844,7 @@ function buildFlatJoinSql(spec) {
2792
2844
  if (Object.keys(includeSpec).length === 0) {
2793
2845
  return emptyResult;
2794
2846
  }
2795
- if (!canUseFlatJoinForAll(includeSpec, model, schemas)) {
2847
+ if (!canUseFlatJoinForAll(includeSpec, model, schemas, false, modelMap)) {
2796
2848
  return emptyResult;
2797
2849
  }
2798
2850
  const { cleanWhere, params } = extractReferencedParams(
@@ -2828,7 +2880,8 @@ function buildFlatJoinSql(spec) {
2828
2880
  dialect,
2829
2881
  "",
2830
2882
  aliasCounter,
2831
- 0
2883
+ 0,
2884
+ modelMap
2832
2885
  );
2833
2886
  if (built.joins.length === 0) {
2834
2887
  return emptyResult;
@@ -3832,8 +3885,8 @@ function buildOperator(expr, op, val, ctx, mode, fieldType) {
3832
3885
  });
3833
3886
  }
3834
3887
  var MAX_PARAM_INDEX = Number.MAX_SAFE_INTEGER - 1e3;
3835
- var _a2;
3836
- var IS_PRODUCTION2 = typeof process !== "undefined" && ((_a2 = process.env) == null ? void 0 : _a2.NODE_ENV) === "production";
3888
+ var _a3;
3889
+ var IS_PRODUCTION3 = typeof process !== "undefined" && ((_a3 = process.env) == null ? void 0 : _a3.NODE_ENV) === "production";
3837
3890
  function assertSameLength(params, mappings) {
3838
3891
  if (params.length !== mappings.length) {
3839
3892
  throw new Error(
@@ -3893,7 +3946,7 @@ function validateMappings(mappings) {
3893
3946
  }
3894
3947
  }
3895
3948
  function validateState(params, mappings, index) {
3896
- if (IS_PRODUCTION2) {
3949
+ if (IS_PRODUCTION3) {
3897
3950
  assertSameLength(params, mappings);
3898
3951
  assertValidNextIndex(index);
3899
3952
  return;
@@ -3951,6 +4004,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3951
4004
  if (frozen) {
3952
4005
  params = params.slice();
3953
4006
  mappings = mappings.slice();
4007
+ dynamicNameToIndex = new Map(dynamicNameToIndex);
3954
4008
  frozen = false;
3955
4009
  }
3956
4010
  }
@@ -3967,6 +4021,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3967
4021
  const dn = validateDynamicName(dynamicName);
3968
4022
  const existing = dynamicNameToIndex.get(dn);
3969
4023
  if (existing !== void 0) return formatPosition(existing);
4024
+ ensureMutable();
3970
4025
  const position = index;
3971
4026
  dynamicNameToIndex.set(dn, position);
3972
4027
  return registerParam(void 0, { index: position, dynamicName: dn });
@@ -3997,7 +4052,7 @@ function createStoreInternal(startIndex, dialect, initialParams = [], initialMap
3997
4052
  index,
3998
4053
  params,
3999
4054
  mappings,
4000
- dynamicNameIndex: new Map(dynamicNameToIndex)
4055
+ dynamicNameIndex: dynamicNameToIndex
4001
4056
  };
4002
4057
  cachedSnapshot = snap;
4003
4058
  dirty = false;
@@ -4052,10 +4107,10 @@ function toPublicResult(clause, joins, params) {
4052
4107
 
4053
4108
  // src/builder/where.ts
4054
4109
  function buildWhereClause(where, options) {
4055
- var _a3, _b, _c, _d, _e;
4110
+ var _a4, _b, _c, _d, _e;
4056
4111
  assertSafeAlias(options.alias);
4057
4112
  const dialect = options.dialect || getGlobalDialect();
4058
- const params = (_a3 = options.params) != null ? _a3 : createParamStore(1, dialect);
4113
+ const params = (_a4 = options.params) != null ? _a4 : createParamStore(1, dialect);
4059
4114
  const ctx = {
4060
4115
  alias: options.alias,
4061
4116
  model: options.model,
@@ -4138,12 +4193,13 @@ function reindexWhereParams(whereClause, specParams, collector) {
4138
4193
  }
4139
4194
  return clean;
4140
4195
  }
4141
- function getRelationModel2(parentModel, relationName, schemas) {
4142
- var _a3;
4196
+ function getRelationModel2(parentModel, relationName, schemas, modelMap) {
4197
+ var _a4, _b;
4143
4198
  const indices = getFieldIndices(parentModel);
4144
4199
  const field = indices.allFieldsByName.get(relationName);
4145
4200
  if (!(field == null ? void 0 : field.isRelation) || !field.relatedModel) return null;
4146
- return (_a3 = schemas.find((m) => m.name === field.relatedModel)) != null ? _a3 : null;
4201
+ if (modelMap) return (_a4 = modelMap.get(field.relatedModel)) != null ? _a4 : null;
4202
+ return (_b = schemas.find((m) => m.name === field.relatedModel)) != null ? _b : null;
4147
4203
  }
4148
4204
  function extractOrderByInput(relArgs) {
4149
4205
  if (!isPlainObject(relArgs)) return void 0;
@@ -4188,7 +4244,12 @@ function buildLateralForRelation(relationName, relArgs, field, relModel, parentM
4188
4244
  const nestedIndices = getFieldIndices(relModel);
4189
4245
  const nestedField = nestedIndices.allFieldsByName.get(nestedName);
4190
4246
  if (!nestedField || !isValidRelationField(nestedField)) continue;
4191
- const nestedModel = getRelationModel2(relModel, nestedName, ctx.schemas);
4247
+ const nestedModel = getRelationModel2(
4248
+ relModel,
4249
+ nestedName,
4250
+ ctx.schemas,
4251
+ ctx.modelMap
4252
+ );
4192
4253
  if (!nestedModel) continue;
4193
4254
  const nested = buildLateralForRelation(
4194
4255
  nestedName,
@@ -4291,12 +4352,12 @@ function buildLateralForRelation(relationName, relArgs, field, relModel, parentM
4291
4352
  }
4292
4353
  const joinSql = `LEFT JOIN LATERAL (${outerSql}) ${latAlias} ON true`;
4293
4354
  const fieldTypes = selectedFields.map((fieldName) => {
4294
- var _a3;
4355
+ var _a4;
4295
4356
  const f = indices.scalarFields.get(fieldName);
4296
4357
  if (!f) return null;
4297
4358
  return {
4298
4359
  fieldName: f.name,
4299
- type: String((_a3 = f.type) != null ? _a3 : "").toLowerCase()
4360
+ type: String((_a4 = f.type) != null ? _a4 : "").toLowerCase()
4300
4361
  };
4301
4362
  }).filter(Boolean);
4302
4363
  const meta = {
@@ -4314,8 +4375,13 @@ function countActiveEntries2(spec) {
4314
4375
  }
4315
4376
  return count;
4316
4377
  }
4317
- function canUseLateralJoin(includeSpec, parentModel, schemas) {
4318
- const relations = resolveIncludeRelations(includeSpec, parentModel, schemas);
4378
+ function canUseLateralJoin(includeSpec, parentModel, schemas, modelMap) {
4379
+ const relations = resolveIncludeRelations(
4380
+ includeSpec,
4381
+ parentModel,
4382
+ schemas,
4383
+ modelMap
4384
+ );
4319
4385
  if (relations.length < countActiveEntries2(includeSpec)) {
4320
4386
  return false;
4321
4387
  }
@@ -4324,14 +4390,14 @@ function canUseLateralJoin(includeSpec, parentModel, schemas) {
4324
4390
  if (!keys || keys.childKeys.length === 0 || keys.parentKeys.length === 0)
4325
4391
  return false;
4326
4392
  if (Object.keys(rel.nestedSpec).length > 0) {
4327
- if (!canUseLateralJoin(rel.nestedSpec, rel.relModel, schemas))
4393
+ if (!canUseLateralJoin(rel.nestedSpec, rel.relModel, schemas, modelMap))
4328
4394
  return false;
4329
4395
  }
4330
4396
  }
4331
4397
  return true;
4332
4398
  }
4333
4399
  function buildLateralJoinSql(spec) {
4334
- var _a3;
4400
+ var _a4;
4335
4401
  const {
4336
4402
  from,
4337
4403
  whereClause,
@@ -4351,6 +4417,8 @@ function buildLateralJoinSql(spec) {
4351
4417
  isLateral: false,
4352
4418
  lateralMeta: []
4353
4419
  };
4420
+ const modelMap = /* @__PURE__ */ new Map();
4421
+ for (const m of schemas) modelMap.set(m.name, m);
4354
4422
  const entries = extractRelationEntries(args, model);
4355
4423
  const includeSpec = {};
4356
4424
  for (const e of entries) {
@@ -4377,7 +4445,8 @@ function buildLateralJoinSql(spec) {
4377
4445
  schemas,
4378
4446
  dialect,
4379
4447
  aliasCounter,
4380
- collector
4448
+ collector,
4449
+ modelMap
4381
4450
  };
4382
4451
  const lateralJoins = [];
4383
4452
  const lateralSelects = [];
@@ -4387,7 +4456,7 @@ function buildLateralJoinSql(spec) {
4387
4456
  const indices = getFieldIndices(model);
4388
4457
  const field = indices.allFieldsByName.get(relName);
4389
4458
  if (!field || !isValidRelationField(field)) continue;
4390
- const relModel = getRelationModel2(model, relName, schemas);
4459
+ const relModel = getRelationModel2(model, relName, schemas, modelMap);
4391
4460
  if (!relModel) continue;
4392
4461
  const result = buildLateralForRelation(
4393
4462
  relName,
@@ -4405,7 +4474,7 @@ function buildLateralJoinSql(spec) {
4405
4474
  lateralMeta.push(result.meta);
4406
4475
  }
4407
4476
  if (lateralJoins.length === 0) return emptyResult;
4408
- const baseSelect = ((_a3 = spec.select) != null ? _a3 : "").trim();
4477
+ const baseSelect = ((_a4 = spec.select) != null ? _a4 : "").trim();
4409
4478
  const allSelects = [baseSelect, ...lateralSelects].filter((s) => s && s.trim().length > 0).join(", ");
4410
4479
  if (!allSelects) {
4411
4480
  return emptyResult;
@@ -4525,9 +4594,9 @@ function renderOrderBySimple(entries, alias) {
4525
4594
  return out.join(SQL_SEPARATORS.ORDER_BY);
4526
4595
  }
4527
4596
  function ensureIdTiebreakerEntries(entries, model) {
4528
- var _a3, _b;
4529
- const idField = (_b = (_a3 = model == null ? void 0 : model.fields) == null ? void 0 : _a3.find) == null ? void 0 : _b.call(
4530
- _a3,
4597
+ var _a4, _b;
4598
+ const idField = (_b = (_a4 = model == null ? void 0 : model.fields) == null ? void 0 : _a4.find) == null ? void 0 : _b.call(
4599
+ _a4,
4531
4600
  (f) => f.name === DEFAULT_PRIMARY_KEY2 && !f.isRelation
4532
4601
  );
4533
4602
  if (!idField) return entries;
@@ -4569,14 +4638,14 @@ function buildJoinsSql(...joinGroups) {
4569
4638
  return all.length > 0 ? " " + all.join(" ") : "";
4570
4639
  }
4571
4640
  function buildSqliteDistinctQuery(spec, selectWithIncludes, countJoins) {
4572
- var _a3, _b;
4641
+ var _a4, _b;
4573
4642
  const { includes, from, whereClause, whereJoins, distinct, model } = spec;
4574
4643
  if (!isNotNullish(distinct) || !isNonEmptyArray(distinct)) {
4575
4644
  throw new Error("buildSqliteDistinctQuery requires distinct fields");
4576
4645
  }
4577
4646
  const scalarNames = parseSimpleScalarSelect(spec.select, from.alias);
4578
4647
  const includeNames = includes.map((i) => i.name);
4579
- const hasCount = Boolean((_b = (_a3 = spec.args) == null ? void 0 : _a3.select) == null ? void 0 : _b[COUNT_SELECT_KEY]);
4648
+ const hasCount = Boolean((_b = (_a4 = spec.args) == null ? void 0 : _a4.select) == null ? void 0 : _b[COUNT_SELECT_KEY]);
4580
4649
  const outerSelectCols = buildOutputColumns(
4581
4650
  scalarNames,
4582
4651
  includeNames,
@@ -4676,12 +4745,12 @@ function resolveCountSelect(countSelectRaw, model) {
4676
4745
  return null;
4677
4746
  }
4678
4747
  function buildIncludeColumns(spec) {
4679
- var _a3, _b, _c, _d, _e;
4748
+ var _a4, _b, _c, _d, _e;
4680
4749
  const { select, includes, dialect, model, schemas, from, params } = spec;
4681
4750
  const baseSelect = (select != null ? select : "").trim();
4682
4751
  let countCols = "";
4683
4752
  let countJoins = [];
4684
- const countSelectRaw = (_e = (_b = (_a3 = spec.args) == null ? void 0 : _a3.select) == null ? void 0 : _b[COUNT_SELECT_KEY]) != null ? _e : (_d = (_c = spec.args) == null ? void 0 : _c.include) == null ? void 0 : _d[COUNT_SELECT_KEY];
4753
+ const countSelectRaw = (_e = (_b = (_a4 = spec.args) == null ? void 0 : _a4.select) == null ? void 0 : _b[COUNT_SELECT_KEY]) != null ? _e : (_d = (_c = spec.args) == null ? void 0 : _c.include) == null ? void 0 : _d[COUNT_SELECT_KEY];
4685
4754
  if (countSelectRaw) {
4686
4755
  const resolvedCountSelect = resolveCountSelect(countSelectRaw, model);
4687
4756
  if (resolvedCountSelect && Object.keys(resolvedCountSelect).length > 0) {
@@ -4863,9 +4932,22 @@ function constructFinalSql(spec) {
4863
4932
  isNotNullish(pagination.take);
4864
4933
  const takeValue = typeof pagination.take === "number" ? pagination.take : null;
4865
4934
  if (dialect === "postgres" && hasIncludes) {
4866
- const canFlatJoin = canUseFlatJoinForAll(includeSpec, model, schemas);
4867
- canUseLateralJoin(includeSpec, model, schemas);
4868
- const hasChildPag = hasChildPaginationAnywhere(includeSpec, model, schemas);
4935
+ const modelMap = getOrCreateModelMap(schemas);
4936
+ const canFlatJoin = canUseFlatJoinForAll(
4937
+ includeSpec,
4938
+ model,
4939
+ schemas,
4940
+ false,
4941
+ modelMap
4942
+ );
4943
+ canUseLateralJoin(includeSpec, model, schemas, modelMap);
4944
+ const hasChildPag = hasChildPaginationAnywhere(
4945
+ includeSpec,
4946
+ model,
4947
+ schemas,
4948
+ 0,
4949
+ modelMap
4950
+ );
4869
4951
  const strategy = pickIncludeStrategy({
4870
4952
  includeSpec,
4871
4953
  model,
@@ -4874,7 +4956,8 @@ function constructFinalSql(spec) {
4874
4956
  args,
4875
4957
  takeValue,
4876
4958
  canFlatJoin,
4877
- hasChildPagination: hasChildPag
4959
+ hasChildPagination: hasChildPag,
4960
+ modelMap
4878
4961
  });
4879
4962
  if (strategy === "flat-join") {
4880
4963
  const flatResult = buildFlatJoinSql(spec);
@@ -4998,8 +5081,8 @@ function buildDefaultScalarFields(model, alias) {
4998
5081
  return out;
4999
5082
  }
5000
5083
  function getDefaultSelectCached(model, alias) {
5001
- var _a3;
5002
- return (_a3 = DEFAULT_SELECT_CACHE.get(model)) == null ? void 0 : _a3.get(alias);
5084
+ var _a4;
5085
+ return (_a4 = DEFAULT_SELECT_CACHE.get(model)) == null ? void 0 : _a4.get(alias);
5003
5086
  }
5004
5087
  function cacheDefaultSelect(model, alias, sql) {
5005
5088
  let cache = DEFAULT_SELECT_CACHE.get(model);
@@ -5281,7 +5364,8 @@ function buildSelectWithNestedIncludes(relArgs, relModel, relAlias, ctx) {
5281
5364
  ctx.schemas,
5282
5365
  relAlias,
5283
5366
  ctx.params,
5284
- ctx.dialect
5367
+ ctx.dialect,
5368
+ ctx.schemaByName
5285
5369
  );
5286
5370
  if (!countBuild.jsonPairs) return baseSelect2;
5287
5371
  countJoins.push(...countBuild.joins);
@@ -5669,7 +5753,9 @@ function resolveTableRef(model, dialect) {
5669
5753
  return buildTableReference(schema, tableName, dialect);
5670
5754
  }
5671
5755
  function findRelationField(model, fieldName) {
5672
- return model.fields.find((f) => f.name === fieldName && f.isRelation);
5756
+ const field = getFieldIndices(model).allFieldsByName.get(fieldName);
5757
+ if (!field || !field.isRelation) return void 0;
5758
+ return field;
5673
5759
  }
5674
5760
  function nextJoinAlias(ctx) {
5675
5761
  let alias;
@@ -5696,7 +5782,7 @@ function resolveRelationOrderByChain(relationFieldName, value, currentModel, cur
5696
5782
  `Relation field '${relationFieldName}' not found on model ${currentModel.name}`
5697
5783
  );
5698
5784
  }
5699
- const relatedModel = getModelByName(ctx.schemas, field.relatedModel);
5785
+ const relatedModel = ctx.modelMap.get(field.relatedModel);
5700
5786
  if (!relatedModel) {
5701
5787
  throw new Error(
5702
5788
  `Related model '${field.relatedModel}' not found for relation '${relationFieldName}'`
@@ -5762,12 +5848,14 @@ function buildOrderByWithRelations(orderBy, alias, dialect, model, schemas) {
5762
5848
  const relationSet = getRelationFieldSet(model);
5763
5849
  const scalarSet = getScalarFieldSet(model);
5764
5850
  const orderFragments = [];
5851
+ const modelMap = /* @__PURE__ */ new Map();
5852
+ for (const m of schemas) modelMap.set(m.name, m);
5765
5853
  const ctx = {
5766
- schemas,
5767
5854
  dialect,
5768
5855
  joins: [],
5769
5856
  usedAliases: /* @__PURE__ */ new Set(),
5770
- aliasCounter: { value: 0 }
5857
+ aliasCounter: { value: 0 },
5858
+ modelMap
5771
5859
  };
5772
5860
  for (const [fieldName, value] of expanded) {
5773
5861
  if (scalarSet.has(fieldName)) {
@@ -5822,11 +5910,11 @@ function mapFirstOrderByByField(existing) {
5822
5910
  return m;
5823
5911
  }
5824
5912
  function buildPostgresDistinctOrderBy(distinctFields, existing) {
5825
- var _a3;
5913
+ var _a4;
5826
5914
  const firstByField = mapFirstOrderByByField(existing);
5827
5915
  const next = [];
5828
5916
  for (const f of distinctFields) {
5829
- next.push((_a3 = firstByField.get(f)) != null ? _a3 : { [f]: "asc" });
5917
+ next.push((_a4 = firstByField.get(f)) != null ? _a4 : { [f]: "asc" });
5830
5918
  }
5831
5919
  const distinctSet = new Set(distinctFields);
5832
5920
  for (const obj of existing) {
@@ -6866,10 +6954,10 @@ function isPrismaMethod(v) {
6866
6954
  return v === "findMany" || v === "findFirst" || v === "findUnique" || v === "aggregate" || v === "groupBy" || v === "count";
6867
6955
  }
6868
6956
  function resolveMethod(directive) {
6869
- var _a3, _b;
6957
+ var _a4, _b;
6870
6958
  const m = directive == null ? void 0 : directive.method;
6871
6959
  if (isPrismaMethod(m)) return m;
6872
- const pm = (_b = (_a3 = directive == null ? void 0 : directive.query) == null ? void 0 : _a3.processed) == null ? void 0 : _b.method;
6960
+ const pm = (_b = (_a4 = directive == null ? void 0 : directive.query) == null ? void 0 : _a4.processed) == null ? void 0 : _b.method;
6873
6961
  if (isPrismaMethod(pm)) return pm;
6874
6962
  return "findMany";
6875
6963
  }
@@ -7034,7 +7122,7 @@ function extractIncludeSpec2(processed, modelDef) {
7034
7122
  return includeSpec;
7035
7123
  }
7036
7124
  function buildAndNormalizeSql(args) {
7037
- var _a3;
7125
+ var _a4;
7038
7126
  const {
7039
7127
  method,
7040
7128
  processed,
@@ -7060,7 +7148,7 @@ function buildAndNormalizeSql(args) {
7060
7148
  sqlResult.paramMappings,
7061
7149
  dialect
7062
7150
  );
7063
- const includeSpec = (_a3 = sqlResult.includeSpec && isPlainObject(sqlResult.includeSpec) ? sqlResult.includeSpec : null) != null ? _a3 : extractIncludeSpec2(processed, modelDef);
7151
+ const includeSpec = (_a4 = sqlResult.includeSpec && isPlainObject(sqlResult.includeSpec) ? sqlResult.includeSpec : null) != null ? _a4 : extractIncludeSpec2(processed, modelDef);
7064
7152
  return {
7065
7153
  sql: normalized.sql,
7066
7154
  paramMappings: normalized.paramMappings,
@@ -7085,8 +7173,8 @@ function finalizeDirective(args) {
7085
7173
  skipWhereIn
7086
7174
  } = args;
7087
7175
  const params = normalizedMappings.map((m) => {
7088
- var _a3;
7089
- return (_a3 = m.value) != null ? _a3 : void 0;
7176
+ var _a4;
7177
+ return (_a4 = m.value) != null ? _a4 : void 0;
7090
7178
  });
7091
7179
  validateParamConsistencyByDialect(normalizedSql, params, dialect);
7092
7180
  const { staticParams, dynamicKeys, paramOrder } = buildParamsFromMappings(normalizedMappings);
@@ -7556,21 +7644,13 @@ function makeAlias(name) {
7556
7644
  const safe = /^[a-z_]/.test(base) ? base : `_${base}`;
7557
7645
  return SQL_RESERVED_WORDS.has(safe) ? `${safe}_t` : safe;
7558
7646
  }
7559
- function canonicalizeReplacer(key, value) {
7647
+ function bigintReplacer(_key, value) {
7560
7648
  if (typeof value === "bigint") return `__bigint__${value.toString()}`;
7561
- if (value && typeof value === "object" && !Array.isArray(value)) {
7562
- const obj = value;
7563
- const sorted = {};
7564
- for (const k of Object.keys(obj).sort()) {
7565
- sorted[k] = obj[k];
7566
- }
7567
- return sorted;
7568
- }
7569
7649
  return value;
7570
7650
  }
7571
7651
  function canonicalizeQuery(modelName, method, args, dialect) {
7572
7652
  if (!args) return `${dialect}:${modelName}:${method}:{}`;
7573
- return `${dialect}:${modelName}:${method}:${JSON.stringify(args, canonicalizeReplacer)}`;
7653
+ return `${dialect}:${modelName}:${method}:${JSON.stringify(args, bigintReplacer)}`;
7574
7654
  }
7575
7655
  function buildSQLFull(model, models, method, args, dialect) {
7576
7656
  const tableName = buildTableReference(
@@ -7754,10 +7834,10 @@ function getRowTransformer(method) {
7754
7834
 
7755
7835
  // src/result-transformers.ts
7756
7836
  function transformQueryResults(method, results) {
7757
- var _a3, _b;
7837
+ var _a4, _b;
7758
7838
  if (method === "findFirst" || method === "findUnique") {
7759
7839
  if (Array.isArray(results)) {
7760
- return (_a3 = results[0]) != null ? _a3 : null;
7840
+ return (_a4 = results[0]) != null ? _a4 : null;
7761
7841
  }
7762
7842
  }
7763
7843
  if (method === "aggregate") {
@@ -7866,10 +7946,10 @@ function createTransactionExecutor(deps) {
7866
7946
  function isListField2(field) {
7867
7947
  return typeof field.type === "string" && field.type.endsWith("[]");
7868
7948
  }
7869
- function resolveRelation(model, relName, allModels) {
7949
+ function resolveRelation(model, relName, allModels, modelMap) {
7870
7950
  const field = model.fields.find((f) => f.name === relName);
7871
7951
  if (!field || !field.isRelation || !field.relatedModel) return null;
7872
- const relModel = allModels.find((m) => m.name === field.relatedModel);
7952
+ const relModel = modelMap ? modelMap.get(field.relatedModel) : allModels.find((m) => m.name === field.relatedModel);
7873
7953
  if (!relModel) return null;
7874
7954
  return { field, relModel };
7875
7955
  }
@@ -7901,23 +7981,11 @@ function buildWhereInSegment(name, relArgs, field, relModel) {
7901
7981
  perParentSkip: pagination.skip
7902
7982
  };
7903
7983
  }
7904
- function deepClone(obj) {
7905
- if (obj === null || typeof obj !== "object") return obj;
7906
- if (obj instanceof Date) return new Date(obj.getTime());
7907
- if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags);
7908
- if (Array.isArray(obj)) return obj.map((item) => deepClone(item));
7909
- const cloned = {};
7910
- for (const key in obj) {
7911
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
7912
- cloned[key] = deepClone(obj[key]);
7913
- }
7914
- }
7915
- return cloned;
7916
- }
7917
7984
  function removeRelationsFromArgs(args, names) {
7918
7985
  if (!args) return args;
7919
- const filtered = deepClone(args);
7986
+ const filtered = __spreadValues({}, args);
7920
7987
  if (filtered.include && isPlainObject(filtered.include)) {
7988
+ filtered.include = __spreadValues({}, filtered.include);
7921
7989
  for (const name of names) {
7922
7990
  delete filtered.include[name];
7923
7991
  }
@@ -7926,6 +7994,7 @@ function removeRelationsFromArgs(args, names) {
7926
7994
  }
7927
7995
  }
7928
7996
  if (filtered.select && isPlainObject(filtered.select)) {
7997
+ filtered.select = __spreadValues({}, filtered.select);
7929
7998
  for (const name of names) {
7930
7999
  delete filtered.select[name];
7931
8000
  }
@@ -7970,14 +8039,28 @@ function planQueryStrategy(params) {
7970
8039
  if (dialect === "postgres") {
7971
8040
  const includeSpec = extractIncludeSpec3(args, model);
7972
8041
  if (Object.keys(includeSpec).length > 0) {
8042
+ const modelMap2 = getOrCreateModelMap(allModels);
7973
8043
  isPlainObject(args) && "take" in args && args.take != null;
7974
8044
  const takeValue = isPlainObject(args) && typeof args.take === "number" ? args.take : null;
7975
- const canFlatJoin = canUseFlatJoinForAll(includeSpec, model, allModels);
7976
- canUseLateralJoin(includeSpec, model, allModels);
8045
+ const canFlatJoin = canUseFlatJoinForAll(
8046
+ includeSpec,
8047
+ model,
8048
+ allModels,
8049
+ false,
8050
+ modelMap2
8051
+ );
8052
+ canUseLateralJoin(
8053
+ includeSpec,
8054
+ model,
8055
+ allModels,
8056
+ modelMap2
8057
+ );
7977
8058
  const hasChildPag = hasChildPaginationAnywhere(
7978
8059
  includeSpec,
7979
8060
  model,
7980
- allModels
8061
+ allModels,
8062
+ 0,
8063
+ modelMap2
7981
8064
  );
7982
8065
  const strategy = pickIncludeStrategy({
7983
8066
  includeSpec,
@@ -7988,7 +8071,8 @@ function planQueryStrategy(params) {
7988
8071
  takeValue,
7989
8072
  canFlatJoin,
7990
8073
  hasChildPagination: hasChildPag,
7991
- debug
8074
+ debug,
8075
+ modelMap: modelMap2
7992
8076
  });
7993
8077
  if (debug) {
7994
8078
  console.log(` [planner] ${model.name}: strategy=${strategy}`);
@@ -7998,10 +8082,11 @@ function planQueryStrategy(params) {
7998
8082
  }
7999
8083
  }
8000
8084
  }
8085
+ const modelMap = getOrCreateModelMap(allModels);
8001
8086
  const whereInSegments = [];
8002
8087
  const toRemove = /* @__PURE__ */ new Set();
8003
8088
  for (const entry of entries) {
8004
- const resolved = resolveRelation(model, entry.name, allModels);
8089
+ const resolved = resolveRelation(model, entry.name, allModels, modelMap);
8005
8090
  if (!resolved) continue;
8006
8091
  const segment = buildWhereInSegment(
8007
8092
  entry.name,
@@ -8264,7 +8349,7 @@ function needsPerParentPagination(segment) {
8264
8349
  return segment.isList && (segment.perParentSkip != null && segment.perParentSkip > 0 || segment.perParentTake != null);
8265
8350
  }
8266
8351
  function stitchChildrenToParents(children, segment, parentKeyIndex) {
8267
- var _a3;
8352
+ var _a4;
8268
8353
  const grouped = /* @__PURE__ */ new Map();
8269
8354
  for (const child of children) {
8270
8355
  const childKey = child[segment.fkFieldName];
@@ -8295,20 +8380,28 @@ function stitchChildrenToParents(children, segment, parentKeyIndex) {
8295
8380
  parent[segment.relationName].push(child);
8296
8381
  }
8297
8382
  } else {
8298
- parent[segment.relationName] = (_a3 = sliced[0]) != null ? _a3 : null;
8383
+ parent[segment.relationName] = (_a4 = sliced[0]) != null ? _a4 : null;
8299
8384
  }
8300
8385
  }
8301
8386
  }
8302
8387
  }
8303
8388
  function buildChildArgs(relArgs, fkFieldName, uniqueIds, stripPagination) {
8304
- const base = relArgs === true || typeof relArgs !== "object" || relArgs === null ? {} : __spreadValues({}, relArgs);
8305
- if (stripPagination) {
8306
- delete base.take;
8307
- delete base.skip;
8389
+ const isObject = relArgs !== true && typeof relArgs === "object" && relArgs !== null;
8390
+ const source = isObject ? relArgs : null;
8391
+ const base = {};
8392
+ if (source) {
8393
+ if (source.select !== void 0) base.select = source.select;
8394
+ if (source.include !== void 0) base.include = source.include;
8395
+ if (source.orderBy !== void 0) base.orderBy = source.orderBy;
8396
+ if (!stripPagination) {
8397
+ if (source.take !== void 0) base.take = source.take;
8398
+ if (source.skip !== void 0) base.skip = source.skip;
8399
+ }
8400
+ if (source.cursor !== void 0) base.cursor = source.cursor;
8401
+ if (source.distinct !== void 0) base.distinct = source.distinct;
8308
8402
  }
8309
- const existingWhere = base.where;
8310
8403
  const inCondition = { [fkFieldName]: { in: uniqueIds } };
8311
- base.where = existingWhere ? { AND: [existingWhere, inCondition] } : inCondition;
8404
+ base.where = source && source.where ? { AND: [source.where, inCondition] } : inCondition;
8312
8405
  return base;
8313
8406
  }
8314
8407
  function ensureFkInSelect(childArgs, fkFieldName) {
@@ -8820,9 +8913,9 @@ function wrapQueryForMethod(method, cteName, resultAlias) {
8820
8913
  }
8821
8914
  }
8822
8915
  function isAllCountQueries(queries, keys) {
8823
- var _a3;
8916
+ var _a4;
8824
8917
  for (const key of keys) {
8825
- if (((_a3 = queries[key]) == null ? void 0 : _a3.method) !== "count") return false;
8918
+ if (((_a4 = queries[key]) == null ? void 0 : _a4.method) !== "count") return false;
8826
8919
  }
8827
8920
  return true;
8828
8921
  }
@@ -8965,8 +9058,8 @@ function buildMergedCountBatchSql(queries, keys, aliasesByKey, modelMap, models,
8965
9058
  const fromSql = rewrittenSubs.join(" CROSS JOIN ");
8966
9059
  const sql = `SELECT ${selectParts.join(", ")} FROM ${fromSql}`;
8967
9060
  const aliases = keys.map((k) => {
8968
- var _a3;
8969
- return (_a3 = aliasesByKey.get(k)) != null ? _a3 : "";
9061
+ var _a4;
9062
+ return (_a4 = aliasesByKey.get(k)) != null ? _a4 : "";
8970
9063
  });
8971
9064
  return { sql, params: finalParams, keys, aliases };
8972
9065
  }
@@ -9324,11 +9417,11 @@ function parseBatchValue(rawValue, method, modelName, modelMap) {
9324
9417
  }
9325
9418
  }
9326
9419
  function parseBatchResults(row, keys, queries, aliases, modelMap) {
9327
- var _a3;
9420
+ var _a4;
9328
9421
  const results = {};
9329
9422
  for (let i = 0; i < keys.length; i++) {
9330
9423
  const key = keys[i];
9331
- const columnKey = (_a3 = aliases == null ? void 0 : aliases[i]) != null ? _a3 : key;
9424
+ const columnKey = (_a4 = aliases == null ? void 0 : aliases[i]) != null ? _a4 : key;
9332
9425
  const rawValue = row[columnKey];
9333
9426
  const query = queries[key];
9334
9427
  results[key] = parseBatchValue(
@@ -9450,8 +9543,8 @@ var createCoreReducer = (config) => {
9450
9543
  return {
9451
9544
  processRow,
9452
9545
  getParent: (key) => {
9453
- var _a3;
9454
- return (_a3 = parentMap.get(key)) != null ? _a3 : null;
9546
+ var _a4;
9547
+ return (_a4 = parentMap.get(key)) != null ? _a4 : null;
9455
9548
  },
9456
9549
  getAllParents: () => Array.from(parentMap.values()),
9457
9550
  getParentMap: () => parentMap