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