prisma-sql 1.66.1 → 1.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,7 +3,6 @@ import { convertDMMFToModels, isDynamicParameter, extractDynamicName } from '@de
3
3
  var __defProp = Object.defineProperty;
4
4
  var __defProps = Object.defineProperties;
5
5
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
6
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
8
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
@@ -23,13 +22,6 @@ var __spreadValues = (a, b) => {
23
22
  return a;
24
23
  };
25
24
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
26
- var __esm = (fn, res) => function __init() {
27
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
28
- };
29
- var __export = (target, all) => {
30
- for (var name in all)
31
- __defProp(target, name, { get: all[name], enumerable: true });
32
- };
33
25
  var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
34
26
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
35
27
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
@@ -64,6 +56,7 @@ var __async = (__this, __arguments, generator) => {
64
56
  };
65
57
 
66
58
  // src/utils/normalize-value.ts
59
+ var MAX_DEPTH = 20;
67
60
  function normalizeValue(value, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {
68
61
  if (depth > MAX_DEPTH) {
69
62
  throw new Error(`Max normalization depth exceeded (${MAX_DEPTH} levels)`);
@@ -117,14 +110,9 @@ function normalizeObjectValue(value, seen, depth) {
117
110
  seen.delete(obj);
118
111
  return out;
119
112
  }
120
- var MAX_DEPTH;
121
- var init_normalize_value = __esm({
122
- "src/utils/normalize-value.ts"() {
123
- MAX_DEPTH = 20;
124
- }
125
- });
126
113
 
127
114
  // src/sql-builder-dialect.ts
115
+ var globalDialect = "postgres";
128
116
  function setGlobalDialect(dialect) {
129
117
  if (dialect !== "postgres" && dialect !== "sqlite") {
130
118
  throw new Error(
@@ -303,175 +291,162 @@ function prepareArrayParam(value, dialect) {
303
291
  }
304
292
  return JSON.stringify(value.map((v) => normalizeValue(v)));
305
293
  }
306
- var globalDialect;
307
- var init_sql_builder_dialect = __esm({
308
- "src/sql-builder-dialect.ts"() {
309
- init_normalize_value();
310
- globalDialect = "postgres";
311
- }
312
- });
313
294
 
314
295
  // src/builder/shared/constants.ts
315
- var IS_PRODUCTION, SQL_SEPARATORS, ALIAS_FORBIDDEN_KEYWORDS, SQL_KEYWORDS, SQL_RESERVED_WORDS, DEFAULT_WHERE_CLAUSE, SPECIAL_FIELDS, SQL_TEMPLATES, SCHEMA_PREFIXES, Ops, LogicalOps, RelationFilters, Modes, Wildcards, REGEX_CACHE, LIMITS, AGGREGATE_PREFIXES;
316
- var init_constants = __esm({
317
- "src/builder/shared/constants.ts"() {
318
- IS_PRODUCTION = process.env.NODE_ENV === "production";
319
- SQL_SEPARATORS = Object.freeze({
320
- FIELD_LIST: ", ",
321
- CONDITION_AND: " AND ",
322
- CONDITION_OR: " OR ",
323
- ORDER_BY: ", "
324
- });
325
- ALIAS_FORBIDDEN_KEYWORDS = /* @__PURE__ */ new Set([
326
- "select",
327
- "from",
328
- "where",
329
- "having",
330
- "order",
331
- "group",
332
- "limit",
333
- "offset",
334
- "join",
335
- "inner",
336
- "left",
337
- "right",
338
- "outer",
339
- "cross",
340
- "full",
341
- "and",
342
- "or",
343
- "not",
344
- "by",
345
- "as",
346
- "on",
347
- "union",
348
- "intersect",
349
- "except",
350
- "case",
351
- "when",
352
- "then",
353
- "else",
354
- "end"
355
- ]);
356
- SQL_KEYWORDS = /* @__PURE__ */ new Set([
357
- ...ALIAS_FORBIDDEN_KEYWORDS,
358
- "user",
359
- "users",
360
- "table",
361
- "column",
362
- "index",
363
- "values",
364
- "in",
365
- "like",
366
- "between",
367
- "is",
368
- "exists",
369
- "null",
370
- "true",
371
- "false",
372
- "all",
373
- "any",
374
- "some",
375
- "update",
376
- "insert",
377
- "delete",
378
- "create",
379
- "drop",
380
- "alter",
381
- "truncate",
382
- "grant",
383
- "revoke",
384
- "exec",
385
- "execute"
386
- ]);
387
- SQL_RESERVED_WORDS = SQL_KEYWORDS;
388
- DEFAULT_WHERE_CLAUSE = "1=1";
389
- SPECIAL_FIELDS = Object.freeze({
390
- ID: "id"
391
- });
392
- SQL_TEMPLATES = Object.freeze({
393
- PUBLIC_SCHEMA: "public",
394
- WHERE: "WHERE",
395
- SELECT: "SELECT",
396
- FROM: "FROM",
397
- ORDER_BY: "ORDER BY",
398
- GROUP_BY: "GROUP BY",
399
- HAVING: "HAVING",
400
- LIMIT: "LIMIT",
401
- OFFSET: "OFFSET",
402
- COUNT_ALL: "COUNT(*)",
403
- AS: "AS",
404
- DISTINCT_ON: "DISTINCT ON",
405
- IS_NULL: "IS NULL",
406
- IS_NOT_NULL: "IS NOT NULL",
407
- LIKE: "LIKE",
408
- AND: "AND",
409
- OR: "OR",
410
- NOT: "NOT"
411
- });
412
- SCHEMA_PREFIXES = Object.freeze({
413
- INTERNAL: "@",
414
- COMMENT: "//"
415
- });
416
- Ops = Object.freeze({
417
- EQUALS: "equals",
418
- NOT: "not",
419
- GT: "gt",
420
- GTE: "gte",
421
- LT: "lt",
422
- LTE: "lte",
423
- IN: "in",
424
- NOT_IN: "notIn",
425
- CONTAINS: "contains",
426
- STARTS_WITH: "startsWith",
427
- ENDS_WITH: "endsWith",
428
- HAS: "has",
429
- HAS_SOME: "hasSome",
430
- HAS_EVERY: "hasEvery",
431
- IS_EMPTY: "isEmpty",
432
- PATH: "path",
433
- STRING_CONTAINS: "string_contains",
434
- STRING_STARTS_WITH: "string_starts_with",
435
- STRING_ENDS_WITH: "string_ends_with"
436
- });
437
- LogicalOps = Object.freeze({
438
- AND: "AND",
439
- OR: "OR",
440
- NOT: "NOT"
441
- });
442
- RelationFilters = Object.freeze({
443
- SOME: "some",
444
- EVERY: "every",
445
- NONE: "none"
446
- });
447
- Modes = Object.freeze({
448
- INSENSITIVE: "insensitive",
449
- DEFAULT: "default"
450
- });
451
- Wildcards = Object.freeze({
452
- [Ops.CONTAINS]: (v) => `%${v}%`,
453
- [Ops.STARTS_WITH]: (v) => `${v}%`,
454
- [Ops.ENDS_WITH]: (v) => `%${v}`
455
- });
456
- REGEX_CACHE = {
457
- PARAM_PLACEHOLDER: /\$(\d+)/g,
458
- VALID_IDENTIFIER: /^[a-z_][a-z0-9_]*$/
459
- };
460
- LIMITS = Object.freeze({
461
- MAX_QUERY_DEPTH: 50,
462
- MAX_ARRAY_SIZE: 1e4,
463
- MAX_STRING_LENGTH: 1e4,
464
- MAX_HAVING_DEPTH: 50
465
- });
466
- AGGREGATE_PREFIXES = /* @__PURE__ */ new Set([
467
- "_count",
468
- "_sum",
469
- "_avg",
470
- "_min",
471
- "_max"
472
- ]);
473
- }
296
+ var IS_PRODUCTION = process.env.NODE_ENV === "production";
297
+ var SQL_SEPARATORS = Object.freeze({
298
+ FIELD_LIST: ", ",
299
+ CONDITION_AND: " AND ",
300
+ CONDITION_OR: " OR ",
301
+ ORDER_BY: ", "
302
+ });
303
+ var ALIAS_FORBIDDEN_KEYWORDS = /* @__PURE__ */ new Set([
304
+ "select",
305
+ "from",
306
+ "where",
307
+ "having",
308
+ "order",
309
+ "group",
310
+ "limit",
311
+ "offset",
312
+ "join",
313
+ "inner",
314
+ "left",
315
+ "right",
316
+ "outer",
317
+ "cross",
318
+ "full",
319
+ "and",
320
+ "or",
321
+ "not",
322
+ "by",
323
+ "as",
324
+ "on",
325
+ "union",
326
+ "intersect",
327
+ "except",
328
+ "case",
329
+ "when",
330
+ "then",
331
+ "else",
332
+ "end"
333
+ ]);
334
+ var SQL_KEYWORDS = /* @__PURE__ */ new Set([
335
+ ...ALIAS_FORBIDDEN_KEYWORDS,
336
+ "user",
337
+ "users",
338
+ "table",
339
+ "column",
340
+ "index",
341
+ "values",
342
+ "in",
343
+ "like",
344
+ "between",
345
+ "is",
346
+ "exists",
347
+ "null",
348
+ "true",
349
+ "false",
350
+ "all",
351
+ "any",
352
+ "some",
353
+ "update",
354
+ "insert",
355
+ "delete",
356
+ "create",
357
+ "drop",
358
+ "alter",
359
+ "truncate",
360
+ "grant",
361
+ "revoke",
362
+ "exec",
363
+ "execute"
364
+ ]);
365
+ var SQL_RESERVED_WORDS = SQL_KEYWORDS;
366
+ var DEFAULT_WHERE_CLAUSE = "1=1";
367
+ var SPECIAL_FIELDS = Object.freeze({
368
+ ID: "id"
369
+ });
370
+ var SQL_TEMPLATES = Object.freeze({
371
+ PUBLIC_SCHEMA: "public",
372
+ WHERE: "WHERE",
373
+ SELECT: "SELECT",
374
+ FROM: "FROM",
375
+ ORDER_BY: "ORDER BY",
376
+ GROUP_BY: "GROUP BY",
377
+ HAVING: "HAVING",
378
+ LIMIT: "LIMIT",
379
+ OFFSET: "OFFSET",
380
+ COUNT_ALL: "COUNT(*)",
381
+ AS: "AS",
382
+ DISTINCT_ON: "DISTINCT ON",
383
+ IS_NULL: "IS NULL",
384
+ IS_NOT_NULL: "IS NOT NULL",
385
+ LIKE: "LIKE",
386
+ AND: "AND",
387
+ OR: "OR",
388
+ NOT: "NOT"
389
+ });
390
+ var SCHEMA_PREFIXES = Object.freeze({
391
+ INTERNAL: "@",
392
+ COMMENT: "//"
393
+ });
394
+ var Ops = Object.freeze({
395
+ EQUALS: "equals",
396
+ NOT: "not",
397
+ GT: "gt",
398
+ GTE: "gte",
399
+ LT: "lt",
400
+ LTE: "lte",
401
+ IN: "in",
402
+ NOT_IN: "notIn",
403
+ CONTAINS: "contains",
404
+ STARTS_WITH: "startsWith",
405
+ ENDS_WITH: "endsWith",
406
+ HAS: "has",
407
+ HAS_SOME: "hasSome",
408
+ HAS_EVERY: "hasEvery",
409
+ IS_EMPTY: "isEmpty",
410
+ PATH: "path",
411
+ STRING_CONTAINS: "string_contains",
412
+ STRING_STARTS_WITH: "string_starts_with",
413
+ STRING_ENDS_WITH: "string_ends_with"
414
+ });
415
+ var LogicalOps = Object.freeze({
416
+ AND: "AND",
417
+ OR: "OR",
418
+ NOT: "NOT"
419
+ });
420
+ var RelationFilters = Object.freeze({
421
+ SOME: "some",
422
+ EVERY: "every",
423
+ NONE: "none"
474
424
  });
425
+ var Modes = Object.freeze({
426
+ INSENSITIVE: "insensitive",
427
+ DEFAULT: "default"
428
+ });
429
+ var Wildcards = Object.freeze({
430
+ [Ops.CONTAINS]: (v) => `%${v}%`,
431
+ [Ops.STARTS_WITH]: (v) => `${v}%`,
432
+ [Ops.ENDS_WITH]: (v) => `%${v}`
433
+ });
434
+ var REGEX_CACHE = {
435
+ VALID_IDENTIFIER: /^[a-z_][a-z0-9_]*$/
436
+ };
437
+ var LIMITS = Object.freeze({
438
+ MAX_QUERY_DEPTH: 50,
439
+ MAX_ARRAY_SIZE: 1e4,
440
+ MAX_STRING_LENGTH: 1e4,
441
+ MAX_HAVING_DEPTH: 50
442
+ });
443
+ var AGGREGATE_PREFIXES = /* @__PURE__ */ new Set([
444
+ "_count",
445
+ "_sum",
446
+ "_avg",
447
+ "_min",
448
+ "_max"
449
+ ]);
475
450
 
476
451
  // src/builder/shared/validators/type-guards.ts
477
452
  function isNotNullish(value) {
@@ -515,12 +490,16 @@ function hasRequiredKeywords(sql) {
515
490
  const hasFrom = upper.includes("FROM");
516
491
  return hasSelect && hasFrom && upper.indexOf("SELECT") < upper.indexOf("FROM");
517
492
  }
518
- var init_type_guards = __esm({
519
- "src/builder/shared/validators/type-guards.ts"() {
520
- }
521
- });
522
493
 
523
494
  // src/builder/shared/errors.ts
495
+ var SqlBuilderError = class extends Error {
496
+ constructor(message, code, context) {
497
+ super(message);
498
+ this.name = "SqlBuilderError";
499
+ this.code = code;
500
+ this.context = context;
501
+ }
502
+ };
524
503
  function createError(message, ctx, code = "VALIDATION_ERROR") {
525
504
  const parts = [message];
526
505
  if (isNonEmptyArray(ctx.path)) {
@@ -534,20 +513,6 @@ function createError(message, ctx, code = "VALIDATION_ERROR") {
534
513
  }
535
514
  return new SqlBuilderError(parts.join("\n"), code, ctx);
536
515
  }
537
- var SqlBuilderError;
538
- var init_errors = __esm({
539
- "src/builder/shared/errors.ts"() {
540
- init_type_guards();
541
- SqlBuilderError = class extends Error {
542
- constructor(message, code, context) {
543
- super(message);
544
- this.name = "SqlBuilderError";
545
- this.code = code;
546
- this.context = context;
547
- }
548
- };
549
- }
550
- });
551
516
 
552
517
  // src/builder/shared/validators/sql-validators.ts
553
518
  function isValidWhereClause(clause) {
@@ -582,6 +547,7 @@ function parseDollarNumber(sql, start) {
582
547
  if (!hasDigit || num <= 0) return { next: i, num: 0 };
583
548
  return { next: i, num };
584
549
  }
550
+ var MAX_PARAMS = 32767;
585
551
  function scanDollarPlaceholders(sql, markUpTo) {
586
552
  if (markUpTo > MAX_PARAMS) {
587
553
  throw new Error(`Parameter count ${markUpTo} exceeds maximum ${MAX_PARAMS}`);
@@ -688,16 +654,10 @@ function needsQuoting(identifier) {
688
654
  if (SQL_KEYWORDS.has(identifier.toLowerCase())) return true;
689
655
  return false;
690
656
  }
691
- var MAX_PARAMS;
692
- var init_sql_validators = __esm({
693
- "src/builder/shared/validators/sql-validators.ts"() {
694
- init_constants();
695
- init_type_guards();
696
- MAX_PARAMS = 32767;
697
- }
698
- });
699
657
 
700
658
  // src/builder/shared/sql-utils.ts
659
+ var COL_EXPR_CACHE = /* @__PURE__ */ new WeakMap();
660
+ var COL_WITH_ALIAS_CACHE = /* @__PURE__ */ new WeakMap();
701
661
  function containsControlChars(s) {
702
662
  for (let i = 0; i < s.length; i++) {
703
663
  const code = s.charCodeAt(i);
@@ -723,6 +683,7 @@ function isIdentCharCode(c) {
723
683
  function isIdentStartCharCode(c) {
724
684
  return c >= 65 && c <= 90 || c >= 97 && c <= 122 || c === 95;
725
685
  }
686
+ var MAX_PARSE_ITERATIONS = 1e4;
726
687
  function parseQuotedPart(input, start) {
727
688
  const n = input.length;
728
689
  let i = start + 1;
@@ -1022,20 +983,9 @@ function normalizeKeyList(input) {
1022
983
  const s = String(input).trim();
1023
984
  return s.length > 0 ? [s] : [];
1024
985
  }
1025
- var COL_EXPR_CACHE, COL_WITH_ALIAS_CACHE, MAX_PARSE_ITERATIONS;
1026
- var init_sql_utils = __esm({
1027
- "src/builder/shared/sql-utils.ts"() {
1028
- init_sql_validators();
1029
- init_type_guards();
1030
- init_model_field_cache();
1031
- init_constants();
1032
- COL_EXPR_CACHE = /* @__PURE__ */ new WeakMap();
1033
- COL_WITH_ALIAS_CACHE = /* @__PURE__ */ new WeakMap();
1034
- MAX_PARSE_ITERATIONS = 1e4;
1035
- }
1036
- });
1037
986
 
1038
987
  // src/builder/shared/model-field-cache.ts
988
+ var FIELD_INDICES_CACHE = /* @__PURE__ */ new WeakMap();
1039
989
  function normalizeField(field) {
1040
990
  return field;
1041
991
  }
@@ -1124,13 +1074,6 @@ function maybeParseJson(value, jsonSet, fieldName) {
1124
1074
  return value;
1125
1075
  }
1126
1076
  }
1127
- var FIELD_INDICES_CACHE;
1128
- var init_model_field_cache = __esm({
1129
- "src/builder/shared/model-field-cache.ts"() {
1130
- init_sql_utils();
1131
- FIELD_INDICES_CACHE = /* @__PURE__ */ new WeakMap();
1132
- }
1133
- });
1134
1077
 
1135
1078
  // src/builder/joins.ts
1136
1079
  function isRelationField(fieldName, model) {
@@ -1189,15 +1132,6 @@ function joinCondition(field, parentModel, childModel, parentAlias, childAlias)
1189
1132
  function getModelByName(schemas, name) {
1190
1133
  return schemas.find((m) => m.name === name);
1191
1134
  }
1192
- var init_joins = __esm({
1193
- "src/builder/joins.ts"() {
1194
- init_constants();
1195
- init_errors();
1196
- init_model_field_cache();
1197
- init_sql_utils();
1198
- init_type_guards();
1199
- }
1200
- });
1201
1135
  function normalizeIntLike(name, v, opts = {}) {
1202
1136
  var _a, _b;
1203
1137
  if (!isNotNullish(v)) return void 0;
@@ -1218,11 +1152,6 @@ function normalizeIntLike(name, v, opts = {}) {
1218
1152
  }
1219
1153
  return v;
1220
1154
  }
1221
- var init_int_like = __esm({
1222
- "src/builder/shared/int-like.ts"() {
1223
- init_type_guards();
1224
- }
1225
- });
1226
1155
  function scopeName(scope, dynamicName) {
1227
1156
  const s = String(scope).trim();
1228
1157
  const dn = String(dynamicName).trim();
@@ -1232,16 +1161,77 @@ function scopeName(scope, dynamicName) {
1232
1161
  function addAutoScoped(params, value, scope) {
1233
1162
  if (isDynamicParameter(value)) {
1234
1163
  const dn = extractDynamicName(value);
1164
+ console.log(`[PARAM] ${scope} = ${JSON.stringify(value)}`);
1235
1165
  return params.add(void 0, scopeName(scope, dn));
1236
1166
  }
1237
1167
  return params.add(value);
1238
1168
  }
1239
- var init_dynamic_params = __esm({
1240
- "src/builder/shared/dynamic-params.ts"() {
1241
- }
1242
- });
1243
1169
 
1244
1170
  // src/builder/shared/order-by-utils.ts
1171
+ var flipNulls = (v) => {
1172
+ const s = String(v).toLowerCase();
1173
+ if (s === "first") return "last";
1174
+ if (s === "last") return "first";
1175
+ return v;
1176
+ };
1177
+ var flipSortString = (v) => {
1178
+ if (typeof v !== "string") return v;
1179
+ const s = v.toLowerCase();
1180
+ if (s === "asc") return "desc";
1181
+ if (s === "desc") return "asc";
1182
+ return v;
1183
+ };
1184
+ var getNextSort = (sortRaw) => {
1185
+ if (typeof sortRaw !== "string") return sortRaw;
1186
+ const s = sortRaw.toLowerCase();
1187
+ if (s === "asc") return "desc";
1188
+ if (s === "desc") return "asc";
1189
+ return sortRaw;
1190
+ };
1191
+ var flipObjectSort = (obj) => {
1192
+ const out = __spreadValues({}, obj);
1193
+ const hasSort = Object.prototype.hasOwnProperty.call(obj, "sort");
1194
+ const hasDirection = Object.prototype.hasOwnProperty.call(obj, "direction");
1195
+ if (hasSort) {
1196
+ out.sort = getNextSort(obj.sort);
1197
+ } else if (hasDirection) {
1198
+ out.direction = getNextSort(obj.direction);
1199
+ } else {
1200
+ out.sort = getNextSort(obj.sort);
1201
+ }
1202
+ if (typeof obj.nulls === "string") {
1203
+ out.nulls = flipNulls(obj.nulls);
1204
+ }
1205
+ return out;
1206
+ };
1207
+ var flipValue = (v) => {
1208
+ if (typeof v === "string") return flipSortString(v);
1209
+ if (isPlainObject(v)) return flipObjectSort(v);
1210
+ return v;
1211
+ };
1212
+ var assertSingleFieldObject = (item) => {
1213
+ if (!isPlainObject(item)) {
1214
+ throw new Error("orderBy array entries must be objects");
1215
+ }
1216
+ const entries = Object.entries(item);
1217
+ if (entries.length !== 1) {
1218
+ throw new Error("orderBy array entries must have exactly one field");
1219
+ }
1220
+ return entries[0];
1221
+ };
1222
+ var flipOrderByArray = (orderBy) => {
1223
+ return orderBy.map((item) => {
1224
+ const [k, v] = assertSingleFieldObject(item);
1225
+ return { [k]: flipValue(v) };
1226
+ });
1227
+ };
1228
+ var flipOrderByObject = (orderBy) => {
1229
+ const out = {};
1230
+ for (const [k, v] of Object.entries(orderBy)) {
1231
+ out[k] = flipValue(v);
1232
+ }
1233
+ return out;
1234
+ };
1245
1235
  function reverseOrderByInput(orderBy) {
1246
1236
  if (!isNotNullish(orderBy)) return orderBy;
1247
1237
  if (Array.isArray(orderBy)) {
@@ -1252,6 +1242,14 @@ function reverseOrderByInput(orderBy) {
1252
1242
  }
1253
1243
  throw new Error("orderBy must be an object or array of objects");
1254
1244
  }
1245
+ var normalizePairs = (pairs, parseValue) => {
1246
+ return pairs.map(([field, rawValue]) => {
1247
+ const parsed = parseValue(rawValue, field);
1248
+ return {
1249
+ [field]: parsed.nulls !== void 0 ? { direction: parsed.direction, nulls: parsed.nulls } : parsed.direction
1250
+ };
1251
+ });
1252
+ };
1255
1253
  function normalizeOrderByInput(orderBy, parseValue) {
1256
1254
  if (!isNotNullish(orderBy)) return [];
1257
1255
  if (Array.isArray(orderBy)) {
@@ -1287,85 +1285,6 @@ function normalizeAndValidateOrderBy(orderBy, model, parseValue) {
1287
1285
  }
1288
1286
  return entries;
1289
1287
  }
1290
- var flipNulls, flipSortString, getNextSort, flipObjectSort, flipValue, assertSingleFieldObject, flipOrderByArray, flipOrderByObject, normalizePairs;
1291
- var init_order_by_utils = __esm({
1292
- "src/builder/shared/order-by-utils.ts"() {
1293
- init_type_guards();
1294
- init_model_field_cache();
1295
- flipNulls = (v) => {
1296
- const s = String(v).toLowerCase();
1297
- if (s === "first") return "last";
1298
- if (s === "last") return "first";
1299
- return v;
1300
- };
1301
- flipSortString = (v) => {
1302
- if (typeof v !== "string") return v;
1303
- const s = v.toLowerCase();
1304
- if (s === "asc") return "desc";
1305
- if (s === "desc") return "asc";
1306
- return v;
1307
- };
1308
- getNextSort = (sortRaw) => {
1309
- if (typeof sortRaw !== "string") return sortRaw;
1310
- const s = sortRaw.toLowerCase();
1311
- if (s === "asc") return "desc";
1312
- if (s === "desc") return "asc";
1313
- return sortRaw;
1314
- };
1315
- flipObjectSort = (obj) => {
1316
- const out = __spreadValues({}, obj);
1317
- const hasSort = Object.prototype.hasOwnProperty.call(obj, "sort");
1318
- const hasDirection = Object.prototype.hasOwnProperty.call(obj, "direction");
1319
- if (hasSort) {
1320
- out.sort = getNextSort(obj.sort);
1321
- } else if (hasDirection) {
1322
- out.direction = getNextSort(obj.direction);
1323
- } else {
1324
- out.sort = getNextSort(obj.sort);
1325
- }
1326
- if (typeof obj.nulls === "string") {
1327
- out.nulls = flipNulls(obj.nulls);
1328
- }
1329
- return out;
1330
- };
1331
- flipValue = (v) => {
1332
- if (typeof v === "string") return flipSortString(v);
1333
- if (isPlainObject(v)) return flipObjectSort(v);
1334
- return v;
1335
- };
1336
- assertSingleFieldObject = (item) => {
1337
- if (!isPlainObject(item)) {
1338
- throw new Error("orderBy array entries must be objects");
1339
- }
1340
- const entries = Object.entries(item);
1341
- if (entries.length !== 1) {
1342
- throw new Error("orderBy array entries must have exactly one field");
1343
- }
1344
- return entries[0];
1345
- };
1346
- flipOrderByArray = (orderBy) => {
1347
- return orderBy.map((item) => {
1348
- const [k, v] = assertSingleFieldObject(item);
1349
- return { [k]: flipValue(v) };
1350
- });
1351
- };
1352
- flipOrderByObject = (orderBy) => {
1353
- const out = {};
1354
- for (const [k, v] of Object.entries(orderBy)) {
1355
- out[k] = flipValue(v);
1356
- }
1357
- return out;
1358
- };
1359
- normalizePairs = (pairs, parseValue) => {
1360
- return pairs.map(([field, rawValue]) => {
1361
- const parsed = parseValue(rawValue, field);
1362
- return {
1363
- [field]: parsed.nulls !== void 0 ? { direction: parsed.direction, nulls: parsed.nulls } : parsed.direction
1364
- };
1365
- });
1366
- };
1367
- }
1368
- });
1369
1288
 
1370
1289
  // src/builder/shared/order-by-determinism.ts
1371
1290
  function findTiebreakerField(model) {
@@ -1398,15 +1317,9 @@ function ensureDeterministicOrderByInput(args) {
1398
1317
  if (hasTiebreaker(orderBy, parseValue, tiebreaker)) return orderBy;
1399
1318
  return addTiebreaker(orderBy, tiebreaker);
1400
1319
  }
1401
- var init_order_by_determinism = __esm({
1402
- "src/builder/shared/order-by-determinism.ts"() {
1403
- init_model_field_cache();
1404
- init_type_guards();
1405
- init_order_by_utils();
1406
- }
1407
- });
1408
1320
 
1409
1321
  // src/builder/shared/primary-key-utils.ts
1322
+ var FIELD_BY_NAME_CACHE = /* @__PURE__ */ new WeakMap();
1410
1323
  function normalizeField2(field) {
1411
1324
  return field;
1412
1325
  }
@@ -1442,13 +1355,6 @@ function getFieldByName(model, fieldName) {
1442
1355
  }
1443
1356
  return cache.get(fieldName);
1444
1357
  }
1445
- var FIELD_BY_NAME_CACHE;
1446
- var init_primary_key_utils = __esm({
1447
- "src/builder/shared/primary-key-utils.ts"() {
1448
- init_model_field_cache();
1449
- FIELD_BY_NAME_CACHE = /* @__PURE__ */ new WeakMap();
1450
- }
1451
- });
1452
1358
 
1453
1359
  // src/builder/shared/validators/field-assertions.ts
1454
1360
  function assertFieldExists(fieldName, model, context, path = []) {
@@ -1496,12 +1402,10 @@ function assertNumericField(model, fieldName, context) {
1496
1402
  }
1497
1403
  return field;
1498
1404
  }
1499
- var init_field_assertions = __esm({
1500
- "src/builder/shared/validators/field-assertions.ts"() {
1501
- init_errors();
1502
- init_primary_key_utils();
1503
- }
1504
- });
1405
+
1406
+ // src/builder/pagination.ts
1407
+ var MAX_LIMIT_OFFSET = 2147483647;
1408
+ var ORDER_BY_ALLOWED_KEYS = /* @__PURE__ */ new Set(["sort", "nulls"]);
1505
1409
  function parseDirectionRaw(raw, errorLabel) {
1506
1410
  const s = String(raw).toLowerCase();
1507
1411
  if (s === "asc" || s === "desc") return s;
@@ -1550,6 +1454,7 @@ function normalizeNonNegativeInt(name, v) {
1550
1454
  throw new Error(`${name} normalization returned undefined`);
1551
1455
  return result;
1552
1456
  }
1457
+ var MIN_NEGATIVE_TAKE = -1e4;
1553
1458
  function normalizeIntAllowNegative(name, v) {
1554
1459
  if (isDynamicParameter(v)) return v;
1555
1460
  const result = normalizeIntLike(name, v, {
@@ -1835,23 +1740,6 @@ function getPaginationParams(method, args) {
1835
1740
  }
1836
1741
  return {};
1837
1742
  }
1838
- var MAX_LIMIT_OFFSET, ORDER_BY_ALLOWED_KEYS, MIN_NEGATIVE_TAKE;
1839
- var init_pagination = __esm({
1840
- "src/builder/pagination.ts"() {
1841
- init_constants();
1842
- init_sql_utils();
1843
- init_sql_builder_dialect();
1844
- init_type_guards();
1845
- init_int_like();
1846
- init_dynamic_params();
1847
- init_order_by_utils();
1848
- init_order_by_determinism();
1849
- init_field_assertions();
1850
- MAX_LIMIT_OFFSET = 2147483647;
1851
- ORDER_BY_ALLOWED_KEYS = /* @__PURE__ */ new Set(["sort", "nulls"]);
1852
- MIN_NEGATIVE_TAKE = -1e4;
1853
- }
1854
- });
1855
1743
 
1856
1744
  // src/builder/shared/null-comparison.ts
1857
1745
  function buildNullComparison(expr, op, allowNull = false) {
@@ -1869,12 +1757,6 @@ function tryBuildNullComparison(expr, op, val, context) {
1869
1757
  }
1870
1758
  return clause;
1871
1759
  }
1872
- var init_null_comparison = __esm({
1873
- "src/builder/shared/null-comparison.ts"() {
1874
- init_constants();
1875
- init_errors();
1876
- }
1877
- });
1878
1760
  function buildInCondition(expr, op, val, params, dialect, context) {
1879
1761
  if (isDynamicParameter(val)) {
1880
1762
  const ph2 = params.addAuto(val);
@@ -1898,12 +1780,9 @@ function buildInCondition(expr, op, val, params, dialect, context) {
1898
1780
  const ph = params.add(paramValue);
1899
1781
  return op === "in" ? inArray(expr, ph, dialect) : notInArray(expr, ph, dialect);
1900
1782
  }
1901
- var init_in_operator_builder = __esm({
1902
- "src/builder/shared/in-operator-builder.ts"() {
1903
- init_sql_builder_dialect();
1904
- init_errors();
1905
- }
1906
- });
1783
+
1784
+ // src/builder/where/operators-scalar.ts
1785
+ var MAX_NOT_DEPTH = 50;
1907
1786
  function buildNotComposite(expr, val, params, dialect, buildOp, separator) {
1908
1787
  const entries = Object.entries(val).filter(
1909
1788
  ([k, v]) => k !== "mode" && v !== void 0
@@ -2079,18 +1958,6 @@ function handleComparisonOperator(expr, op, val, params) {
2079
1958
  const placeholder = params.addAuto(val);
2080
1959
  return `${expr} ${sqlOp} ${placeholder}`;
2081
1960
  }
2082
- var MAX_NOT_DEPTH;
2083
- var init_operators_scalar = __esm({
2084
- "src/builder/where/operators-scalar.ts"() {
2085
- init_sql_builder_dialect();
2086
- init_constants();
2087
- init_errors();
2088
- init_type_guards();
2089
- init_null_comparison();
2090
- init_in_operator_builder();
2091
- MAX_NOT_DEPTH = 50;
2092
- }
2093
- });
2094
1961
  function buildArrayParam(val, params, dialect) {
2095
1962
  if (isDynamicParameter(val)) {
2096
1963
  return params.addAuto(val);
@@ -2222,17 +2089,11 @@ function handleArrayIsEmpty(expr, val, dialect) {
2222
2089
  }
2223
2090
  return val === true ? arrayIsEmpty(expr, dialect) : arrayIsNotEmpty(expr, dialect);
2224
2091
  }
2225
- var init_operators_array = __esm({
2226
- "src/builder/where/operators-array.ts"() {
2227
- init_sql_builder_dialect();
2228
- init_constants();
2229
- init_errors();
2230
- init_type_guards();
2231
- init_null_comparison();
2232
- }
2233
- });
2234
2092
 
2235
2093
  // src/builder/where/operators-json.ts
2094
+ var SAFE_JSON_PATH_SEGMENT = /^[a-zA-Z_]\w*$/;
2095
+ var MAX_PATH_SEGMENT_LENGTH = 255;
2096
+ var MAX_PATH_SEGMENTS = 100;
2236
2097
  function sanitizeForError(s) {
2237
2098
  let result = "";
2238
2099
  for (let i = 0; i < s.length; i++) {
@@ -2349,20 +2210,9 @@ function handleJsonWildcard(expr, op, val, params, wildcards, dialect) {
2349
2210
  const jsonText = jsonToText(expr, dialect);
2350
2211
  return caseInsensitiveLike(jsonText, placeholder, dialect);
2351
2212
  }
2352
- var SAFE_JSON_PATH_SEGMENT, MAX_PATH_SEGMENT_LENGTH, MAX_PATH_SEGMENTS;
2353
- var init_operators_json = __esm({
2354
- "src/builder/where/operators-json.ts"() {
2355
- init_sql_builder_dialect();
2356
- init_constants();
2357
- init_errors();
2358
- init_type_guards();
2359
- SAFE_JSON_PATH_SEGMENT = /^[a-zA-Z_]\w*$/;
2360
- MAX_PATH_SEGMENT_LENGTH = 255;
2361
- MAX_PATH_SEGMENTS = 100;
2362
- }
2363
- });
2364
2213
 
2365
2214
  // src/builder/where/relations.ts
2215
+ var NO_JOINS = [];
2366
2216
  function isListRelation(fieldType) {
2367
2217
  return typeof fieldType === "string" && fieldType.endsWith("[]");
2368
2218
  }
@@ -2393,21 +2243,6 @@ function buildToOneNotExistsMatch(relTable, relAlias, join, sub) {
2393
2243
  const joins = sub.joins.length > 0 ? ` ${sub.joins.join(" ")}` : "";
2394
2244
  return `${SQL_TEMPLATES.NOT} EXISTS (${SQL_TEMPLATES.SELECT} 1 ${SQL_TEMPLATES.FROM} ${relTable} ${relAlias}${joins} ${SQL_TEMPLATES.WHERE} ${join} ${SQL_TEMPLATES.AND} ${sub.clause})`;
2395
2245
  }
2396
- function tryOptimizeNoneFilter(noneValue, ctx, relModel, relTable, relAlias, join, sub) {
2397
- const isEmptyFilter = isPlainObject(noneValue) && Object.keys(noneValue).length === 0;
2398
- const canOptimize = !ctx.isSubquery && isEmptyFilter && sub.clause === DEFAULT_WHERE_CLAUSE && sub.joins.length === 0;
2399
- if (!canOptimize) return null;
2400
- const checkField = relModel.fields.find(
2401
- (f) => !f.isRelation && f.isRequired && f.name !== "id"
2402
- ) || relModel.fields.find((f) => !f.isRelation && f.name === "id");
2403
- if (!checkField) return null;
2404
- const leftJoinSql = `LEFT JOIN ${relTable} ${relAlias} ON ${join}`;
2405
- const whereClause = `${relAlias}.${quoteColumn(relModel, checkField.name)} IS NULL`;
2406
- return {
2407
- clause: whereClause,
2408
- joins: [leftJoinSql]
2409
- };
2410
- }
2411
2246
  function processRelationFilter(key, wrap, args) {
2412
2247
  const { value, fieldName, ctx, relAlias, relModel, whereBuilder } = args;
2413
2248
  const raw = value[key];
@@ -2427,7 +2262,6 @@ function buildListRelationFilters(args) {
2427
2262
  fieldName,
2428
2263
  value,
2429
2264
  ctx,
2430
- whereBuilder,
2431
2265
  relModel,
2432
2266
  relTable,
2433
2267
  relAlias,
@@ -2435,23 +2269,17 @@ function buildListRelationFilters(args) {
2435
2269
  } = args;
2436
2270
  const noneValue = value[RelationFilters.NONE];
2437
2271
  if (noneValue !== void 0 && noneValue !== null) {
2438
- const sub = whereBuilder.build(noneValue, __spreadProps(__spreadValues({}, ctx), {
2439
- alias: relAlias,
2440
- model: relModel,
2441
- path: [...ctx.path, fieldName, RelationFilters.NONE],
2442
- isSubquery: true,
2443
- depth: ctx.depth + 1
2444
- }));
2445
- const optimized = tryOptimizeNoneFilter(
2446
- noneValue,
2447
- ctx,
2448
- relModel,
2449
- relTable,
2450
- relAlias,
2451
- join,
2452
- sub
2453
- );
2454
- if (optimized) return optimized;
2272
+ const isEmptyFilter = isPlainObject(noneValue) && Object.keys(noneValue).length === 0;
2273
+ if (isEmptyFilter && !ctx.isSubquery) {
2274
+ const checkField = relModel.fields.find(
2275
+ (f) => !f.isRelation && f.isRequired && f.name !== "id"
2276
+ ) || relModel.fields.find((f) => !f.isRelation && f.name === "id");
2277
+ if (checkField) {
2278
+ const leftJoinSql = `LEFT JOIN ${relTable} ${relAlias} ON ${join}`;
2279
+ const whereClause = `${relAlias}.${quoteColumn(relModel, checkField.name)} IS NULL`;
2280
+ return { clause: whereClause, joins: [leftJoinSql] };
2281
+ }
2282
+ }
2455
2283
  }
2456
2284
  const filters = [
2457
2285
  {
@@ -2623,18 +2451,6 @@ function buildTopLevelRelation(fieldName, value, ctx, whereBuilder) {
2623
2451
  function buildNestedRelation(fieldName, value, ctx, whereBuilder) {
2624
2452
  return buildTopLevelRelation(fieldName, value, ctx, whereBuilder);
2625
2453
  }
2626
- var NO_JOINS;
2627
- var init_relations = __esm({
2628
- "src/builder/where/relations.ts"() {
2629
- init_joins();
2630
- init_constants();
2631
- init_errors();
2632
- init_sql_utils();
2633
- init_type_guards();
2634
- init_primary_key_utils();
2635
- NO_JOINS = [];
2636
- }
2637
- });
2638
2454
 
2639
2455
  // src/builder/shared/array-utils.ts
2640
2456
  function deduplicatePreserveOrder(items) {
@@ -2649,12 +2465,28 @@ function deduplicatePreserveOrder(items) {
2649
2465
  }
2650
2466
  return out;
2651
2467
  }
2652
- var init_array_utils = __esm({
2653
- "src/builder/shared/array-utils.ts"() {
2654
- }
2655
- });
2656
2468
 
2657
2469
  // src/builder/where/builder.ts
2470
+ var MAX_QUERY_DEPTH = 50;
2471
+ var EMPTY_JOINS = [];
2472
+ var JSON_OPS = /* @__PURE__ */ new Set([
2473
+ Ops.PATH,
2474
+ Ops.STRING_CONTAINS,
2475
+ Ops.STRING_STARTS_WITH,
2476
+ Ops.STRING_ENDS_WITH
2477
+ ]);
2478
+ var WhereBuilder = class {
2479
+ build(where, ctx) {
2480
+ if (!isPlainObject(where)) {
2481
+ throw createError("where must be an object", {
2482
+ path: ctx.path,
2483
+ modelName: ctx.model.name
2484
+ });
2485
+ }
2486
+ return buildWhereInternal(where, ctx, this);
2487
+ }
2488
+ };
2489
+ var whereBuilderInstance = new WhereBuilder();
2658
2490
  function createResult(clause, joins = EMPTY_JOINS) {
2659
2491
  return { clause, joins };
2660
2492
  }
@@ -2718,16 +2550,9 @@ function buildWhereInternal(where, ctx, builder) {
2718
2550
  { path: ctx.path, modelName: ctx.model.name }
2719
2551
  );
2720
2552
  }
2721
- if (ctx.seenObjects.has(where)) {
2722
- throw createError("Circular reference detected in WHERE clause", {
2723
- path: ctx.path,
2724
- modelName: ctx.model.name
2725
- });
2726
- }
2727
2553
  if (!isPlainObject(where) || Object.keys(where).length === 0) {
2728
2554
  return createResult(DEFAULT_WHERE_CLAUSE, EMPTY_JOINS);
2729
2555
  }
2730
- ctx.seenObjects.add(where);
2731
2556
  if (isSimpleWhere(where)) {
2732
2557
  const key = Object.keys(where)[0];
2733
2558
  const value = where[key];
@@ -2861,45 +2686,9 @@ function buildOperator(expr, op, val, ctx, mode, fieldType) {
2861
2686
  dialect: ctx.dialect
2862
2687
  });
2863
2688
  }
2864
- var MAX_QUERY_DEPTH, EMPTY_JOINS, JSON_OPS, WhereBuilder, whereBuilderInstance;
2865
- var init_builder = __esm({
2866
- "src/builder/where/builder.ts"() {
2867
- init_joins();
2868
- init_operators_scalar();
2869
- init_operators_array();
2870
- init_operators_json();
2871
- init_relations();
2872
- init_constants();
2873
- init_errors();
2874
- init_sql_utils();
2875
- init_field_assertions();
2876
- init_sql_validators();
2877
- init_type_guards();
2878
- init_array_utils();
2879
- MAX_QUERY_DEPTH = 50;
2880
- EMPTY_JOINS = [];
2881
- JSON_OPS = /* @__PURE__ */ new Set([
2882
- Ops.PATH,
2883
- Ops.STRING_CONTAINS,
2884
- Ops.STRING_STARTS_WITH,
2885
- Ops.STRING_ENDS_WITH
2886
- ]);
2887
- WhereBuilder = class {
2888
- build(where, ctx) {
2889
- if (!isPlainObject(where)) {
2890
- throw createError("where must be an object", {
2891
- path: ctx.path,
2892
- modelName: ctx.model.name
2893
- });
2894
- }
2895
- return buildWhereInternal(where, ctx, this);
2896
- }
2897
- };
2898
- whereBuilderInstance = new WhereBuilder();
2899
- }
2900
- });
2901
2689
 
2902
2690
  // src/builder/shared/alias-generator.ts
2691
+ var SAFE_IDENTIFIER_CACHE = /* @__PURE__ */ new Map();
2903
2692
  function toSafeSqlIdentifier(input) {
2904
2693
  const cached = SAFE_IDENTIFIER_CACHE.get(input);
2905
2694
  if (cached !== void 0) return cached;
@@ -2953,13 +2742,7 @@ function createAliasGenerator(maxAliases = 1e4) {
2953
2742
  }
2954
2743
  };
2955
2744
  }
2956
- var SAFE_IDENTIFIER_CACHE;
2957
- var init_alias_generator = __esm({
2958
- "src/builder/shared/alias-generator.ts"() {
2959
- init_constants();
2960
- SAFE_IDENTIFIER_CACHE = /* @__PURE__ */ new Map();
2961
- }
2962
- });
2745
+ var MAX_PARAM_INDEX = Number.MAX_SAFE_INTEGER - 1e3;
2963
2746
  function assertSameLength(params, mappings) {
2964
2747
  if (params.length !== mappings.length) {
2965
2748
  throw new Error(
@@ -3041,6 +2824,10 @@ function assertCanAddParam(currentIndex) {
3041
2824
  );
3042
2825
  }
3043
2826
  }
2827
+ var POSTGRES_POSITION_CACHE = new Array(500);
2828
+ for (let i = 0; i < 500; i++) {
2829
+ POSTGRES_POSITION_CACHE[i] = `$${i + 1}`;
2830
+ }
3044
2831
  function formatPositionPostgres(position) {
3045
2832
  if (position <= 500) return POSTGRES_POSITION_CACHE[position - 1];
3046
2833
  return `$${position}`;
@@ -3154,17 +2941,6 @@ function createParamStoreFrom(existingParams, existingMappings, nextIndex, diale
3154
2941
  cachedIndex
3155
2942
  );
3156
2943
  }
3157
- var MAX_PARAM_INDEX, POSTGRES_POSITION_CACHE;
3158
- var init_param_store = __esm({
3159
- "src/builder/shared/param-store.ts"() {
3160
- init_normalize_value();
3161
- MAX_PARAM_INDEX = Number.MAX_SAFE_INTEGER - 1e3;
3162
- POSTGRES_POSITION_CACHE = new Array(500);
3163
- for (let i = 0; i < 500; i++) {
3164
- POSTGRES_POSITION_CACHE[i] = `$${i + 1}`;
3165
- }
3166
- }
3167
- });
3168
2944
 
3169
2945
  // src/builder/shared/state.ts
3170
2946
  function toPublicResult(clause, joins, params) {
@@ -3177,18 +2953,13 @@ function toPublicResult(clause, joins, params) {
3177
2953
  nextParamIndex: snapshot.index
3178
2954
  });
3179
2955
  }
3180
- var init_state = __esm({
3181
- "src/builder/shared/state.ts"() {
3182
- init_constants();
3183
- }
3184
- });
3185
2956
 
3186
2957
  // src/builder/where.ts
3187
2958
  function buildWhereClause(where, options) {
3188
2959
  var _a, _b, _c, _d, _e;
3189
2960
  assertSafeAlias(options.alias);
3190
2961
  const dialect = options.dialect || getGlobalDialect();
3191
- const params = (_a = options.params) != null ? _a : createParamStore();
2962
+ const params = (_a = options.params) != null ? _a : createParamStore(1, dialect);
3192
2963
  const ctx = {
3193
2964
  alias: options.alias,
3194
2965
  model: options.model,
@@ -3205,21 +2976,13 @@ function buildWhereClause(where, options) {
3205
2976
  const publicResult = toPublicResult(result.clause, result.joins, params);
3206
2977
  return publicResult;
3207
2978
  }
3208
- var init_where = __esm({
3209
- "src/builder/where.ts"() {
3210
- init_sql_builder_dialect();
3211
- init_builder();
3212
- init_alias_generator();
3213
- init_param_store();
3214
- init_state();
3215
- init_sql_utils();
3216
- }
3217
- });
3218
2979
 
3219
2980
  // src/builder/select/fields.ts
2981
+ var DEFAULT_SELECT_CACHE = /* @__PURE__ */ new WeakMap();
3220
2982
  function toSelectEntries(select) {
3221
2983
  const out = [];
3222
2984
  for (const [k, v] of Object.entries(select)) {
2985
+ if (k === "_count") continue;
3223
2986
  if (v !== false && v !== void 0) out.push([k, v]);
3224
2987
  }
3225
2988
  return out;
@@ -3341,7 +3104,7 @@ function buildRelationSelect(relArgs, relModel, relAlias) {
3341
3104
  const scalarNames = getScalarFieldSet(relModel);
3342
3105
  const relationNames = getRelationFieldSet(relModel);
3343
3106
  const entries = toSelectEntries(sel);
3344
- validateFieldKeys(entries, scalarNames, relationNames, false);
3107
+ validateFieldKeys(entries, scalarNames, relationNames, true);
3345
3108
  return buildSelectedScalarParts(
3346
3109
  entries,
3347
3110
  scalarNames,
@@ -3351,16 +3114,6 @@ function buildRelationSelect(relArgs, relModel, relAlias) {
3351
3114
  }
3352
3115
  return buildAllScalarParts(relModel, relAlias).join(SQL_SEPARATORS.FIELD_LIST);
3353
3116
  }
3354
- var DEFAULT_SELECT_CACHE;
3355
- var init_fields = __esm({
3356
- "src/builder/select/fields.ts"() {
3357
- init_constants();
3358
- init_model_field_cache();
3359
- init_sql_utils();
3360
- init_type_guards();
3361
- DEFAULT_SELECT_CACHE = /* @__PURE__ */ new WeakMap();
3362
- }
3363
- });
3364
3117
 
3365
3118
  // src/builder/shared/relation-key-utils.ts
3366
3119
  function resolveRelationKeys(field, context = "include") {
@@ -3381,11 +3134,6 @@ function resolveRelationKeys(field, context = "include") {
3381
3134
  const parentKeys = field.isForeignKeyLocal ? fkFields : refFields;
3382
3135
  return { childKeys, parentKeys };
3383
3136
  }
3384
- var init_relation_key_utils = __esm({
3385
- "src/builder/shared/relation-key-utils.ts"() {
3386
- init_sql_utils();
3387
- }
3388
- });
3389
3137
 
3390
3138
  // src/builder/shared/relation-extraction-utils.ts
3391
3139
  function extractRelationEntries(args, model) {
@@ -3410,12 +3158,11 @@ function extractRelationEntries(args, model) {
3410
3158
  }
3411
3159
  return entries;
3412
3160
  }
3413
- var init_relation_extraction_utils = __esm({
3414
- "src/builder/shared/relation-extraction-utils.ts"() {
3415
- init_model_field_cache();
3416
- init_type_guards();
3417
- }
3418
- });
3161
+
3162
+ // src/builder/select/includes.ts
3163
+ var MAX_INCLUDE_DEPTH = 5;
3164
+ var MAX_INCLUDES_PER_LEVEL = 10;
3165
+ var MAX_TOTAL_SUBQUERIES = 100;
3419
3166
  function buildIncludeScope(includePath) {
3420
3167
  if (includePath.length === 0) return "include";
3421
3168
  let scope = "include";
@@ -4100,30 +3847,6 @@ function buildRelationCountSql(countSelect, model, schemas, parentAlias, _params
4100
3847
  }
4101
3848
  return { joins, jsonPairs: pairs.join(SQL_SEPARATORS.FIELD_LIST) };
4102
3849
  }
4103
- var MAX_INCLUDE_DEPTH, MAX_INCLUDES_PER_LEVEL, MAX_TOTAL_SUBQUERIES;
4104
- var init_includes = __esm({
4105
- "src/builder/select/includes.ts"() {
4106
- init_joins();
4107
- init_pagination();
4108
- init_where();
4109
- init_sql_builder_dialect();
4110
- init_fields();
4111
- init_alias_generator();
4112
- init_constants();
4113
- init_sql_utils();
4114
- init_sql_validators();
4115
- init_type_guards();
4116
- init_order_by_utils();
4117
- init_dynamic_params();
4118
- init_model_field_cache();
4119
- init_order_by_determinism();
4120
- init_relation_key_utils();
4121
- init_relation_extraction_utils();
4122
- MAX_INCLUDE_DEPTH = 5;
4123
- MAX_INCLUDES_PER_LEVEL = 10;
4124
- MAX_TOTAL_SUBQUERIES = 100;
4125
- }
4126
- });
4127
3850
 
4128
3851
  // src/builder/shared/string-builder.ts
4129
3852
  function joinNonEmpty(parts, sep) {
@@ -4136,10 +3859,6 @@ function joinNonEmpty(parts, sep) {
4136
3859
  }
4137
3860
  return result;
4138
3861
  }
4139
- var init_string_builder = __esm({
4140
- "src/builder/shared/string-builder.ts"() {
4141
- }
4142
- });
4143
3862
 
4144
3863
  // src/builder/shared/relation-utils.ts
4145
3864
  function hasChildPagination(relArgs) {
@@ -4201,12 +3920,6 @@ function extractNestedIncludeSpec(relArgs, relModel) {
4201
3920
  }
4202
3921
  return out;
4203
3922
  }
4204
- var init_relation_utils = __esm({
4205
- "src/builder/shared/relation-utils.ts"() {
4206
- init_model_field_cache();
4207
- init_type_guards();
4208
- }
4209
- });
4210
3923
 
4211
3924
  // src/builder/select/flat-join.ts
4212
3925
  function createAliasCounter() {
@@ -4426,19 +4139,7 @@ function buildFlatJoinSql(spec) {
4426
4139
  `.trim();
4427
4140
  return { sql, requiresReduction: true, includeSpec };
4428
4141
  }
4429
- var init_flat_join = __esm({
4430
- "src/builder/select/flat-join.ts"() {
4431
- init_constants();
4432
- init_sql_utils();
4433
- init_joins();
4434
- init_model_field_cache();
4435
- init_assembly();
4436
- init_type_guards();
4437
- init_primary_key_utils();
4438
- init_relation_extraction_utils();
4439
- init_relation_utils();
4440
- }
4441
- });
4142
+ var SELECT_FIELD_REGEX = /^\s*("(?:[^"]|"")+"|[a-z_][a-z0-9_]*)\s*\.\s*("(?:[^"]|"")+"|[a-z_][a-z0-9_]*)(?:\s+AS\s+("(?:[^"]|"")+"|[a-z_][a-z0-9_]*))?\s*$/i;
4442
4143
  function buildWhereSql(conditions) {
4443
4144
  if (!isNonEmptyArray(conditions)) return "";
4444
4145
  return " " + SQL_TEMPLATES.WHERE + " " + conditions.join(SQL_SEPARATORS.CONDITION_AND);
@@ -4940,24 +4641,6 @@ function constructFinalSql(spec) {
4940
4641
  sql = appendPagination(sql, spec);
4941
4642
  return finalizeSql(sql, params, dialect);
4942
4643
  }
4943
- var SELECT_FIELD_REGEX;
4944
- var init_assembly = __esm({
4945
- "src/builder/select/assembly.ts"() {
4946
- init_constants();
4947
- init_sql_utils();
4948
- init_sql_validators();
4949
- init_type_guards();
4950
- init_dynamic_params();
4951
- init_sql_builder_dialect();
4952
- init_includes();
4953
- init_string_builder();
4954
- init_model_field_cache();
4955
- init_pagination();
4956
- init_order_by_utils();
4957
- init_flat_join();
4958
- SELECT_FIELD_REGEX = /^\s*("(?:[^"]|"")+"|[a-z_][a-z0-9_]*)\s*\.\s*("(?:[^"]|"")+"|[a-z_][a-z0-9_]*)(?:\s+AS\s+("(?:[^"]|"")+"|[a-z_][a-z0-9_]*))?\s*$/i;
4959
- }
4960
- });
4961
4644
 
4962
4645
  // src/builder/select.ts
4963
4646
  function normalizeOrderByInput3(orderBy) {
@@ -5235,23 +4918,9 @@ function buildSelectSql(input) {
5235
4918
  });
5236
4919
  return constructFinalSql(spec);
5237
4920
  }
5238
- var init_select = __esm({
5239
- "src/builder/select.ts"() {
5240
- init_sql_builder_dialect();
5241
- init_pagination();
5242
- init_assembly();
5243
- init_fields();
5244
- init_includes();
5245
- init_order_by_utils();
5246
- init_param_store();
5247
- init_sql_utils();
5248
- init_type_guards();
5249
- init_field_assertions();
5250
- init_model_field_cache();
5251
- }
5252
- });
5253
4921
 
5254
4922
  // src/builder/shared/comparison-builder.ts
4923
+ var DEFAULT_EXCLUDE_KEYS = /* @__PURE__ */ new Set(["mode"]);
5255
4924
  function buildComparisons(expr, filter, params, dialect, builder, excludeKeys = DEFAULT_EXCLUDE_KEYS) {
5256
4925
  const out = [];
5257
4926
  for (const op in filter) {
@@ -5264,14 +4933,40 @@ function buildComparisons(expr, filter, params, dialect, builder, excludeKeys =
5264
4933
  }
5265
4934
  return out;
5266
4935
  }
5267
- var DEFAULT_EXCLUDE_KEYS;
5268
- var init_comparison_builder = __esm({
5269
- "src/builder/shared/comparison-builder.ts"() {
5270
- DEFAULT_EXCLUDE_KEYS = /* @__PURE__ */ new Set(["mode"]);
5271
- }
5272
- });
5273
4936
 
5274
4937
  // src/builder/aggregates.ts
4938
+ var MAX_NOT_DEPTH2 = 50;
4939
+ var AGGREGATES = [
4940
+ ["_sum", "SUM"],
4941
+ ["_avg", "AVG"],
4942
+ ["_min", "MIN"],
4943
+ ["_max", "MAX"]
4944
+ ];
4945
+ var COMPARISON_OPS = {
4946
+ [Ops.EQUALS]: "=",
4947
+ [Ops.NOT]: "<>",
4948
+ [Ops.GT]: ">",
4949
+ [Ops.GTE]: ">=",
4950
+ [Ops.LT]: "<",
4951
+ [Ops.LTE]: "<="
4952
+ };
4953
+ var HAVING_ALLOWED_OPS = /* @__PURE__ */ new Set([
4954
+ Ops.EQUALS,
4955
+ Ops.NOT,
4956
+ Ops.GT,
4957
+ Ops.GTE,
4958
+ Ops.LT,
4959
+ Ops.LTE,
4960
+ Ops.IN,
4961
+ Ops.NOT_IN
4962
+ ]);
4963
+ var HAVING_FIELD_FIRST_AGG_KEYS = Object.freeze([
4964
+ "_count",
4965
+ "_sum",
4966
+ "_avg",
4967
+ "_min",
4968
+ "_max"
4969
+ ]);
5275
4970
  function hasAnyOwnKey(obj) {
5276
4971
  for (const k in obj) {
5277
4972
  if (Object.prototype.hasOwnProperty.call(obj, k)) return true;
@@ -5779,58 +5474,6 @@ function buildCountSql(whereResult, tableName, alias, argsOrSkip, dialect, model
5779
5474
  paramMappings: sub.paramMappings
5780
5475
  };
5781
5476
  }
5782
- var MAX_NOT_DEPTH2, AGGREGATES, COMPARISON_OPS, HAVING_ALLOWED_OPS, HAVING_FIELD_FIRST_AGG_KEYS;
5783
- var init_aggregates = __esm({
5784
- "src/builder/aggregates.ts"() {
5785
- init_constants();
5786
- init_sql_utils();
5787
- init_param_store();
5788
- init_sql_validators();
5789
- init_type_guards();
5790
- init_sql_builder_dialect();
5791
- init_dynamic_params();
5792
- init_operators_scalar();
5793
- init_field_assertions();
5794
- init_comparison_builder();
5795
- init_pagination();
5796
- init_select();
5797
- init_primary_key_utils();
5798
- init_null_comparison();
5799
- init_in_operator_builder();
5800
- MAX_NOT_DEPTH2 = 50;
5801
- AGGREGATES = [
5802
- ["_sum", "SUM"],
5803
- ["_avg", "AVG"],
5804
- ["_min", "MIN"],
5805
- ["_max", "MAX"]
5806
- ];
5807
- COMPARISON_OPS = {
5808
- [Ops.EQUALS]: "=",
5809
- [Ops.NOT]: "<>",
5810
- [Ops.GT]: ">",
5811
- [Ops.GTE]: ">=",
5812
- [Ops.LT]: "<",
5813
- [Ops.LTE]: "<="
5814
- };
5815
- HAVING_ALLOWED_OPS = /* @__PURE__ */ new Set([
5816
- Ops.EQUALS,
5817
- Ops.NOT,
5818
- Ops.GT,
5819
- Ops.GTE,
5820
- Ops.LT,
5821
- Ops.LTE,
5822
- Ops.IN,
5823
- Ops.NOT_IN
5824
- ]);
5825
- HAVING_FIELD_FIRST_AGG_KEYS = Object.freeze([
5826
- "_count",
5827
- "_sum",
5828
- "_avg",
5829
- "_min",
5830
- "_max"
5831
- ]);
5832
- }
5833
- });
5834
5477
  function safeAlias(input) {
5835
5478
  const raw = String(input).toLowerCase();
5836
5479
  const cleaned = raw.replace(/[^a-z0-9_]/g, "_");
@@ -6106,19 +5749,6 @@ function generateSQL(directive) {
6106
5749
  includeSpec: built.includeSpec
6107
5750
  });
6108
5751
  }
6109
- var init_sql_generator = __esm({
6110
- "src/sql-generator.ts"() {
6111
- init_joins();
6112
- init_select();
6113
- init_aggregates();
6114
- init_sql_builder_dialect();
6115
- init_where();
6116
- init_sql_utils();
6117
- init_constants();
6118
- init_sql_validators();
6119
- init_type_guards();
6120
- }
6121
- });
6122
5752
 
6123
5753
  // src/utils/s3-fifo.ts
6124
5754
  function withDispose(it) {
@@ -6129,220 +5759,215 @@ function withDispose(it) {
6129
5759
  }
6130
5760
  return it;
6131
5761
  }
6132
- function createBoundedCache(maxSize) {
6133
- return new BoundedCache(maxSize);
6134
- }
6135
- var BoundedCache;
6136
- var init_s3_fifo = __esm({
6137
- "src/utils/s3-fifo.ts"() {
6138
- BoundedCache = class {
6139
- constructor(maxSize) {
6140
- this.map = /* @__PURE__ */ new Map();
6141
- this.ghost = /* @__PURE__ */ new Set();
6142
- this.smallHead = null;
6143
- this.smallTail = null;
6144
- this.smallSize = 0;
6145
- this.mainHead = null;
6146
- this.mainTail = null;
6147
- this.mainSize = 0;
6148
- this.maxSize = maxSize;
6149
- this.smallLimit = Math.max(1, Math.floor(maxSize * 0.1));
6150
- this.mainLimit = maxSize - this.smallLimit;
6151
- this.ghostLimit = this.mainLimit;
6152
- }
6153
- get size() {
6154
- return this.map.size;
6155
- }
6156
- get(key) {
6157
- const node = this.map.get(key);
6158
- if (!node) return void 0;
6159
- node.freq = Math.min(node.freq + 1, 3);
6160
- return node.value;
6161
- }
6162
- set(key, value) {
6163
- const existing = this.map.get(key);
6164
- if (existing) {
6165
- existing.value = value;
6166
- return this;
6167
- }
6168
- if (this.ghost.has(key)) {
6169
- this.ghost.delete(key);
6170
- const node2 = this.createNode(key, value, "main");
6171
- this.map.set(key, node2);
6172
- this.pushMain(node2);
6173
- if (this.mainSize > this.mainLimit) this.evictMain();
6174
- return this;
6175
- }
6176
- const node = this.createNode(key, value, "small");
6177
- this.map.set(key, node);
6178
- this.pushSmall(node);
6179
- if (this.size > this.maxSize) {
6180
- if (this.smallSize > this.smallLimit) this.evictSmall();
6181
- else this.evictMain();
6182
- }
6183
- return this;
6184
- }
6185
- has(key) {
6186
- return this.map.has(key);
6187
- }
6188
- delete(key) {
6189
- const node = this.map.get(key);
6190
- if (!node) return false;
6191
- this.map.delete(key);
6192
- this.removeNode(node);
6193
- return true;
6194
- }
6195
- clear() {
6196
- this.map.clear();
6197
- this.ghost.clear();
6198
- this.smallHead = this.smallTail = null;
6199
- this.mainHead = this.mainTail = null;
6200
- this.smallSize = this.mainSize = 0;
6201
- }
6202
- keys() {
6203
- return withDispose(
6204
- (function* (self) {
6205
- for (const key of self.map.keys()) yield key;
6206
- })(this)
6207
- );
6208
- }
6209
- values() {
6210
- return withDispose(
6211
- (function* (self) {
6212
- for (const node of self.map.values()) yield node.value;
6213
- })(this)
6214
- );
6215
- }
6216
- entries() {
6217
- return withDispose(
6218
- (function* (self) {
6219
- for (const [key, node] of self.map.entries())
6220
- yield [key, node.value];
6221
- })(this)
6222
- );
6223
- }
6224
- forEach(callbackfn, thisArg) {
6225
- for (const [key, node] of this.map.entries()) {
6226
- callbackfn.call(thisArg, node.value, key, this);
6227
- }
6228
- }
6229
- [Symbol.iterator]() {
6230
- return this.entries();
6231
- }
6232
- get [Symbol.toStringTag]() {
6233
- return "BoundedCache";
6234
- }
6235
- createNode(key, value, queue) {
6236
- return { key, value, freq: 0, queue, prev: null, next: null };
6237
- }
6238
- pushSmall(node) {
6239
- node.next = this.smallHead;
6240
- node.prev = null;
6241
- if (this.smallHead) this.smallHead.prev = node;
6242
- else this.smallTail = node;
6243
- this.smallHead = node;
6244
- this.smallSize++;
6245
- }
6246
- pushMain(node) {
6247
- node.next = this.mainHead;
6248
- node.prev = null;
6249
- if (this.mainHead) this.mainHead.prev = node;
6250
- else this.mainTail = node;
6251
- this.mainHead = node;
6252
- this.mainSize++;
6253
- }
6254
- popSmall() {
6255
- if (!this.smallTail) return null;
6256
- const node = this.smallTail;
6257
- this.smallTail = node.prev;
6258
- if (this.smallTail) this.smallTail.next = null;
6259
- else this.smallHead = null;
6260
- node.prev = null;
6261
- node.next = null;
6262
- this.smallSize--;
6263
- return node;
6264
- }
6265
- popMain() {
6266
- if (!this.mainTail) return null;
6267
- const node = this.mainTail;
6268
- this.mainTail = node.prev;
6269
- if (this.mainTail) this.mainTail.next = null;
6270
- else this.mainHead = null;
6271
- node.prev = null;
6272
- node.next = null;
6273
- this.mainSize--;
6274
- return node;
6275
- }
6276
- removeNode(node) {
6277
- this.unlinkNode(node);
6278
- if (node.queue === "small") {
6279
- if (node === this.smallHead) this.smallHead = node.next;
6280
- if (node === this.smallTail) this.smallTail = node.prev;
6281
- this.smallSize--;
6282
- } else {
6283
- if (node === this.mainHead) this.mainHead = node.next;
6284
- if (node === this.mainTail) this.mainTail = node.prev;
6285
- this.mainSize--;
6286
- }
6287
- node.prev = null;
6288
- node.next = null;
6289
- }
6290
- unlinkNode(node) {
6291
- if (node.prev) node.prev.next = node.next;
6292
- if (node.next) node.next.prev = node.prev;
6293
- }
6294
- shouldPromoteFromSmall(node) {
6295
- return node.freq > 1;
6296
- }
6297
- shouldRetryInMain(node) {
6298
- return node.freq >= 1;
6299
- }
6300
- promoteToMain(node) {
6301
- node.queue = "main";
6302
- this.pushMain(node);
6303
- }
6304
- addToGhost(key) {
6305
- this.ghost.add(key);
6306
- if (this.ghost.size <= this.ghostLimit) return;
6307
- const firstGhost = this.ghost.values().next().value;
6308
- if (firstGhost !== void 0) this.ghost.delete(firstGhost);
6309
- }
6310
- evictFromCache(node) {
6311
- this.map.delete(node.key);
6312
- }
6313
- evictSmall() {
6314
- while (this.smallSize > 0) {
6315
- const node = this.popSmall();
6316
- if (!node) return;
6317
- if (this.shouldPromoteFromSmall(node)) {
6318
- this.promoteToMain(node);
6319
- if (this.mainSize > this.mainLimit) {
6320
- this.evictMain();
6321
- return;
6322
- }
6323
- continue;
6324
- }
6325
- this.evictFromCache(node);
6326
- this.addToGhost(node.key);
5762
+ var BoundedCache = class {
5763
+ constructor(maxSize) {
5764
+ this.map = /* @__PURE__ */ new Map();
5765
+ this.ghost = /* @__PURE__ */ new Set();
5766
+ this.smallHead = null;
5767
+ this.smallTail = null;
5768
+ this.smallSize = 0;
5769
+ this.mainHead = null;
5770
+ this.mainTail = null;
5771
+ this.mainSize = 0;
5772
+ this.maxSize = maxSize;
5773
+ this.smallLimit = Math.max(1, Math.floor(maxSize * 0.1));
5774
+ this.mainLimit = maxSize - this.smallLimit;
5775
+ this.ghostLimit = this.mainLimit;
5776
+ }
5777
+ get size() {
5778
+ return this.map.size;
5779
+ }
5780
+ get(key) {
5781
+ const node = this.map.get(key);
5782
+ if (!node) return void 0;
5783
+ node.freq = Math.min(node.freq + 1, 3);
5784
+ return node.value;
5785
+ }
5786
+ set(key, value) {
5787
+ const existing = this.map.get(key);
5788
+ if (existing) {
5789
+ existing.value = value;
5790
+ return this;
5791
+ }
5792
+ if (this.ghost.has(key)) {
5793
+ this.ghost.delete(key);
5794
+ const node2 = this.createNode(key, value, "main");
5795
+ this.map.set(key, node2);
5796
+ this.pushMain(node2);
5797
+ if (this.mainSize > this.mainLimit) this.evictMain();
5798
+ return this;
5799
+ }
5800
+ const node = this.createNode(key, value, "small");
5801
+ this.map.set(key, node);
5802
+ this.pushSmall(node);
5803
+ if (this.size > this.maxSize) {
5804
+ if (this.smallSize > this.smallLimit) this.evictSmall();
5805
+ else this.evictMain();
5806
+ }
5807
+ return this;
5808
+ }
5809
+ has(key) {
5810
+ return this.map.has(key);
5811
+ }
5812
+ delete(key) {
5813
+ const node = this.map.get(key);
5814
+ if (!node) return false;
5815
+ this.map.delete(key);
5816
+ this.removeNode(node);
5817
+ return true;
5818
+ }
5819
+ clear() {
5820
+ this.map.clear();
5821
+ this.ghost.clear();
5822
+ this.smallHead = this.smallTail = null;
5823
+ this.mainHead = this.mainTail = null;
5824
+ this.smallSize = this.mainSize = 0;
5825
+ }
5826
+ keys() {
5827
+ return withDispose(
5828
+ (function* (self) {
5829
+ for (const key of self.map.keys()) yield key;
5830
+ })(this)
5831
+ );
5832
+ }
5833
+ values() {
5834
+ return withDispose(
5835
+ (function* (self) {
5836
+ for (const node of self.map.values()) yield node.value;
5837
+ })(this)
5838
+ );
5839
+ }
5840
+ entries() {
5841
+ return withDispose(
5842
+ (function* (self) {
5843
+ for (const [key, node] of self.map.entries())
5844
+ yield [key, node.value];
5845
+ })(this)
5846
+ );
5847
+ }
5848
+ forEach(callbackfn, thisArg) {
5849
+ for (const [key, node] of this.map.entries()) {
5850
+ callbackfn.call(thisArg, node.value, key, this);
5851
+ }
5852
+ }
5853
+ [Symbol.iterator]() {
5854
+ return this.entries();
5855
+ }
5856
+ get [Symbol.toStringTag]() {
5857
+ return "BoundedCache";
5858
+ }
5859
+ createNode(key, value, queue) {
5860
+ return { key, value, freq: 0, queue, prev: null, next: null };
5861
+ }
5862
+ pushSmall(node) {
5863
+ node.next = this.smallHead;
5864
+ node.prev = null;
5865
+ if (this.smallHead) this.smallHead.prev = node;
5866
+ else this.smallTail = node;
5867
+ this.smallHead = node;
5868
+ this.smallSize++;
5869
+ }
5870
+ pushMain(node) {
5871
+ node.next = this.mainHead;
5872
+ node.prev = null;
5873
+ if (this.mainHead) this.mainHead.prev = node;
5874
+ else this.mainTail = node;
5875
+ this.mainHead = node;
5876
+ this.mainSize++;
5877
+ }
5878
+ popSmall() {
5879
+ if (!this.smallTail) return null;
5880
+ const node = this.smallTail;
5881
+ this.smallTail = node.prev;
5882
+ if (this.smallTail) this.smallTail.next = null;
5883
+ else this.smallHead = null;
5884
+ node.prev = null;
5885
+ node.next = null;
5886
+ this.smallSize--;
5887
+ return node;
5888
+ }
5889
+ popMain() {
5890
+ if (!this.mainTail) return null;
5891
+ const node = this.mainTail;
5892
+ this.mainTail = node.prev;
5893
+ if (this.mainTail) this.mainTail.next = null;
5894
+ else this.mainHead = null;
5895
+ node.prev = null;
5896
+ node.next = null;
5897
+ this.mainSize--;
5898
+ return node;
5899
+ }
5900
+ removeNode(node) {
5901
+ this.unlinkNode(node);
5902
+ if (node.queue === "small") {
5903
+ if (node === this.smallHead) this.smallHead = node.next;
5904
+ if (node === this.smallTail) this.smallTail = node.prev;
5905
+ this.smallSize--;
5906
+ } else {
5907
+ if (node === this.mainHead) this.mainHead = node.next;
5908
+ if (node === this.mainTail) this.mainTail = node.prev;
5909
+ this.mainSize--;
5910
+ }
5911
+ node.prev = null;
5912
+ node.next = null;
5913
+ }
5914
+ unlinkNode(node) {
5915
+ if (node.prev) node.prev.next = node.next;
5916
+ if (node.next) node.next.prev = node.prev;
5917
+ }
5918
+ shouldPromoteFromSmall(node) {
5919
+ return node.freq > 1;
5920
+ }
5921
+ shouldRetryInMain(node) {
5922
+ return node.freq >= 1;
5923
+ }
5924
+ promoteToMain(node) {
5925
+ node.queue = "main";
5926
+ this.pushMain(node);
5927
+ }
5928
+ addToGhost(key) {
5929
+ this.ghost.add(key);
5930
+ if (this.ghost.size <= this.ghostLimit) return;
5931
+ const firstGhost = this.ghost.values().next().value;
5932
+ if (firstGhost !== void 0) this.ghost.delete(firstGhost);
5933
+ }
5934
+ evictFromCache(node) {
5935
+ this.map.delete(node.key);
5936
+ }
5937
+ evictSmall() {
5938
+ while (this.smallSize > 0) {
5939
+ const node = this.popSmall();
5940
+ if (!node) return;
5941
+ if (this.shouldPromoteFromSmall(node)) {
5942
+ this.promoteToMain(node);
5943
+ if (this.mainSize > this.mainLimit) {
5944
+ this.evictMain();
6327
5945
  return;
6328
5946
  }
5947
+ continue;
6329
5948
  }
6330
- evictMain() {
6331
- while (this.mainSize > 0) {
6332
- const node = this.popMain();
6333
- if (!node) return;
6334
- if (this.shouldRetryInMain(node)) {
6335
- node.freq--;
6336
- this.pushMain(node);
6337
- continue;
6338
- }
6339
- this.evictFromCache(node);
6340
- return;
6341
- }
5949
+ this.evictFromCache(node);
5950
+ this.addToGhost(node.key);
5951
+ return;
5952
+ }
5953
+ }
5954
+ evictMain() {
5955
+ while (this.mainSize > 0) {
5956
+ const node = this.popMain();
5957
+ if (!node) return;
5958
+ if (this.shouldRetryInMain(node)) {
5959
+ node.freq--;
5960
+ this.pushMain(node);
5961
+ continue;
6342
5962
  }
6343
- };
5963
+ this.evictFromCache(node);
5964
+ return;
5965
+ }
6344
5966
  }
6345
- });
5967
+ };
5968
+ function createBoundedCache(maxSize) {
5969
+ return new BoundedCache(maxSize);
5970
+ }
6346
5971
 
6347
5972
  // src/fast-path.ts
6348
5973
  function getIdField(model) {
@@ -6504,17 +6129,36 @@ function tryFastPath(model, method, args, dialect) {
6504
6129
  }
6505
6130
  return null;
6506
6131
  }
6507
- var init_fast_path = __esm({
6508
- "src/fast-path.ts"() {
6509
- init_sql_utils();
6510
- init_constants();
6511
- init_type_guards();
6512
- init_normalize_value();
6513
- init_query_cache();
6514
- }
6515
- });
6516
6132
 
6517
6133
  // src/query-cache.ts
6134
+ var _hits, _misses;
6135
+ var QueryCacheStats = class {
6136
+ constructor() {
6137
+ __privateAdd(this, _hits, 0);
6138
+ __privateAdd(this, _misses, 0);
6139
+ }
6140
+ hit() {
6141
+ __privateWrapper(this, _hits)._++;
6142
+ }
6143
+ miss() {
6144
+ __privateWrapper(this, _misses)._++;
6145
+ }
6146
+ reset() {
6147
+ __privateSet(this, _hits, 0);
6148
+ __privateSet(this, _misses, 0);
6149
+ }
6150
+ get snapshot() {
6151
+ return Object.freeze({
6152
+ hits: __privateGet(this, _hits),
6153
+ misses: __privateGet(this, _misses),
6154
+ size: queryCache.size
6155
+ });
6156
+ }
6157
+ };
6158
+ _hits = new WeakMap();
6159
+ _misses = new WeakMap();
6160
+ var queryCache = createBoundedCache(1e3);
6161
+ var queryCacheStats = new QueryCacheStats();
6518
6162
  function makeAlias(name) {
6519
6163
  const base = name.toLowerCase().replace(/[^a-z0-9_]/g, "_").slice(0, 50);
6520
6164
  const safe = /^[a-z_]/.test(base) ? base : `_${base}`;
@@ -6744,73 +6388,99 @@ function buildSQLWithCache(model, models, method, args, dialect) {
6744
6388
  });
6745
6389
  return result;
6746
6390
  }
6747
- var _hits, _misses, QueryCacheStats, queryCache, queryCacheStats;
6748
- var init_query_cache = __esm({
6749
- "src/query-cache.ts"() {
6750
- init_where();
6751
- init_select();
6752
- init_aggregates();
6753
- init_sql_utils();
6754
- init_constants();
6755
- init_s3_fifo();
6756
- init_fast_path();
6757
- QueryCacheStats = class {
6758
- constructor() {
6759
- __privateAdd(this, _hits, 0);
6760
- __privateAdd(this, _misses, 0);
6761
- }
6762
- hit() {
6763
- __privateWrapper(this, _hits)._++;
6764
- }
6765
- miss() {
6766
- __privateWrapper(this, _misses)._++;
6391
+
6392
+ // src/builder/select/row-transformers.ts
6393
+ function transformAggregateRow(row) {
6394
+ if (!row || typeof row !== "object") return row;
6395
+ const result = {};
6396
+ for (const key in row) {
6397
+ if (!Object.prototype.hasOwnProperty.call(row, key)) continue;
6398
+ let value = row[key];
6399
+ if (typeof value === "string" && /^-?\d+(\.\d+)?$/.test(value)) {
6400
+ value = value.includes(".") ? parseFloat(value) : parseInt(value, 10);
6401
+ }
6402
+ const dotIndex = key.indexOf(".");
6403
+ if (dotIndex === -1) {
6404
+ result[key] = value;
6405
+ continue;
6406
+ }
6407
+ const prefix = key.slice(0, dotIndex);
6408
+ const suffix = key.slice(dotIndex + 1);
6409
+ if (AGGREGATE_PREFIXES.has(prefix)) {
6410
+ if (!result[prefix]) {
6411
+ result[prefix] = {};
6767
6412
  }
6768
- reset() {
6769
- __privateSet(this, _hits, 0);
6770
- __privateSet(this, _misses, 0);
6413
+ result[prefix][suffix] = value;
6414
+ } else {
6415
+ result[key] = value;
6416
+ }
6417
+ }
6418
+ return result;
6419
+ }
6420
+ function extractCountValue(row) {
6421
+ if (!row || typeof row !== "object") return 0;
6422
+ if ("_count._all" in row) {
6423
+ const value = row["_count._all"];
6424
+ if (typeof value === "string") return parseInt(value, 10);
6425
+ return value;
6426
+ }
6427
+ if ("_count" in row && row["_count"] && typeof row["_count"] === "object") {
6428
+ const countObj = row["_count"];
6429
+ if ("_all" in countObj) {
6430
+ const value = countObj["_all"];
6431
+ if (typeof value === "string") return parseInt(value, 10);
6432
+ return value;
6433
+ }
6434
+ }
6435
+ const keys = Object.keys(row);
6436
+ for (const key of keys) {
6437
+ if (key.includes("count") || key.includes("COUNT")) {
6438
+ const value = row[key];
6439
+ if (typeof value === "number" || typeof value === "bigint") {
6440
+ return value;
6771
6441
  }
6772
- get snapshot() {
6773
- return Object.freeze({
6774
- hits: __privateGet(this, _hits),
6775
- misses: __privateGet(this, _misses),
6776
- size: queryCache.size
6777
- });
6442
+ if (typeof value === "string") {
6443
+ return parseInt(value, 10);
6778
6444
  }
6779
- };
6780
- _hits = new WeakMap();
6781
- _misses = new WeakMap();
6782
- queryCache = createBoundedCache(1e3);
6783
- queryCacheStats = new QueryCacheStats();
6445
+ }
6784
6446
  }
6785
- });
6447
+ return 0;
6448
+ }
6449
+ function getRowTransformer(method) {
6450
+ if (method === "count") {
6451
+ return extractCountValue;
6452
+ }
6453
+ if (method === "groupBy" || method === "aggregate") {
6454
+ return transformAggregateRow;
6455
+ }
6456
+ return null;
6457
+ }
6786
6458
 
6787
6459
  // src/result-transformers.ts
6788
6460
  function transformQueryResults(method, results) {
6789
- var _a;
6461
+ var _a, _b;
6790
6462
  if (method === "findFirst" || method === "findUnique") {
6791
6463
  if (Array.isArray(results)) {
6792
6464
  return (_a = results[0]) != null ? _a : null;
6793
6465
  }
6794
6466
  }
6467
+ if (method === "aggregate") {
6468
+ if (Array.isArray(results)) {
6469
+ return (_b = results[0]) != null ? _b : null;
6470
+ }
6471
+ }
6795
6472
  if (method === "count") {
6796
6473
  if (Array.isArray(results) && results.length > 0) {
6797
- const row = results[0];
6798
- if (typeof row === "number" || typeof row === "bigint") {
6799
- return row;
6800
- }
6801
- if (row && typeof row === "object" && "_count._all" in row) {
6802
- return row["_count._all"];
6474
+ const first = results[0];
6475
+ if (typeof first === "number" || typeof first === "bigint") {
6476
+ return first;
6803
6477
  }
6804
- return row;
6478
+ return extractCountValue(first);
6805
6479
  }
6806
6480
  return 0;
6807
6481
  }
6808
6482
  return results;
6809
6483
  }
6810
- var init_result_transformers = __esm({
6811
- "src/result-transformers.ts"() {
6812
- }
6813
- });
6814
6484
 
6815
6485
  // src/batch.ts
6816
6486
  function quoteBatchIdent(id) {
@@ -7457,12 +7127,29 @@ function parseCountValue(value) {
7457
7127
  }
7458
7128
  return 0;
7459
7129
  }
7460
- function parseBatchCountResults(row, count) {
7130
+ function parseBatchCountResults(row, queryCount) {
7461
7131
  const results = [];
7462
- for (let i = 0; i < count; i++) {
7463
- const key = `count_${i}`;
7132
+ for (let i = 0; i < queryCount; i++) {
7133
+ const key = `_count_${i}`;
7464
7134
  const value = row[key];
7465
- results.push(parseCountValue(value));
7135
+ if (value === null || value === void 0) {
7136
+ results.push(0);
7137
+ continue;
7138
+ }
7139
+ if (typeof value === "number") {
7140
+ results.push(value);
7141
+ continue;
7142
+ }
7143
+ if (typeof value === "bigint") {
7144
+ results.push(Number(value));
7145
+ continue;
7146
+ }
7147
+ if (typeof value === "string") {
7148
+ const parsed = parseInt(value, 10);
7149
+ results.push(isNaN(parsed) ? 0 : parsed);
7150
+ continue;
7151
+ }
7152
+ results.push(0);
7466
7153
  }
7467
7154
  return results;
7468
7155
  }
@@ -7647,13 +7334,6 @@ function parseBatchResults(row, keys, queries, aliases, modelMap) {
7647
7334
  }
7648
7335
  return results;
7649
7336
  }
7650
- var init_batch = __esm({
7651
- "src/batch.ts"() {
7652
- init_query_cache();
7653
- init_result_transformers();
7654
- init_sql_utils();
7655
- }
7656
- });
7657
7337
 
7658
7338
  // src/transaction.ts
7659
7339
  function isolationLevelToPostgresKeyword(level) {
@@ -7724,7 +7404,11 @@ function createTransactionExecutor(deps) {
7724
7404
  q.args || {},
7725
7405
  dialect
7726
7406
  );
7727
- const rawResults = yield sql.unsafe(sqlStr, params);
7407
+ let rawResults = yield sql.unsafe(sqlStr, params);
7408
+ const rowTransformer = getRowTransformer(q.method);
7409
+ if (rowTransformer && Array.isArray(rawResults)) {
7410
+ rawResults = rawResults.map(rowTransformer);
7411
+ }
7728
7412
  results.push(transformQueryResults(q.method, rawResults));
7729
7413
  }
7730
7414
  return results;
@@ -7734,12 +7418,6 @@ function createTransactionExecutor(deps) {
7734
7418
  }
7735
7419
  };
7736
7420
  }
7737
- var init_transaction = __esm({
7738
- "src/transaction.ts"() {
7739
- init_query_cache();
7740
- init_result_transformers();
7741
- }
7742
- });
7743
7421
 
7744
7422
  // src/builder/shared/key-utils.ts
7745
7423
  function buildCompositeKey(row, fields) {
@@ -7774,10 +7452,6 @@ function buildCompositeKey(row, fields) {
7774
7452
  }
7775
7453
  return parts.join("");
7776
7454
  }
7777
- var init_key_utils = __esm({
7778
- "src/builder/shared/key-utils.ts"() {
7779
- }
7780
- });
7781
7455
 
7782
7456
  // src/builder/select/reducer.ts
7783
7457
  function buildRelationScalarCols(relModel, relPath, includeAllScalars, selectedScalarFields) {
@@ -7962,17 +7636,10 @@ function reduceFlatRows(rows, config) {
7962
7636
  }
7963
7637
  return Array.from(resultMap.values());
7964
7638
  }
7965
- var init_reducer = __esm({
7966
- "src/builder/select/reducer.ts"() {
7967
- init_model_field_cache();
7968
- init_primary_key_utils();
7969
- init_key_utils();
7970
- init_model_field_cache();
7971
- init_relation_utils();
7972
- }
7973
- });
7974
7639
 
7975
7640
  // src/builder/select/segment-planner.ts
7641
+ var HARD_FANOUT_CAP = 5e3;
7642
+ var MAX_ESTIMATED_ROWS = Number.MAX_SAFE_INTEGER / 1e3;
7976
7643
  function isList(field) {
7977
7644
  return typeof field.type === "string" && field.type.endsWith("[]");
7978
7645
  }
@@ -8133,17 +7800,6 @@ function planQueryStrategy(params) {
8133
7800
  const filteredArgs = removeRelationsFromArgs(args, toRemove);
8134
7801
  return { filteredArgs, whereInSegments };
8135
7802
  }
8136
- var HARD_FANOUT_CAP, MAX_ESTIMATED_ROWS;
8137
- var init_segment_planner = __esm({
8138
- "src/builder/select/segment-planner.ts"() {
8139
- init_type_guards();
8140
- init_relation_extraction_utils();
8141
- init_relation_key_utils();
8142
- init_relation_utils();
8143
- HARD_FANOUT_CAP = 5e3;
8144
- MAX_ESTIMATED_ROWS = Number.MAX_SAFE_INTEGER / 1e3;
8145
- }
8146
- });
8147
7803
 
8148
7804
  // src/builder/shared/where-in-executor-base.ts
8149
7805
  function getParamLimit(dialect) {
@@ -8250,13 +7906,6 @@ function executeSegmentBase(segment, parentRows, allModels, modelMap, dialect, e
8250
7906
  stitchResults(parentRows, segment, allChildRows, needsStripFk);
8251
7907
  });
8252
7908
  }
8253
- var init_where_in_executor_base = __esm({
8254
- "src/builder/shared/where-in-executor-base.ts"() {
8255
- init_src();
8256
- init_reducer();
8257
- init_type_guards();
8258
- }
8259
- });
8260
7909
 
8261
7910
  // src/builder/where-in-executor.ts
8262
7911
  function executeWhereInSegments(params) {
@@ -8276,135 +7925,122 @@ function executeWhereInSegments(params) {
8276
7925
  }
8277
7926
  });
8278
7927
  }
8279
- var init_where_in_executor = __esm({
8280
- "src/builder/where-in-executor.ts"() {
8281
- init_where_in_executor_base();
8282
- }
8283
- });
8284
7928
 
8285
7929
  // src/builder/select/core-reducer.ts
8286
- var getOrCreateRelationMap, getOrCreateChildMap, createParentObject, createChildObject, extractChildKey, attachChildToParent, createRelationProcessor, createCoreReducer;
8287
- var init_core_reducer = __esm({
8288
- "src/builder/select/core-reducer.ts"() {
8289
- init_primary_key_utils();
8290
- init_key_utils();
8291
- init_model_field_cache();
8292
- getOrCreateRelationMap = (relationMaps, parent) => {
8293
- let relMap = relationMaps.get(parent);
8294
- if (!relMap) {
8295
- relMap = /* @__PURE__ */ new Map();
8296
- relationMaps.set(parent, relMap);
8297
- }
8298
- return relMap;
8299
- };
8300
- getOrCreateChildMap = (relMap, path) => {
8301
- let childMap = relMap.get(path);
8302
- if (!childMap) {
8303
- childMap = /* @__PURE__ */ new Map();
8304
- relMap.set(path, childMap);
8305
- }
8306
- return childMap;
8307
- };
8308
- createParentObject = (row, scalarFields, jsonSet, includedRelations) => {
8309
- const parent = {};
8310
- for (const field of scalarFields) {
8311
- if (!(field.name in row)) continue;
8312
- parent[field.name] = maybeParseJson(row[field.name], jsonSet, field.name);
8313
- }
8314
- for (const rel of includedRelations) {
8315
- parent[rel.name] = rel.cardinality === "many" ? [] : null;
8316
- }
8317
- return parent;
8318
- };
8319
- createChildObject = (row, rel) => {
8320
- const child = {};
8321
- for (const spec of rel.scalarCols) {
8322
- if (!(spec.colName in row)) continue;
8323
- child[spec.fieldName] = parseJsonIfNeeded(spec.isJson, row[spec.colName]);
8324
- }
7930
+ var getOrCreateRelationMap = (relationMaps, parent) => {
7931
+ let relMap = relationMaps.get(parent);
7932
+ if (!relMap) {
7933
+ relMap = /* @__PURE__ */ new Map();
7934
+ relationMaps.set(parent, relMap);
7935
+ }
7936
+ return relMap;
7937
+ };
7938
+ var getOrCreateChildMap = (relMap, path) => {
7939
+ let childMap = relMap.get(path);
7940
+ if (!childMap) {
7941
+ childMap = /* @__PURE__ */ new Map();
7942
+ relMap.set(path, childMap);
7943
+ }
7944
+ return childMap;
7945
+ };
7946
+ var createParentObject = (row, scalarFields, jsonSet, includedRelations) => {
7947
+ const parent = {};
7948
+ for (const field of scalarFields) {
7949
+ if (!(field.name in row)) continue;
7950
+ parent[field.name] = maybeParseJson(row[field.name], jsonSet, field.name);
7951
+ }
7952
+ for (const rel of includedRelations) {
7953
+ parent[rel.name] = rel.cardinality === "many" ? [] : null;
7954
+ }
7955
+ return parent;
7956
+ };
7957
+ var createChildObject = (row, rel) => {
7958
+ const child = {};
7959
+ for (const spec of rel.scalarCols) {
7960
+ if (!(spec.colName in row)) continue;
7961
+ child[spec.fieldName] = parseJsonIfNeeded(spec.isJson, row[spec.colName]);
7962
+ }
7963
+ if (rel.nestedIncludes) {
7964
+ for (const nested of rel.nestedIncludes.includedRelations) {
7965
+ child[nested.name] = nested.cardinality === "many" ? [] : null;
7966
+ }
7967
+ }
7968
+ return child;
7969
+ };
7970
+ var extractChildKey = (row, rel) => {
7971
+ const cols = rel.primaryKeyFields.map((f) => `${rel.path}.${f}`);
7972
+ return buildCompositeKey(row, cols);
7973
+ };
7974
+ var attachChildToParent = (parent, child, rel) => {
7975
+ if (rel.cardinality === "many") {
7976
+ parent[rel.name].push(child);
7977
+ } else {
7978
+ parent[rel.name] = child;
7979
+ }
7980
+ };
7981
+ var createRelationProcessor = (relationMaps) => {
7982
+ const processRelation2 = (parent, rel, row) => {
7983
+ const childKey = extractChildKey(row, rel);
7984
+ if (!childKey) return;
7985
+ const relMap = getOrCreateRelationMap(relationMaps, parent);
7986
+ const childMap = getOrCreateChildMap(relMap, rel.path);
7987
+ if (childMap.has(childKey)) {
7988
+ const existing = childMap.get(childKey);
8325
7989
  if (rel.nestedIncludes) {
8326
7990
  for (const nested of rel.nestedIncludes.includedRelations) {
8327
- child[nested.name] = nested.cardinality === "many" ? [] : null;
7991
+ processRelation2(existing, nested, row);
8328
7992
  }
8329
7993
  }
8330
- return child;
8331
- };
8332
- extractChildKey = (row, rel) => {
8333
- const cols = rel.primaryKeyFields.map((f) => `${rel.path}.${f}`);
8334
- return buildCompositeKey(row, cols);
8335
- };
8336
- attachChildToParent = (parent, child, rel) => {
8337
- if (rel.cardinality === "many") {
8338
- parent[rel.name].push(child);
8339
- } else {
8340
- parent[rel.name] = child;
7994
+ return;
7995
+ }
7996
+ const child = createChildObject(row, rel);
7997
+ childMap.set(childKey, child);
7998
+ attachChildToParent(parent, child, rel);
7999
+ if (rel.nestedIncludes) {
8000
+ for (const nested of rel.nestedIncludes.includedRelations) {
8001
+ processRelation2(child, nested, row);
8341
8002
  }
8342
- };
8343
- createRelationProcessor = (relationMaps) => {
8344
- const processRelation2 = (parent, rel, row) => {
8345
- const childKey = extractChildKey(row, rel);
8346
- if (!childKey) return;
8347
- const relMap = getOrCreateRelationMap(relationMaps, parent);
8348
- const childMap = getOrCreateChildMap(relMap, rel.path);
8349
- if (childMap.has(childKey)) {
8350
- const existing = childMap.get(childKey);
8351
- if (rel.nestedIncludes) {
8352
- for (const nested of rel.nestedIncludes.includedRelations) {
8353
- processRelation2(existing, nested, row);
8354
- }
8355
- }
8356
- return;
8357
- }
8358
- const child = createChildObject(row, rel);
8359
- childMap.set(childKey, child);
8360
- attachChildToParent(parent, child, rel);
8361
- if (rel.nestedIncludes) {
8362
- for (const nested of rel.nestedIncludes.includedRelations) {
8363
- processRelation2(child, nested, row);
8364
- }
8365
- }
8366
- };
8367
- return processRelation2;
8368
- };
8369
- createCoreReducer = (config) => {
8370
- const parentMap = /* @__PURE__ */ new Map();
8371
- const relationMaps = /* @__PURE__ */ new WeakMap();
8372
- const scalarFields = config.parentModel.fields.filter((f) => !f.isRelation);
8373
- const jsonSet = getJsonFieldSet(config.parentModel);
8374
- const parentPkFields = getPrimaryKeyFields(config.parentModel);
8375
- const includedRelations = config.includedRelations;
8376
- const extractParentKey = (row) => buildCompositeKey(row, parentPkFields);
8377
- const processRelation2 = createRelationProcessor(relationMaps);
8378
- const processRow = (row) => {
8379
- const parentKey = extractParentKey(row);
8380
- if (!parentKey) return null;
8381
- const parent = parentMap.has(parentKey) ? parentMap.get(parentKey) : (() => {
8382
- const newParent = createParentObject(
8383
- row,
8384
- scalarFields,
8385
- jsonSet,
8386
- includedRelations
8387
- );
8388
- parentMap.set(parentKey, newParent);
8389
- return newParent;
8390
- })();
8391
- for (const rel of includedRelations) {
8392
- processRelation2(parent, rel, row);
8393
- }
8394
- return parentKey;
8395
- };
8396
- return {
8397
- processRow,
8398
- getParent: (key) => {
8399
- var _a;
8400
- return (_a = parentMap.get(key)) != null ? _a : null;
8401
- },
8402
- getAllParents: () => Array.from(parentMap.values()),
8403
- getParentMap: () => parentMap
8404
- };
8405
- };
8406
- }
8407
- });
8003
+ }
8004
+ };
8005
+ return processRelation2;
8006
+ };
8007
+ var createCoreReducer = (config) => {
8008
+ const parentMap = /* @__PURE__ */ new Map();
8009
+ const relationMaps = /* @__PURE__ */ new WeakMap();
8010
+ const scalarFields = config.parentModel.fields.filter((f) => !f.isRelation);
8011
+ const jsonSet = getJsonFieldSet(config.parentModel);
8012
+ const parentPkFields = getPrimaryKeyFields(config.parentModel);
8013
+ const includedRelations = config.includedRelations;
8014
+ const extractParentKey = (row) => buildCompositeKey(row, parentPkFields);
8015
+ const processRelation2 = createRelationProcessor(relationMaps);
8016
+ const processRow = (row) => {
8017
+ const parentKey = extractParentKey(row);
8018
+ if (!parentKey) return null;
8019
+ const parent = parentMap.has(parentKey) ? parentMap.get(parentKey) : (() => {
8020
+ const newParent = createParentObject(
8021
+ row,
8022
+ scalarFields,
8023
+ jsonSet,
8024
+ includedRelations
8025
+ );
8026
+ parentMap.set(parentKey, newParent);
8027
+ return newParent;
8028
+ })();
8029
+ for (const rel of includedRelations) {
8030
+ processRelation2(parent, rel, row);
8031
+ }
8032
+ return parentKey;
8033
+ };
8034
+ return {
8035
+ processRow,
8036
+ getParent: (key) => {
8037
+ var _a;
8038
+ return (_a = parentMap.get(key)) != null ? _a : null;
8039
+ },
8040
+ getAllParents: () => Array.from(parentMap.values()),
8041
+ getParentMap: () => parentMap
8042
+ };
8043
+ };
8408
8044
 
8409
8045
  // src/builder/select/streaming-reducer.ts
8410
8046
  function createStreamingReducer(config) {
@@ -8424,11 +8060,6 @@ function createStreamingReducer(config) {
8424
8060
  }
8425
8061
  };
8426
8062
  }
8427
- var init_streaming_reducer = __esm({
8428
- "src/builder/select/streaming-reducer.ts"() {
8429
- init_core_reducer();
8430
- }
8431
- });
8432
8063
 
8433
8064
  // src/builder/select/streaming-progressive-reducer.ts
8434
8065
  function createProgressiveReducer(config) {
@@ -8463,11 +8094,6 @@ function createProgressiveReducer(config) {
8463
8094
  }
8464
8095
  };
8465
8096
  }
8466
- var init_streaming_progressive_reducer = __esm({
8467
- "src/builder/select/streaming-progressive-reducer.ts"() {
8468
- init_core_reducer();
8469
- }
8470
- });
8471
8097
 
8472
8098
  // src/builder/select/streaming-where-in-executor.ts
8473
8099
  function executeWhereInSegmentsStreaming(params) {
@@ -8595,77 +8221,9 @@ function buildChildArgs2(relArgs, fkFieldName, parentIds) {
8595
8221
  base.where = existingWhere ? { AND: [existingWhere, inCondition] } : inCondition;
8596
8222
  return base;
8597
8223
  }
8598
- var init_streaming_where_in_executor = __esm({
8599
- "src/builder/select/streaming-where-in-executor.ts"() {
8600
- init_primary_key_utils();
8601
- init_src();
8602
- init_reducer();
8603
- }
8604
- });
8605
-
8606
- // src/builder/select/row-transformers.ts
8607
- function transformAggregateRow(row) {
8608
- if (!row || typeof row !== "object") return row;
8609
- const result = {};
8610
- for (const key in row) {
8611
- if (!Object.prototype.hasOwnProperty.call(row, key)) continue;
8612
- const value = row[key];
8613
- const dotIndex = key.indexOf(".");
8614
- if (dotIndex === -1) {
8615
- result[key] = value;
8616
- continue;
8617
- }
8618
- const prefix = key.slice(0, dotIndex);
8619
- const suffix = key.slice(dotIndex + 1);
8620
- if (AGGREGATE_PREFIXES.has(prefix)) {
8621
- if (!result[prefix]) {
8622
- result[prefix] = {};
8623
- }
8624
- result[prefix][suffix] = value;
8625
- } else {
8626
- result[key] = value;
8627
- }
8628
- }
8629
- return result;
8630
- }
8631
- function extractCountValue(row) {
8632
- if (!row || typeof row !== "object") return 0;
8633
- if ("_count._all" in row) {
8634
- return row["_count._all"];
8635
- }
8636
- if ("_count" in row && row["_count"] && typeof row["_count"] === "object") {
8637
- const countObj = row["_count"];
8638
- if ("_all" in countObj) {
8639
- return countObj["_all"];
8640
- }
8641
- }
8642
- const keys = Object.keys(row);
8643
- for (const key of keys) {
8644
- if (key.includes("count") || key.includes("COUNT")) {
8645
- const value = row[key];
8646
- if (typeof value === "number" || typeof value === "bigint") {
8647
- return value;
8648
- }
8649
- }
8650
- }
8651
- return 0;
8652
- }
8653
- function getRowTransformer(method) {
8654
- if (method === "count") {
8655
- return extractCountValue;
8656
- }
8657
- if (method === "groupBy" || method === "aggregate") {
8658
- return transformAggregateRow;
8659
- }
8660
- return null;
8661
- }
8662
- var init_row_transformers = __esm({
8663
- "src/builder/select/row-transformers.ts"() {
8664
- init_constants();
8665
- }
8666
- });
8667
8224
 
8668
8225
  // src/generated-runtime.ts
8226
+ var SQLITE_STMT_CACHE = /* @__PURE__ */ new WeakMap();
8669
8227
  function getOrPrepareStatement(client, sql) {
8670
8228
  let cache = SQLITE_STMT_CACHE.get(client);
8671
8229
  if (!cache) {
@@ -8692,66 +8250,39 @@ function normalizeParams(params) {
8692
8250
  function executePostgresQuery(client, sql, params, method, requiresReduction, includeSpec, model, allModels) {
8693
8251
  return __async(this, null, function* () {
8694
8252
  const normalizedParams = normalizeParams(params);
8695
- const query = client.unsafe(sql, normalizedParams);
8696
- if (requiresReduction && includeSpec && model) {
8253
+ const rowTransformer = getRowTransformer(method);
8254
+ if (requiresReduction && includeSpec) {
8697
8255
  const config = buildReducerConfig(model, includeSpec, allModels);
8698
- const { createStreamingReducer: createStreamingReducer2 } = yield Promise.resolve().then(() => (init_src(), src_exports));
8699
- const reducer = createStreamingReducer2(config);
8700
- yield query.forEach((row) => {
8701
- reducer.processRow(row);
8256
+ const reducer = createStreamingReducer(config);
8257
+ yield client.unsafe(sql, normalizedParams).forEach((row) => {
8258
+ reducer.processRow(rowTransformer ? rowTransformer(row) : row);
8702
8259
  });
8703
8260
  return reducer.getResults();
8704
8261
  }
8705
- if (method === "count") {
8706
- const results2 = [];
8707
- yield query.forEach((row) => {
8708
- results2.push(extractCountValue(row));
8709
- });
8710
- return results2;
8711
- }
8712
- if (method === "groupBy" || method === "aggregate") {
8713
- const results2 = [];
8714
- yield query.forEach((row) => {
8715
- results2.push(transformAggregateRow(row));
8716
- });
8717
- return results2;
8718
- }
8719
8262
  const results = [];
8720
- yield query.forEach((row) => {
8721
- results.push(row);
8263
+ yield client.unsafe(sql, normalizedParams).forEach((row) => {
8264
+ results.push(rowTransformer ? rowTransformer(row) : row);
8722
8265
  });
8723
8266
  return results;
8724
8267
  });
8725
8268
  }
8726
8269
  function executeSqliteQuery(client, sql, params, method, requiresReduction, includeSpec, model, allModels) {
8727
8270
  const normalizedParams = normalizeParams(params);
8728
- const stmt = getOrPrepareStatement(client, sql);
8729
- if (shouldSqliteUseGet(method)) {
8730
- const row = stmt.get(...normalizedParams);
8731
- if (row === void 0) {
8732
- return method === "count" ? [0] : [];
8733
- }
8734
- if (method === "count") {
8735
- return [extractCountValue(row)];
8736
- }
8737
- if (method === "aggregate") {
8738
- return [transformAggregateRow(row)];
8739
- }
8740
- return [row];
8741
- }
8742
- const rows = stmt.all(...normalizedParams);
8743
- if (method === "count") {
8744
- if (rows.length === 0) return [0];
8745
- return [extractCountValue(rows[0])];
8746
- }
8747
- if (method === "groupBy" || method === "aggregate") {
8748
- return rows.map((row) => transformAggregateRow(row));
8749
- }
8750
- if (requiresReduction && includeSpec && model) {
8271
+ const shouldTransform = method === "groupBy" || method === "aggregate" || method === "count";
8272
+ if (requiresReduction && includeSpec) {
8751
8273
  const config = buildReducerConfig(model, includeSpec, allModels);
8752
- return reduceFlatRows(rows, config);
8274
+ const stmt2 = getOrPrepareStatement(client, sql);
8275
+ const useGet2 = shouldSqliteUseGet(method);
8276
+ const rawResults2 = useGet2 ? stmt2.get(...normalizedParams) : stmt2.all(...normalizedParams);
8277
+ const results2 = Array.isArray(rawResults2) ? rawResults2 : [rawResults2];
8278
+ const transformed = shouldTransform ? results2.map(transformAggregateRow) : results2;
8279
+ return reduceFlatRows(transformed, config);
8753
8280
  }
8754
- return rows;
8281
+ const stmt = getOrPrepareStatement(client, sql);
8282
+ const useGet = shouldSqliteUseGet(method);
8283
+ const rawResults = useGet ? stmt.get(...normalizedParams) : stmt.all(...normalizedParams);
8284
+ const results = Array.isArray(rawResults) ? rawResults : [rawResults];
8285
+ return shouldTransform ? results.map(transformAggregateRow) : results;
8755
8286
  }
8756
8287
  function executeRaw(client, sql, params, dialect) {
8757
8288
  return __async(this, null, function* () {
@@ -8761,47 +8292,8 @@ function executeRaw(client, sql, params, dialect) {
8761
8292
  throw new Error("Raw execution for sqlite not supported in transactions");
8762
8293
  });
8763
8294
  }
8764
- var SQLITE_STMT_CACHE;
8765
- var init_generated_runtime = __esm({
8766
- "src/generated-runtime.ts"() {
8767
- init_src();
8768
- SQLITE_STMT_CACHE = /* @__PURE__ */ new WeakMap();
8769
- }
8770
- });
8771
8295
 
8772
8296
  // src/index.ts
8773
- var src_exports = {};
8774
- __export(src_exports, {
8775
- buildBatchCountSql: () => buildBatchCountSql,
8776
- buildBatchSql: () => buildBatchSql,
8777
- buildReducerConfig: () => buildReducerConfig,
8778
- buildSQL: () => buildSQL,
8779
- createPrismaSQL: () => createPrismaSQL,
8780
- createProgressiveReducer: () => createProgressiveReducer,
8781
- createStreamingReducer: () => createStreamingReducer,
8782
- createToSQL: () => createToSQL,
8783
- createTransactionExecutor: () => createTransactionExecutor,
8784
- executePostgresQuery: () => executePostgresQuery,
8785
- executeRaw: () => executeRaw,
8786
- executeSqliteQuery: () => executeSqliteQuery,
8787
- executeWhereInSegments: () => executeWhereInSegments,
8788
- executeWhereInSegmentsStreaming: () => executeWhereInSegmentsStreaming,
8789
- extractCountValue: () => extractCountValue,
8790
- generateAllSQL: () => generateAllSQL,
8791
- generateSQL: () => generateSQL2,
8792
- generateSQLByModel: () => generateSQLByModel,
8793
- getOrPrepareStatement: () => getOrPrepareStatement,
8794
- getRowTransformer: () => getRowTransformer,
8795
- normalizeParams: () => normalizeParams,
8796
- normalizeValue: () => normalizeValue,
8797
- parseBatchCountResults: () => parseBatchCountResults,
8798
- parseBatchResults: () => parseBatchResults,
8799
- planQueryStrategy: () => planQueryStrategy,
8800
- reduceFlatRows: () => reduceFlatRows,
8801
- shouldSqliteUseGet: () => shouldSqliteUseGet,
8802
- transformAggregateRow: () => transformAggregateRow,
8803
- transformQueryResults: () => transformQueryResults
8804
- });
8805
8297
  function buildSQL(model, models, method, args, dialect) {
8806
8298
  return buildSQLWithCache(model, models, method, args, dialect);
8807
8299
  }
@@ -8903,27 +8395,6 @@ function generateSQLByModel(directives) {
8903
8395
  }
8904
8396
  return byModel;
8905
8397
  }
8906
- var init_src = __esm({
8907
- "src/index.ts"() {
8908
- init_sql_builder_dialect();
8909
- init_sql_generator();
8910
- init_query_cache();
8911
- init_batch();
8912
- init_transaction();
8913
- init_result_transformers();
8914
- init_reducer();
8915
- init_segment_planner();
8916
- init_where_in_executor();
8917
- init_reducer();
8918
- init_normalize_value();
8919
- init_streaming_reducer();
8920
- init_streaming_progressive_reducer();
8921
- init_streaming_where_in_executor();
8922
- init_row_transformers();
8923
- init_generated_runtime();
8924
- }
8925
- });
8926
- init_src();
8927
8398
 
8928
8399
  export { buildBatchCountSql, buildBatchSql, buildReducerConfig, buildSQL, createPrismaSQL, createProgressiveReducer, createStreamingReducer, createToSQL, createTransactionExecutor, executePostgresQuery, executeRaw, executeSqliteQuery, executeWhereInSegments, executeWhereInSegmentsStreaming, extractCountValue, generateAllSQL, generateSQL2 as generateSQL, generateSQLByModel, getOrPrepareStatement, getRowTransformer, normalizeParams, normalizeValue, parseBatchCountResults, parseBatchResults, planQueryStrategy, reduceFlatRows, shouldSqliteUseGet, transformAggregateRow, transformQueryResults };
8929
8400
  //# sourceMappingURL=index.js.map