@warlock.js/cascade 4.4.0 → 4.6.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/CHANGELOG.md +29 -3
- package/cjs/index.cjs +933 -90
- package/cjs/index.cjs.map +1 -1
- package/esm/contracts/database-driver.contract.d.mts +27 -4
- package/esm/contracts/database-driver.contract.d.mts.map +1 -1
- package/esm/contracts/database-id-generator.contract.d.mts +38 -0
- package/esm/contracts/database-id-generator.contract.d.mts.map +1 -1
- package/esm/contracts/index.d.mts +1 -1
- package/esm/contracts/query-builder.contract.d.mts +27 -0
- package/esm/contracts/query-builder.contract.d.mts.map +1 -1
- package/esm/data-source/data-source.d.mts +21 -1
- package/esm/data-source/data-source.d.mts.map +1 -1
- package/esm/data-source/data-source.mjs +22 -0
- package/esm/data-source/data-source.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.d.mts +2 -2
- package/esm/drivers/mongodb/mongodb-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-id-generator.d.mts +98 -48
- package/esm/drivers/mongodb/mongodb-id-generator.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-id-generator.mjs +153 -59
- package/esm/drivers/mongodb/mongodb-id-generator.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts +25 -0
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.mjs +32 -0
- package/esm/drivers/mongodb/mongodb-query-builder.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts +36 -0
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs +80 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-dialect.d.mts +32 -4
- package/esm/drivers/postgres/postgres-dialect.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-dialect.mjs +57 -4
- package/esm/drivers/postgres/postgres-dialect.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-driver.d.mts +42 -0
- package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-driver.mjs +55 -6
- package/esm/drivers/postgres/postgres-driver.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.d.mts +32 -0
- package/esm/drivers/postgres/postgres-query-builder.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.mjs +47 -1
- package/esm/drivers/postgres/postgres-query-builder.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts +13 -2
- package/esm/drivers/postgres/postgres-query-parser.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.mjs +21 -4
- package/esm/drivers/postgres/postgres-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/types.d.mts +15 -0
- package/esm/drivers/postgres/types.d.mts.map +1 -1
- package/esm/drivers/sql/sql-dialect.contract.d.mts +20 -0
- package/esm/drivers/sql/sql-dialect.contract.d.mts.map +1 -1
- package/esm/expressions/aggregate-expressions.d.mts +71 -34
- package/esm/expressions/aggregate-expressions.d.mts.map +1 -1
- package/esm/expressions/aggregate-expressions.mjs +80 -7
- package/esm/expressions/aggregate-expressions.mjs.map +1 -1
- package/esm/expressions/column-expressions.d.mts +193 -0
- package/esm/expressions/column-expressions.d.mts.map +1 -0
- package/esm/expressions/column-expressions.mjs +152 -0
- package/esm/expressions/column-expressions.mjs.map +1 -0
- package/esm/index.d.mts +3 -2
- package/esm/index.mjs +2 -1
- package/esm/model/methods/write-methods.d.mts +29 -0
- package/esm/model/methods/write-methods.d.mts.map +1 -0
- package/esm/model/methods/write-methods.mjs +164 -2
- package/esm/model/methods/write-methods.mjs.map +1 -1
- package/esm/model/model.d.mts +64 -3
- package/esm/model/model.d.mts.map +1 -1
- package/esm/model/model.mjs +65 -3
- package/esm/model/model.mjs.map +1 -1
- package/esm/writer/database-writer.d.mts.map +1 -1
- package/esm/writer/database-writer.mjs +4 -3
- package/esm/writer/database-writer.mjs.map +1 -1
- package/llms-full.txt +106 -7
- package/llms.txt +3 -3
- package/package.json +4 -4
- package/skills/README.md +3 -3
- package/skills/aggregate-data/SKILL.md +43 -3
- package/skills/manage-transactions/SKILL.md +40 -1
- package/skills/perform-atomic-ops/SKILL.md +23 -3
|
@@ -37,6 +37,13 @@ declare class MongoQueryParser {
|
|
|
37
37
|
* Maps pipeline index to field names.
|
|
38
38
|
*/
|
|
39
39
|
private readonly groupFieldNames;
|
|
40
|
+
/**
|
|
41
|
+
* Track `countDistinct` aggregate aliases per group stage. The renaming
|
|
42
|
+
* `$project` finalizes these with `{ $size: "$alias" }` over the set built
|
|
43
|
+
* by `$addToSet` in the `$group` stage.
|
|
44
|
+
* Maps pipeline index to the set of aliases needing `$size` finalization.
|
|
45
|
+
*/
|
|
46
|
+
private readonly countDistinctAliases;
|
|
40
47
|
/**
|
|
41
48
|
* Create a new MongoDB query parser.
|
|
42
49
|
*
|
|
@@ -68,6 +75,12 @@ declare class MongoQueryParser {
|
|
|
68
75
|
* Track field names for group stages that need _id renaming.
|
|
69
76
|
*/
|
|
70
77
|
private trackGroupFieldNames;
|
|
78
|
+
/**
|
|
79
|
+
* Record which aggregate aliases in a group stage are `countDistinct` so the
|
|
80
|
+
* renaming `$project` can finalize them with `{ $size: "$alias" }` over the
|
|
81
|
+
* set built by `$addToSet` (the standard distinct-count-per-group pattern).
|
|
82
|
+
*/
|
|
83
|
+
private trackCountDistinctAliases;
|
|
71
84
|
/**
|
|
72
85
|
* Post-process pipeline to rename _id fields after $group stages.
|
|
73
86
|
*
|
|
@@ -235,6 +248,16 @@ declare class MongoQueryParser {
|
|
|
235
248
|
* @returns The $group stage or null
|
|
236
249
|
*/
|
|
237
250
|
private buildGroupByWithAggregatesStage;
|
|
251
|
+
/**
|
|
252
|
+
* Build a `$group` stage that buckets documents by a `$dateTrunc` of a date
|
|
253
|
+
* field, optionally running aggregates over each bucket.
|
|
254
|
+
*
|
|
255
|
+
* @param column - The date field to bucket
|
|
256
|
+
* @param unit - The bucket granularity
|
|
257
|
+
* @param aggregates - Aggregate operations (abstract or raw)
|
|
258
|
+
* @returns The `$group` stage
|
|
259
|
+
*/
|
|
260
|
+
private buildGroupByDateStage;
|
|
238
261
|
/**
|
|
239
262
|
* Extract field names from GroupByInput for renaming _id.
|
|
240
263
|
*
|
|
@@ -249,6 +272,19 @@ declare class MongoQueryParser {
|
|
|
249
272
|
* @returns MongoDB aggregation expression
|
|
250
273
|
*/
|
|
251
274
|
private translateAggregateExpression;
|
|
275
|
+
/**
|
|
276
|
+
* Compile a typed {@link ColumnExpression} tree into a MongoDB aggregation
|
|
277
|
+
* expression.
|
|
278
|
+
*
|
|
279
|
+
* Column references become `$field` paths; literals are emitted verbatim;
|
|
280
|
+
* arithmetic ops map to `$add` / `$subtract` / `$multiply` / `$divide`. The
|
|
281
|
+
* `raw` node is rejected — a raw SQL fragment is not portable to a MongoDB
|
|
282
|
+
* pipeline, so callers must use the typed combinators (or `groupByRaw`) here.
|
|
283
|
+
*
|
|
284
|
+
* @param expression - The expression tree to compile
|
|
285
|
+
* @returns A MongoDB aggregation expression (e.g. `{ $multiply: ["$price", "$quantity"] }`)
|
|
286
|
+
*/
|
|
287
|
+
private columnExpressionToMongo;
|
|
252
288
|
private buildGroupId;
|
|
253
289
|
/**
|
|
254
290
|
* Build a $lookup stage from join operations.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongodb-query-parser.d.mts","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/mongodb/mongodb-query-parser.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"mongodb-query-parser.d.mts","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/mongodb/mongodb-query-parser.ts"],"mappings":";;;;;;;AAcA;KAAY,uBAAA;6CAEV,UAAA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mBAAA;EAAA,QAeA,mBAAA;;;;;UAkBA,0BAAA;EAAA,QAaA,cAAA;EAAA,QAMA,qBAAA;EAAA,QAMA,uBAAA;;;;;;;UAsBA,iBAAA;;;;;;;UAqHA,cAAA;;;;;;;UA2BA,eAAA;EAAA,QA0DA,iBAAA;;;;;;;;UAgBA,+BAAA;;;;;;;;;;UAoCA,qBAAA;;;;;;;UA0BA,sBAAA;;;;;;;UA4BA,4BAAA;;;;;;;;;;;;;UAuFA,uBAAA;EAAA,QAoCA,YAAA;;;;;;;UAgDA,gBAAA;AAAA"}
|
|
@@ -29,6 +29,13 @@ var MongoQueryParser = class {
|
|
|
29
29
|
*/
|
|
30
30
|
groupFieldNames = /* @__PURE__ */ new Map();
|
|
31
31
|
/**
|
|
32
|
+
* Track `countDistinct` aggregate aliases per group stage. The renaming
|
|
33
|
+
* `$project` finalizes these with `{ $size: "$alias" }` over the set built
|
|
34
|
+
* by `$addToSet` in the `$group` stage.
|
|
35
|
+
* Maps pipeline index to the set of aliases needing `$size` finalization.
|
|
36
|
+
*/
|
|
37
|
+
countDistinctAliases = /* @__PURE__ */ new Map();
|
|
38
|
+
/**
|
|
32
39
|
* Create a new MongoDB query parser.
|
|
33
40
|
*
|
|
34
41
|
* @param options - Configuration options for the parser
|
|
@@ -105,10 +112,24 @@ var MongoQueryParser = class {
|
|
|
105
112
|
if (op.type === "groupByWithAggregates" && op.data.fields) {
|
|
106
113
|
const fieldNames = this.extractGroupFieldNames(op.data.fields);
|
|
107
114
|
if (fieldNames) this.groupFieldNames.set(stageIndex, fieldNames);
|
|
115
|
+
this.trackCountDistinctAliases(stageIndex, op.data.aggregates);
|
|
116
|
+
} else if (op.type === "groupByDate") {
|
|
117
|
+
this.groupFieldNames.set(stageIndex, op.data.column);
|
|
118
|
+
this.trackCountDistinctAliases(stageIndex, op.data.aggregates ?? {});
|
|
108
119
|
}
|
|
109
120
|
}
|
|
110
121
|
}
|
|
111
122
|
/**
|
|
123
|
+
* Record which aggregate aliases in a group stage are `countDistinct` so the
|
|
124
|
+
* renaming `$project` can finalize them with `{ $size: "$alias" }` over the
|
|
125
|
+
* set built by `$addToSet` (the standard distinct-count-per-group pattern).
|
|
126
|
+
*/
|
|
127
|
+
trackCountDistinctAliases(stageIndex, aggregates) {
|
|
128
|
+
const distinctAliases = /* @__PURE__ */ new Set();
|
|
129
|
+
for (const [alias, expression] of Object.entries(aggregates)) if (isAggregateExpression(expression) && expression.__agg === "countDistinct") distinctAliases.add(alias);
|
|
130
|
+
if (distinctAliases.size > 0) this.countDistinctAliases.set(stageIndex, distinctAliases);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
112
133
|
* Post-process pipeline to rename _id fields after $group stages.
|
|
113
134
|
*
|
|
114
135
|
* This automatically renames MongoDB's `_id` field to the actual field name(s)
|
|
@@ -127,8 +148,10 @@ var MongoQueryParser = class {
|
|
|
127
148
|
const projection = {};
|
|
128
149
|
if (typeof fieldNames === "string") projection[fieldNames] = "$_id";
|
|
129
150
|
else if (Array.isArray(fieldNames) && fieldNames.length > 0) for (const fieldName of fieldNames) projection[fieldName] = `$_id.${fieldName}`;
|
|
151
|
+
const distinctAliases = this.countDistinctAliases.get(i);
|
|
130
152
|
const aggregateFields = Object.keys(stage.$group).filter((key) => key !== "_id");
|
|
131
|
-
for (const field of aggregateFields) projection[field] =
|
|
153
|
+
for (const field of aggregateFields) if (distinctAliases?.has(field)) projection[field] = { $size: `$${field}` };
|
|
154
|
+
else projection[field] = 1;
|
|
132
155
|
if (Object.keys(projection).length > 0) {
|
|
133
156
|
projection._id = 0;
|
|
134
157
|
processed.push({ $project: projection });
|
|
@@ -832,6 +855,11 @@ var MongoQueryParser = class {
|
|
|
832
855
|
if (stage) return stage;
|
|
833
856
|
break;
|
|
834
857
|
}
|
|
858
|
+
case "groupByDate": {
|
|
859
|
+
const stage = this.buildGroupByDateStage(op.data.column, op.data.unit, op.data.aggregates ?? {});
|
|
860
|
+
if (stage) return stage;
|
|
861
|
+
break;
|
|
862
|
+
}
|
|
835
863
|
case "groupByRaw": {
|
|
836
864
|
const expression = op.data.expression;
|
|
837
865
|
if (expression && typeof expression === "object") return { $group: expression };
|
|
@@ -868,6 +896,24 @@ var MongoQueryParser = class {
|
|
|
868
896
|
return { $group: groupStage };
|
|
869
897
|
}
|
|
870
898
|
/**
|
|
899
|
+
* Build a `$group` stage that buckets documents by a `$dateTrunc` of a date
|
|
900
|
+
* field, optionally running aggregates over each bucket.
|
|
901
|
+
*
|
|
902
|
+
* @param column - The date field to bucket
|
|
903
|
+
* @param unit - The bucket granularity
|
|
904
|
+
* @param aggregates - Aggregate operations (abstract or raw)
|
|
905
|
+
* @returns The `$group` stage
|
|
906
|
+
*/
|
|
907
|
+
buildGroupByDateStage(column, unit, aggregates) {
|
|
908
|
+
const groupStage = { _id: { $dateTrunc: {
|
|
909
|
+
date: `$${column}`,
|
|
910
|
+
unit
|
|
911
|
+
} } };
|
|
912
|
+
for (const [alias, expression] of Object.entries(aggregates)) if (isAggregateExpression(expression)) groupStage[alias] = this.translateAggregateExpression(expression);
|
|
913
|
+
else groupStage[alias] = expression;
|
|
914
|
+
return { $group: groupStage };
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
871
917
|
* Extract field names from GroupByInput for renaming _id.
|
|
872
918
|
*
|
|
873
919
|
* @param fields - The grouping fields
|
|
@@ -891,7 +937,11 @@ var MongoQueryParser = class {
|
|
|
891
937
|
translateAggregateExpression(expr) {
|
|
892
938
|
switch (expr.__agg) {
|
|
893
939
|
case "count": return { $sum: 1 };
|
|
940
|
+
case "countDistinct":
|
|
941
|
+
if (!expr.__field) throw new Error("Count distinct aggregate requires a field name");
|
|
942
|
+
return { $addToSet: `$${expr.__field}` };
|
|
894
943
|
case "sum":
|
|
944
|
+
if (expr.__expr) return { $sum: this.columnExpressionToMongo(expr.__expr) };
|
|
895
945
|
if (!expr.__field) throw new Error("Sum aggregate requires a field name");
|
|
896
946
|
return { $sum: `$${expr.__field}` };
|
|
897
947
|
case "avg":
|
|
@@ -918,6 +968,35 @@ var MongoQueryParser = class {
|
|
|
918
968
|
default: throw new Error(`Unknown aggregate function: ${expr.__agg}`);
|
|
919
969
|
}
|
|
920
970
|
}
|
|
971
|
+
/**
|
|
972
|
+
* Compile a typed {@link ColumnExpression} tree into a MongoDB aggregation
|
|
973
|
+
* expression.
|
|
974
|
+
*
|
|
975
|
+
* Column references become `$field` paths; literals are emitted verbatim;
|
|
976
|
+
* arithmetic ops map to `$add` / `$subtract` / `$multiply` / `$divide`. The
|
|
977
|
+
* `raw` node is rejected — a raw SQL fragment is not portable to a MongoDB
|
|
978
|
+
* pipeline, so callers must use the typed combinators (or `groupByRaw`) here.
|
|
979
|
+
*
|
|
980
|
+
* @param expression - The expression tree to compile
|
|
981
|
+
* @returns A MongoDB aggregation expression (e.g. `{ $multiply: ["$price", "$quantity"] }`)
|
|
982
|
+
*/
|
|
983
|
+
columnExpressionToMongo(expression) {
|
|
984
|
+
switch (expression.__expr) {
|
|
985
|
+
case "column": return `$${expression.column}`;
|
|
986
|
+
case "literal": return expression.value;
|
|
987
|
+
case "raw": throw new Error("$agg.sumRaw / $expr.raw is not portable to a MongoDB pipeline — a raw SQL fragment has no MongoDB equivalent. Use the typed $expr combinators ($expr.mul / $expr.add / $expr.sub / $expr.div / $expr.col / $expr.lit) or groupByRaw instead.");
|
|
988
|
+
case "add":
|
|
989
|
+
case "subtract":
|
|
990
|
+
case "multiply":
|
|
991
|
+
case "divide": return { [{
|
|
992
|
+
add: "$add",
|
|
993
|
+
subtract: "$subtract",
|
|
994
|
+
multiply: "$multiply",
|
|
995
|
+
divide: "$divide"
|
|
996
|
+
}[expression.__expr]]: expression.operands.map((operand) => this.columnExpressionToMongo(operand)) };
|
|
997
|
+
default: throw new Error(`Unsupported column expression node: ${JSON.stringify(expression)}`);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
921
1000
|
buildGroupId(fields) {
|
|
922
1001
|
if (!fields) return null;
|
|
923
1002
|
if (typeof fields === "string") return `$${fields}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongodb-query-parser.mjs","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/mongodb/mongodb-query-parser.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport type { Collection } from \"mongodb\";\nimport type { GroupByInput, RawExpression, WhereOperator } from \"../../contracts\";\nimport {\n isAggregateExpression,\n type AggregateExpression,\n} from \"../../expressions/aggregate-expressions\";\nimport type { MongoQueryBuilder } from \"./mongodb-query-builder\";\nimport type { Operation, PipelineStage } from \"./types\";\n\n/**\n * Options for configuring the MongoDB query parser.\n */\nexport type MongoQueryParserOptions = {\n /** The MongoDB collection being queried */\n collection: Collection;\n /** The ordered list of operations to parse */\n operations: Operation[];\n /** Factory method for creating sub-builders (used for callbacks) */\n createSubBuilder: () => MongoQueryBuilder;\n};\n\n/**\n * Parses query builder operations into MongoDB aggregation pipeline.\n *\n * This parser is responsible for converting the abstract operations collected\n * by the query builder into a concrete MongoDB aggregation pipeline. It handles\n * intelligent grouping of mergeable operations (like multiple where clauses)\n * into single pipeline stages for optimal performance.\n */\nexport class MongoQueryParser {\n /**\n * The MongoDB collection being queried.\n */\n private readonly collection: Collection;\n\n /**\n * The ordered list of operations to parse.\n */\n private readonly operations: Operation[];\n\n /**\n * Factory for creating sub-builders (used when resolving callbacks).\n */\n private readonly createSubBuilder: () => MongoQueryBuilder;\n\n /**\n * Track group field names for automatic _id renaming.\n * Maps pipeline index to field names.\n */\n private readonly groupFieldNames = new Map<number, string | string[]>();\n\n /**\n * Create a new MongoDB query parser.\n *\n * @param options - Configuration options for the parser\n */\n public constructor(options: MongoQueryParserOptions) {\n this.collection = options.collection;\n this.operations = options.operations;\n this.createSubBuilder = options.createSubBuilder;\n }\n\n /**\n * Parse the operations into a MongoDB aggregation pipeline.\n *\n * This method intelligently groups mergeable operations (e.g., multiple where\n * clauses) into single pipeline stages while maintaining the correct execution\n * order for non-mergeable operations.\n *\n * @returns The MongoDB aggregation pipeline\n *\n * @example\n * ```typescript\n * const parser = new MongoQueryParser({ collection, operations });\n * const pipeline = parser.parse();\n * // [\n * // { $match: { status: 'active', age: { $gt: 18 } } },\n * // { $sort: { createdAt: -1 } },\n * // { $limit: 10 }\n * // ]\n * ```\n */\n public parse(): any[] {\n const pipeline: any[] = [];\n let currentStage: PipelineStage | null = null;\n let currentBuffer: Operation[] = [];\n\n for (const op of this.operations) {\n if (op.mergeable && op.stage === currentStage) {\n // Same mergeable stage, add to buffer\n currentBuffer.push(op);\n } else {\n // Different stage or non-mergeable, flush buffer\n if (currentBuffer.length > 0) {\n const builtStage = this.buildStage(currentStage!, currentBuffer);\n if (builtStage) {\n const stageIndex = pipeline.length;\n pipeline.push(builtStage);\n // Track field names for group stages with aggregates\n this.trackGroupFieldNames(currentStage!, currentBuffer, stageIndex);\n }\n currentBuffer = [];\n }\n\n if (op.mergeable) {\n // Start new buffer\n currentStage = op.stage;\n currentBuffer.push(op);\n } else {\n // Non-mergeable, add directly\n const builtStage = this.buildStage(op.stage, [op]);\n if (builtStage) {\n const stageIndex = pipeline.length;\n pipeline.push(builtStage);\n // Track field names for group stages with aggregates\n this.trackGroupFieldNames(op.stage, [op], stageIndex);\n }\n currentStage = null;\n }\n }\n }\n\n // Flush remaining buffer\n if (currentBuffer.length > 0) {\n const builtStage = this.buildStage(currentStage!, currentBuffer);\n if (builtStage) {\n const stageIndex = pipeline.length;\n pipeline.push(builtStage);\n // Track field names for group stages with aggregates\n this.trackGroupFieldNames(currentStage!, currentBuffer, stageIndex);\n }\n }\n\n // Post-process: Rename _id to actual field names after $group stages with aggregates\n return this.postProcessGroupStages(pipeline);\n }\n\n /**\n * Track field names for group stages that need _id renaming.\n */\n private trackGroupFieldNames(\n stage: PipelineStage,\n operations: Operation[],\n stageIndex: number,\n ): void {\n if (stage === \"$group\") {\n const op = operations[0];\n if (op.type === \"groupByWithAggregates\" && op.data.fields) {\n const fieldNames = this.extractGroupFieldNames(op.data.fields);\n if (fieldNames) {\n this.groupFieldNames.set(stageIndex, fieldNames);\n }\n }\n }\n }\n\n /**\n * Post-process pipeline to rename _id fields after $group stages.\n *\n * This automatically renames MongoDB's `_id` field to the actual field name(s)\n * used for grouping, making the results more intuitive.\n *\n * @param pipeline - The aggregation pipeline\n * @returns The processed pipeline\n */\n private postProcessGroupStages(pipeline: any[]): any[] {\n const processed: any[] = [];\n\n for (let i = 0; i < pipeline.length; i++) {\n const stage = pipeline[i];\n\n // Check if this is a $group stage that needs _id renaming\n if (stage.$group && this.groupFieldNames.has(i)) {\n const fieldNames = this.groupFieldNames.get(i)!;\n\n // Add the $group stage\n processed.push(stage);\n\n // Add a $project stage to rename _id\n const projection: Record<string, unknown> = {};\n\n if (typeof fieldNames === \"string\") {\n // Single field: rename _id to field name\n projection[fieldNames] = \"$_id\";\n } else if (Array.isArray(fieldNames) && fieldNames.length > 0) {\n // Multiple fields: _id is an object, spread it\n for (const fieldName of fieldNames) {\n projection[fieldName] = `$_id.${fieldName}`;\n }\n }\n\n // Include all aggregate fields\n const aggregateFields = Object.keys(stage.$group).filter((key) => key !== \"_id\");\n for (const field of aggregateFields) {\n projection[field] = 1;\n }\n\n if (Object.keys(projection).length > 0) {\n // now unselect the _id field\n projection._id = 0;\n processed.push({ $project: projection });\n }\n } else {\n // Regular stage, add as-is\n processed.push(stage);\n }\n }\n\n return processed;\n }\n\n /**\n * Convert the parsed pipeline to a pretty-printed string for debugging.\n *\n * This method formats the MongoDB aggregation pipeline in a human-readable\n * way, making it easier to understand and debug complex queries.\n *\n * @returns A formatted string representation of the pipeline\n *\n * @example\n * ```typescript\n * const parser = new MongoQueryParser({ collection, operations });\n * console.log(parser.toPrettyString());\n * // Output:\n * // MongoDB Aggregation Pipeline:\n * // ════════════════════════════\n * // Stage 1: $match\n * // status: \"active\"\n * // age: { $gt: 18 }\n * //\n * // Stage 2: $sort\n * // createdAt: -1\n * ```\n */\n public toPrettyString(): string {\n const pipeline = this.parse();\n\n if (pipeline.length === 0) {\n return \"MongoDB Aggregation Pipeline: (empty)\";\n }\n\n let output = \"MongoDB Aggregation Pipeline:\\n\";\n output += \"═\".repeat(50) + \"\\n\";\n\n pipeline.forEach((stage, index) => {\n const stageName = Object.keys(stage)[0];\n const stageData = stage[stageName];\n\n if (index > 0) {\n output += \"\\n\";\n }\n\n output += `Stage ${index + 1}: ${colors.redBright(stageName)}\\n`;\n output += this.formatStageData(stageData, 2);\n });\n\n return output;\n }\n\n /**\n * Format stage data with proper indentation.\n *\n * @param data - The stage data to format\n * @param indent - The indentation level\n * @returns Formatted string\n */\n private formatStageData(data: any, indent: number = 0): string {\n const spaces = \" \".repeat(indent);\n\n if (typeof data !== \"object\" || data === null) {\n return `${spaces}${JSON.stringify(data)}\\n`;\n }\n\n if (Array.isArray(data)) {\n if (data.length === 0) return `${spaces}[]`;\n\n let result = \"\";\n data.forEach((item, index) => {\n result += `${spaces}[${colors.magenta(index)}]:\\n`;\n result += this.formatStageData(item, indent + 2);\n });\n return result;\n }\n\n let result = \"\";\n Object.entries(data).forEach(([key, value]) => {\n const isOperator = key.startsWith(\"$\");\n const coloredKey = isOperator ? colors.magentaBright(key) : colors.blue(key);\n\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n result += `${spaces}${coloredKey}:\\n`;\n result += this.formatStageData(value, indent + 2);\n } else if (Array.isArray(value)) {\n result += `${spaces}${coloredKey}:\\n`;\n result += this.formatStageData(value, indent + 2);\n } else {\n const formattedValue =\n typeof value === \"number\"\n ? colors.yellowBright(value)\n : typeof value === \"boolean\"\n ? colors.cyanBright(value.toString())\n : typeof value === \"string\"\n ? colors.greenBright(JSON.stringify(value))\n : colors.greenBright(String(value));\n result += `${spaces}${coloredKey}: ${formattedValue}\\n`;\n }\n });\n\n return result.endsWith(\"\\n\") ? result : `${result}\\n`;\n }\n\n /**\n * Build a single pipeline stage from a group of operations.\n *\n * @param stage - The pipeline stage type\n * @param operations - The operations to build the stage from\n * @returns The built pipeline stage or null if no stage should be added\n */\n private buildStage(stage: PipelineStage, operations: Operation[]): any {\n switch (stage) {\n case \"$match\":\n return this.buildMatchStage(operations);\n case \"$project\":\n return this.buildProjectStage(operations);\n case \"$sort\":\n return this.buildSortStage(operations);\n case \"$group\":\n return this.buildGroupStage(operations);\n case \"$lookup\":\n return this.buildLookupStage(operations);\n case \"$limit\":\n return { $limit: operations[0].data.value };\n case \"$skip\":\n return { $skip: operations[0].data.value };\n case \"$setWindowFields\":\n return {\n $setWindowFields: operations[0].data.spec,\n };\n default:\n return null;\n }\n }\n\n /**\n * Build a $match stage from where operations.\n *\n * Query building strategy:\n * - Top-level where() + orWhere() = Pure OR\n * - Use callbacks for AND + OR grouping\n *\n * @param operations - The where operations\n * @returns The $match stage or null\n */\n private buildMatchStage(operations: Operation[]): any {\n const andFilter: Record<string, any> = {};\n const orClauses: any[] = [];\n const pendingSimpleWhere: any[] = [];\n let topLevelOrMode = false;\n\n const pushOr = (clause: any): void => {\n if (!clause) {\n return;\n }\n\n if (this.isPureOrCondition(clause)) {\n orClauses.push(...clause.$or);\n return;\n }\n\n if (Array.isArray(clause)) {\n orClauses.push(...clause);\n return;\n }\n\n orClauses.push(clause);\n };\n\n const mergeAnd = (condition: any): void => {\n if (!condition) {\n return;\n }\n\n Object.entries(condition).forEach(([key, value]) => {\n if (key === \"$or\") {\n pushOr(value);\n return;\n }\n\n if (\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n andFilter[key] &&\n typeof andFilter[key] === \"object\" &&\n !Array.isArray(andFilter[key])\n ) {\n andFilter[key] = { ...andFilter[key], ...value };\n } else {\n andFilter[key] = value;\n }\n });\n };\n\n const queueSimpleWhere = (condition: any): void => {\n if (!condition) {\n return;\n }\n if (topLevelOrMode) {\n pushOr(condition);\n } else {\n pendingSimpleWhere.push(condition);\n }\n };\n\n const enterTopLevelOrMode = (): void => {\n if (topLevelOrMode) {\n return;\n }\n topLevelOrMode = true;\n while (pendingSimpleWhere.length > 0) {\n const condition = pendingSimpleWhere.shift();\n if (condition) {\n pushOr(condition);\n }\n }\n };\n\n const flushPendingSimpleWhere = (): void => {\n if (pendingSimpleWhere.length === 0) {\n return;\n }\n if (topLevelOrMode) {\n pendingSimpleWhere.forEach(pushOr);\n } else {\n pendingSimpleWhere.forEach(mergeAnd);\n }\n pendingSimpleWhere.length = 0;\n };\n\n for (const op of operations) {\n if (op.type === \"where:callback\" || op.type === \"orWhere:callback\") {\n flushPendingSimpleWhere();\n const callbackCondition = this.buildCallbackCondition(op.data);\n if (!callbackCondition) {\n continue;\n }\n\n const treatAsOr =\n op.type === \"orWhere:callback\" ||\n (topLevelOrMode && !this.isPureOrCondition(callbackCondition)) ||\n this.isPureOrCondition(callbackCondition);\n\n if (treatAsOr) {\n if (op.type === \"orWhere:callback\") {\n enterTopLevelOrMode();\n }\n pushOr(callbackCondition);\n } else {\n mergeAnd(callbackCondition);\n }\n continue;\n }\n\n if (op.type === \"where:object\") {\n queueSimpleWhere(op.data);\n continue;\n }\n\n if (\n op.type === \"where:not\" ||\n op.type === \"orWhere:not\" ||\n op.type === \"where:exists\" ||\n op.type === \"where:notExists\"\n ) {\n const negated = op.type === \"where:not\" || op.type === \"where:notExists\";\n const nested = this.buildCallbackCondition(op.data.callback);\n if (nested) {\n const condition = negated ? { $nor: [nested] } : nested;\n if (op.type.startsWith(\"orWhere\")) {\n enterTopLevelOrMode();\n pushOr(condition);\n } else {\n queueSimpleWhere(condition);\n }\n }\n continue;\n }\n\n if (op.type === \"orWhere:object\") {\n enterTopLevelOrMode();\n pushOr(op.data);\n continue;\n }\n\n const condition = this.buildWhereCondition(op);\n if (!condition) {\n continue;\n }\n\n if (op.type.startsWith(\"orWhere\")) {\n enterTopLevelOrMode();\n pushOr(condition);\n } else {\n queueSimpleWhere(condition);\n }\n }\n\n flushPendingSimpleWhere();\n\n const hasAnd = Object.keys(andFilter).length > 0;\n const hasOr = orClauses.length > 0;\n\n if (!hasAnd && !hasOr) {\n return null;\n }\n\n const match: any = {};\n if (hasAnd) {\n Object.assign(match, andFilter);\n }\n if (hasOr) {\n match.$or = orClauses;\n }\n\n return { $match: match };\n }\n\n private isPureOrCondition(condition: any): condition is { $or: any[] } {\n return (\n condition &&\n typeof condition === \"object\" &&\n !Array.isArray(condition) &&\n Object.keys(condition).length === 1 &&\n Array.isArray((condition as any).$or)\n );\n }\n\n /**\n * Build a condition from a callback-based where clause.\n * Creates a sub-builder, executes the callback, and extracts the conditions.\n * If callback has orWhere, all conditions become OR.\n *\n * @param callback - The callback function\n * @returns The built condition or null\n */\n private buildCallbackCondition(callback: any): any {\n // Create a temporary sub-builder\n const subBuilder = this.createSubBuilder();\n\n // Execute the callback with the sub-builder\n callback(subBuilder);\n\n // Extract only match operations from the sub-builder\n const matchOps = subBuilder.operations.filter((op: Operation) => op.stage === \"$match\");\n\n if (matchOps.length === 0) {\n return null;\n }\n\n const andFilter: Record<string, any> = {};\n const orClauses: any[] = [];\n const hasInternalOr = matchOps.some((op) => op.type.startsWith(\"orWhere\"));\n\n const pushOr = (clause: any): void => {\n if (!clause) {\n return;\n }\n if (this.isPureOrCondition(clause)) {\n orClauses.push(...clause.$or);\n return;\n }\n orClauses.push(clause);\n };\n\n if (hasInternalOr) {\n for (const op of matchOps) {\n if (op.type === \"where:callback\" || op.type === \"orWhere:callback\") {\n const nestedCondition = this.buildCallbackCondition(op.data);\n if (nestedCondition) {\n pushOr(nestedCondition);\n }\n continue;\n }\n\n if (op.type === \"where:object\" || op.type === \"orWhere:object\") {\n pushOr(op.data);\n continue;\n }\n\n const condition = this.buildWhereCondition(op);\n if (condition) {\n pushOr(condition);\n }\n }\n\n return orClauses.length > 0 ? { $or: orClauses } : null;\n }\n\n for (const op of matchOps) {\n if (op.type === \"where:callback\") {\n const nestedCondition = this.buildCallbackCondition(op.data);\n if (nestedCondition) {\n Object.assign(andFilter, nestedCondition);\n }\n } else if (op.type === \"where:object\") {\n Object.assign(andFilter, op.data);\n } else {\n const condition = this.buildWhereCondition(op);\n if (condition) {\n Object.assign(andFilter, condition);\n }\n }\n }\n\n return Object.keys(andFilter).length > 0 ? andFilter : null;\n }\n\n /**\n * Build a MongoDB filter condition from a where operation.\n *\n * @param op - The operation to build\n * @returns The MongoDB filter condition\n */\n private buildWhereCondition(op: Operation): any {\n const { field, operator, value } = op.data;\n\n switch (op.type) {\n case \"where\":\n case \"orWhere\":\n return this.buildOperatorCondition(field, operator, value);\n\n case \"whereIn\":\n return { [field]: { $in: value || op.data.values } };\n\n case \"whereNotIn\":\n return { [field]: { $nin: value || op.data.values } };\n\n case \"whereNull\":\n return { [field]: null };\n\n case \"whereNotNull\":\n return { [field]: { $ne: null } };\n\n case \"whereBetween\":\n return {\n [field]: {\n $gte: op.data.range[0],\n $lte: op.data.range[1],\n },\n };\n\n case \"whereNotBetween\":\n return {\n [field]: {\n $not: {\n $gte: op.data.range[0],\n $lte: op.data.range[1],\n },\n },\n };\n\n case \"whereLike\": {\n const pattern =\n typeof op.data.pattern === \"string\" ? op.data.pattern : op.data.pattern.source;\n return { [field]: { $regex: pattern, $options: \"i\" } };\n }\n\n case \"whereNotLike\": {\n const notPattern =\n typeof op.data.pattern === \"string\" ? op.data.pattern : op.data.pattern.source;\n return { [field]: { $not: { $regex: notPattern, $options: \"i\" } } };\n }\n\n case \"whereStartsWith\":\n return { [field]: { $regex: `^${op.data.value}`, $options: \"i\" } };\n\n case \"whereNotStartsWith\":\n return {\n [field]: { $not: { $regex: `^${op.data.value}`, $options: \"i\" } },\n };\n\n case \"whereEndsWith\":\n return { [field]: { $regex: `${op.data.value}$`, $options: \"i\" } };\n\n case \"whereNotEndsWith\":\n return {\n [field]: { $not: { $regex: `${op.data.value}$`, $options: \"i\" } },\n };\n\n case \"whereExists\":\n return { [field]: { $exists: true } };\n\n case \"whereNotExists\":\n return { [field]: { $exists: false } };\n\n case \"whereSize\":\n if (op.data.operator === \"=\") {\n return { [field]: { $size: op.data.size } };\n } else {\n const mongoOp = this.getMongoOperator(op.data.operator);\n return {\n $expr: {\n [mongoOp]: [{ $size: `$${field}` }, op.data.size],\n },\n };\n }\n\n case \"textSearch\":\n return {\n $text: { $search: op.data.query },\n ...(op.data.filters || {}),\n };\n\n case \"whereRaw\":\n case \"orWhereRaw\":\n return this.resolveRawExpression(\n op.data.expression as RawExpression,\n op.data.bindings,\n );\n\n case \"whereColumn\":\n case \"orWhereColumn\":\n return this.buildColumnComparison(op.data.first, op.data.operator, op.data.second);\n\n case \"whereBetweenColumns\":\n return this.buildBetweenColumnsCondition(\n op.data.field,\n op.data.lowerColumn,\n op.data.upperColumn,\n );\n\n case \"whereDate\":\n case \"whereDateEquals\":\n return this.buildDateEqualityCondition(op.data.field, op.data.value);\n\n case \"whereDateBefore\":\n return this.buildDateBeforeCondition(op.data.field, op.data.value);\n\n case \"whereDateAfter\":\n return this.buildDateAfterCondition(op.data.field, op.data.value);\n\n case \"whereTime\":\n return this.buildTimeCondition(op.data.field, op.data.value);\n\n case \"whereDay\":\n return this.buildDatePartCondition(op.data.field, \"$dayOfMonth\", op.data.value);\n\n case \"whereMonth\":\n return this.buildDatePartCondition(op.data.field, \"$month\", op.data.value);\n\n case \"whereYear\":\n return this.buildDatePartCondition(op.data.field, \"$year\", op.data.value);\n\n case \"whereJsonContains\":\n return this.buildJsonContainsCondition(op.data.path, op.data.value);\n\n case \"whereJsonDoesntContain\":\n return this.buildJsonDoesntContainCondition(op.data.path, op.data.value);\n\n case \"whereJsonContainsKey\":\n return this.buildJsonContainsKeyCondition(op.data.path);\n\n case \"whereJsonLength\":\n return this.buildJsonLengthCondition(\n op.data.path,\n op.data.operator,\n op.data.value,\n );\n\n case \"whereJsonIsArray\":\n return this.buildJsonTypeCondition(op.data.path, \"array\");\n\n case \"whereJsonIsObject\":\n return this.buildJsonTypeCondition(op.data.path, \"object\");\n\n case \"whereArrayLength\":\n return this.buildArrayLengthCondition(\n op.data.field,\n op.data.operator,\n op.data.value,\n );\n\n case \"whereFullText\":\n case \"orWhereFullText\":\n return { $text: { $search: op.data.query } };\n\n case \"whereSearch\":\n return {\n [op.data.field]: {\n $regex: op.data.query,\n $options: \"i\",\n },\n };\n\n case \"where:not\":\n case \"orWhere:not\": {\n const nestedNot = this.buildCallbackCondition(op.data.callback);\n return nestedNot ? { $nor: [nestedNot] } : null;\n }\n\n case \"where:exists\":\n return this.buildCallbackCondition(op.data.callback);\n\n case \"where:notExists\": {\n const nestedExists = this.buildCallbackCondition(op.data.callback);\n return nestedExists ? { $nor: [nestedExists] } : null;\n }\n\n case \"whereArrayContains\":\n if (op.data.key) {\n return {\n [field]: {\n $elemMatch: { [op.data.key]: op.data.value },\n },\n };\n } else {\n return { [field]: op.data.value };\n }\n\n default:\n return null;\n }\n }\n\n /**\n * Build a condition based on the operator.\n *\n * @param field - The field name\n * @param operator - The comparison operator\n * @param value - The value to compare\n * @returns The MongoDB filter condition\n */\n private buildOperatorCondition(field: string, operator: string, value: unknown): any {\n switch (operator) {\n case \"=\":\n return { [field]: value };\n case \"!=\":\n return { [field]: { $ne: value } };\n case \">\":\n return { [field]: { $gt: value } };\n case \">=\":\n return { [field]: { $gte: value } };\n case \"<\":\n return { [field]: { $lt: value } };\n case \"<=\":\n return { [field]: { $lte: value } };\n default:\n return { [field]: value };\n }\n }\n\n /**\n * Get MongoDB operator from comparison operator.\n *\n * @param operator - The comparison operator\n * @returns The MongoDB operator\n */\n private getMongoOperator(operator: string): string {\n const map: Record<string, string> = {\n \"=\": \"$eq\",\n \"!=\": \"$ne\",\n \">\": \"$gt\",\n \">=\": \"$gte\",\n \"<\": \"$lt\",\n \"<=\": \"$lte\",\n };\n return map[operator] || \"$eq\";\n }\n\n private resolveRawExpression(expression: RawExpression, bindings?: unknown[]): any {\n if (typeof expression === \"string\") {\n const bound = this.bindRawString(expression, bindings);\n return { $where: bound };\n }\n\n if (typeof expression === \"object\" && expression !== null) {\n return expression;\n }\n\n return null;\n }\n\n private bindRawString(expression: string, bindings?: unknown[]): string {\n if (!bindings || bindings.length === 0) {\n return expression;\n }\n\n let index = 0;\n return expression.replace(/\\?/g, () => {\n const value = bindings[index++];\n return value === undefined ? \"?\" : JSON.stringify(value);\n });\n }\n\n private buildColumnComparison(first: string, operator: WhereOperator, second: string): any {\n const mongoOperator = this.getMongoOperator(operator);\n return {\n $expr: {\n [mongoOperator]: [this.wrapColumn(first), this.wrapColumn(second)],\n },\n };\n }\n\n private buildBetweenColumnsCondition(field: string, lower: string, upper: string): any {\n return {\n $expr: {\n $and: [\n { $gte: [this.wrapColumn(field), this.wrapColumn(lower)] },\n { $lte: [this.wrapColumn(field), this.wrapColumn(upper)] },\n ],\n },\n };\n }\n\n private wrapColumn(column: string): string {\n return column.startsWith(\"$\") ? column : `$${column}`;\n }\n\n private buildDateEqualityCondition(field: string, value: Date | string): any {\n const target = this.normalizeDateInput(value);\n const start = this.startOfDay(target);\n const end = this.endOfDay(target);\n return { [field]: { $gte: start, $lte: end } };\n }\n\n private buildDateBeforeCondition(field: string, value: Date | string): any {\n const target = this.startOfDay(this.normalizeDateInput(value));\n return { [field]: { $lt: target } };\n }\n\n private buildDateAfterCondition(field: string, value: Date | string): any {\n const target = this.endOfDay(this.normalizeDateInput(value));\n return { [field]: { $gt: target } };\n }\n\n private buildTimeCondition(field: string, value: string): any {\n return {\n $expr: {\n $eq: [\n {\n $dateToString: {\n format: \"%H:%M\",\n date: `$${field}`,\n },\n },\n value,\n ],\n },\n };\n }\n\n private buildDatePartCondition(\n field: string,\n operator: \"$dayOfMonth\" | \"$month\" | \"$year\",\n value: number,\n ): any {\n return {\n $expr: {\n $eq: [\n {\n [operator]: `$${field}`,\n },\n value,\n ],\n },\n };\n }\n\n private buildJsonContainsCondition(path: string, value: unknown): any {\n const fieldPath = this.normalizePath(path);\n if (Array.isArray(value)) {\n return { [fieldPath]: { $all: value } };\n }\n return { [fieldPath]: value };\n }\n\n private buildJsonDoesntContainCondition(path: string, value: unknown): any {\n const fieldPath = this.normalizePath(path);\n const values = Array.isArray(value) ? value : [value];\n return { [fieldPath]: { $nin: values } };\n }\n\n private buildJsonContainsKeyCondition(path: string): any {\n return {\n [this.normalizePath(path)]: { $exists: true },\n };\n }\n\n private buildJsonLengthCondition(path: string, operator: WhereOperator, value: number): any {\n const mongoOperator = this.getMongoOperator(operator);\n return {\n $expr: {\n [mongoOperator]: [{ $size: { $ifNull: [`$${this.normalizePath(path)}`, []] } }, value],\n },\n };\n }\n\n private buildJsonTypeCondition(path: string, type: string): any {\n return {\n $expr: {\n $eq: [{ $type: `$${this.normalizePath(path)}` }, type],\n },\n };\n }\n\n private buildArrayLengthCondition(field: string, operator: WhereOperator, value: number): any {\n const mongoOperator = this.getMongoOperator(operator);\n return {\n $expr: {\n [mongoOperator]: [{ $size: { $ifNull: [`$${field}`, []] } }, value],\n },\n };\n }\n\n private normalizeDateInput(value: Date | string): Date {\n if (value instanceof Date) {\n return value;\n }\n const parsed = new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n throw new Error(`Invalid date value: ${value}`);\n }\n return parsed;\n }\n\n private startOfDay(date: Date): Date {\n const copy = new Date(date);\n copy.setHours(0, 0, 0, 0);\n return copy;\n }\n\n private endOfDay(date: Date): Date {\n const copy = new Date(date);\n copy.setHours(23, 59, 59, 999);\n return copy;\n }\n\n private normalizePath(path: string): string {\n return path.replace(/->/g, \".\");\n }\n\n private applyProjectionFields(\n projection: Record<string, unknown>,\n fields: string[],\n value: 0 | 1,\n ): void {\n for (const field of fields) {\n projection[field] = value;\n }\n }\n\n /**\n * Apply projection object with aliases and inclusion/exclusion.\n * @param projection - The projection object to modify\n * @param projectionObj - The projection specification\n */\n private applyProjectionObject(\n projection: Record<string, unknown>,\n projectionObj: Record<string, unknown>,\n ): void {\n for (const [field, value] of Object.entries(projectionObj)) {\n // Handle boolean values (true = 1, false = 0)\n if (typeof value === \"boolean\") {\n projection[field] = value ? 1 : 0;\n continue;\n }\n\n // Handle numeric values (0 or 1)\n if (typeof value === \"number\") {\n projection[field] = value;\n continue;\n }\n\n // Handle string values (aliases)\n if (typeof value === \"string\") {\n // Alias: project the field with a new name\n projection[value] = `$${field}`;\n continue;\n }\n\n // Handle complex expressions (objects)\n if (typeof value === \"object\" && value !== null) {\n projection[field] = value;\n continue;\n }\n\n // Default: include the field\n projection[field] = 1;\n }\n }\n\n private applyRawProjection(\n projection: Record<string, unknown>,\n expression: RawExpression,\n bindings?: unknown[],\n ): void {\n const resolved = this.resolveProjectionExpression(expression, bindings);\n if (!resolved) {\n return;\n }\n\n if (typeof resolved === \"object\" && resolved !== null && !Array.isArray(resolved)) {\n Object.assign(projection, resolved as Record<string, unknown>);\n }\n }\n\n private resolveProjectionExpression(\n expression: RawExpression | unknown,\n bindings?: unknown[],\n ): any {\n if (typeof expression === \"string\") {\n const source =\n bindings && expression.includes(\"?\")\n ? this.bindRawString(expression, bindings)\n : expression;\n if (source.startsWith(\":\")) {\n return source.slice(1);\n }\n return this.normalizeFieldReference(source);\n }\n\n if (typeof expression === \"object\" && expression !== null && !(expression instanceof Date)) {\n return expression;\n }\n\n if (typeof expression === \"number\" || typeof expression === \"boolean\") {\n return expression;\n }\n\n return expression;\n }\n\n private normalizeFieldReference(value: string | RawExpression): any {\n if (typeof value === \"string\") {\n if (value.startsWith(\":\")) {\n return value.slice(1);\n }\n // If already a field reference, return as-is\n if (value.startsWith(\"$\")) {\n return value;\n }\n // Check if it's a string literal (contains spaces or special chars)\n // Field paths are typically: alphanumeric, underscore, dot only\n if (!/^[a-zA-Z0-9_.]+$/.test(value)) {\n return value; // Return as literal\n }\n // Otherwise, treat as field reference\n return `$${value}`;\n }\n return value;\n }\n\n private buildAggregateProjection(field: string, aggregate: string): any {\n if (aggregate === \"count\") {\n return this.buildArraySizeExpression(field);\n }\n\n const map: Record<string, string> = {\n sum: \"$sum\",\n avg: \"$avg\",\n min: \"$min\",\n max: \"$max\",\n first: \"$first\",\n last: \"$last\",\n };\n\n const operator = map[aggregate];\n if (!operator) {\n return null;\n }\n\n return {\n [operator]: this.normalizeFieldReference(field),\n };\n }\n\n private buildExistsProjection(field: string): any {\n return {\n $ne: [{ $type: `$${field}` }, \"missing\"],\n };\n }\n\n private buildArraySizeExpression(field: string): any {\n return {\n $size: { $ifNull: [`$${field}`, []] },\n };\n }\n\n private buildCaseExpression(\n cases: Array<{ when: RawExpression; then: RawExpression | unknown }>,\n otherwise: RawExpression | unknown,\n ): any {\n return {\n $switch: {\n branches: cases.map((item) => ({\n case: this.resolveProjectionExpression(item.when),\n then: this.resolveLiteralOrExpression(item.then),\n })),\n default: this.resolveLiteralOrExpression(otherwise),\n },\n };\n }\n\n private buildCondExpression(\n condition: RawExpression,\n thenValue: RawExpression | unknown,\n elseValue: RawExpression | unknown,\n ): any {\n return {\n $cond: [\n this.resolveProjectionExpression(condition),\n this.resolveLiteralOrExpression(thenValue),\n this.resolveLiteralOrExpression(elseValue),\n ],\n };\n }\n\n /**\n * Resolve a value as a literal (if it's a plain string) or as an expression.\n * Used for `then`/`default` values in CASE/WHEN expressions.\n */\n private resolveLiteralOrExpression(value: RawExpression | unknown): any {\n // If it's a string that starts with $, treat as field reference\n if (typeof value === \"string\" && value.startsWith(\"$\")) {\n return value;\n }\n // If it's a plain string (not starting with $), treat as literal\n if (typeof value === \"string\") {\n return value;\n }\n // For objects (expressions), numbers, booleans, etc., use normal resolution\n return this.resolveProjectionExpression(value);\n }\n\n private inferJsonAlias(path: string): string {\n const normalized = this.normalizePath(path);\n const segments = normalized.split(\".\");\n return segments[segments.length - 1];\n }\n\n private buildConcatExpression(values: Array<string | RawExpression>): any {\n return {\n $concat: values.map((value) => this.normalizeFieldReference(value)),\n };\n }\n\n private buildCoalesceExpression(values: Array<string | RawExpression>): any {\n if (values.length === 0) {\n return null;\n }\n\n let expression = this.normalizeFieldReference(values[values.length - 1]);\n\n for (let index = values.length - 2; index >= 0; index--) {\n expression = {\n $ifNull: [this.normalizeFieldReference(values[index]), expression],\n };\n }\n\n return expression;\n }\n\n /**\n * Build a $project stage from select operations.\n *\n * @param operations - The select operations\n * @returns The $project stage or null\n */\n private buildProjectStage(operations: Operation[]): any {\n if (operations.length === 0) {\n return null;\n }\n\n const projection: Record<string, unknown> = {};\n const driverCallbacks: Array<(projection: Record<string, unknown>) => void> = [];\n\n for (const op of operations) {\n switch (op.type) {\n case \"select\":\n // Handle new projection format with aliases\n if (op.data.projection) {\n this.applyProjectionObject(projection, op.data.projection);\n } else if (op.data.fields) {\n this.applyProjectionFields(projection, op.data.fields, 1);\n }\n break;\n\n case \"deselect\":\n this.applyProjectionFields(projection, op.data.fields, 0);\n break;\n\n case \"addSelect\":\n this.applyProjectionFields(projection, op.data.fields, 1);\n break;\n\n case \"selectRaw\":\n this.applyRawProjection(projection, op.data.expression, op.data.bindings);\n break;\n\n case \"selectSub\":\n case \"addSelectSub\": {\n const expr = this.resolveProjectionExpression(op.data.expression, op.data.bindings);\n if (expr !== undefined) {\n projection[op.data.alias] = expr;\n }\n break;\n }\n\n case \"selectAggregate\":\n projection[op.data.alias] = this.buildAggregateProjection(\n op.data.field,\n op.data.aggregate,\n );\n break;\n\n case \"selectExists\":\n projection[op.data.alias] = this.buildExistsProjection(op.data.field);\n break;\n\n case \"selectCount\":\n projection[op.data.alias] = this.buildArraySizeExpression(op.data.field);\n break;\n\n case \"selectCase\":\n projection[op.data.alias] = this.buildCaseExpression(\n op.data.cases,\n op.data.otherwise,\n );\n break;\n\n case \"selectWhen\":\n projection[op.data.alias] = this.buildCondExpression(\n op.data.condition,\n op.data.thenValue,\n op.data.elseValue,\n );\n break;\n\n case \"selectDriverProjection\":\n driverCallbacks.push(op.data.callback);\n break;\n\n case \"selectJson\": {\n const alias = op.data.alias ?? this.inferJsonAlias(op.data.path);\n projection[alias] = this.normalizeFieldReference(\n `$${this.normalizePath(op.data.path)}`,\n );\n break;\n }\n\n case \"selectJsonRaw\": {\n projection[op.data.alias] = this.resolveProjectionExpression(op.data.expression);\n break;\n }\n\n case \"deselectJson\":\n projection[this.normalizePath(op.data.path)] = 0;\n break;\n\n case \"selectConcat\":\n projection[op.data.alias] = this.buildConcatExpression(op.data.fields);\n break;\n\n case \"selectCoalesce\":\n projection[op.data.alias] = this.buildCoalesceExpression(op.data.fields);\n break;\n\n default:\n break;\n }\n }\n\n for (const callback of driverCallbacks) {\n callback(projection);\n }\n\n return Object.keys(projection).length > 0 ? { $project: projection } : null;\n }\n\n /**\n * Build a $sort stage from order operations.\n *\n * @param operations - The order operations\n * @returns The $sort stage or null\n */\n private buildSortStage(operations: Operation[]): any {\n const sort: any = {};\n\n for (const op of operations) {\n switch (op.type) {\n case \"orderBy\":\n sort[op.data.field] = op.data.direction === \"asc\" ? 1 : -1;\n break;\n\n case \"orderByRandom\":\n return { $sample: { size: op.data.limit } };\n\n case \"orderByRaw\":\n // TODO: Handle raw expressions\n break;\n }\n }\n\n return Object.keys(sort).length > 0 ? { $sort: sort } : null;\n }\n\n /**\n * Build a $group stage from group operations.\n *\n * @param operations - The group operations\n * @returns The $group stage or null\n */\n private buildGroupStage(operations: Operation[]): any {\n const op = operations[0];\n\n switch (op.type) {\n case \"groupBy\": {\n const stage = this.buildGroupByStage(op.data.fields);\n if (stage) {\n return stage;\n }\n break;\n }\n case \"groupByWithAggregates\": {\n const stage = this.buildGroupByWithAggregatesStage(\n op.data.fields,\n op.data.aggregates,\n );\n if (stage) {\n return stage;\n }\n break;\n }\n case \"groupByRaw\": {\n const expression = op.data.expression;\n if (expression && typeof expression === \"object\") {\n return { $group: expression };\n }\n // If expression is not an object, it might be a string or other type\n // In that case, we should still return it as a $group stage\n if (expression) {\n return { $group: { _id: expression } };\n }\n break;\n }\n case \"distinct\": {\n const stage = this.buildGroupByStage(op.data.fields);\n if (stage) {\n return stage;\n }\n break;\n }\n default:\n break;\n }\n\n return null;\n }\n\n private buildGroupByStage(fields: GroupByInput): any {\n const groupId = this.buildGroupId(fields);\n if (!groupId) {\n return null;\n }\n\n return { $group: { _id: groupId } };\n }\n\n /**\n * Build a $group stage with aggregates from group operations.\n *\n * @param fields - Fields to group by\n * @param aggregates - Aggregate operations (abstract or raw)\n * @returns The $group stage or null\n */\n private buildGroupByWithAggregatesStage(\n fields: GroupByInput,\n aggregates: Record<string, RawExpression>,\n ): any {\n const groupId = this.buildGroupId(fields);\n if (!groupId) {\n return null;\n }\n\n const groupStage: Record<string, unknown> = {\n _id: groupId,\n };\n\n // Translate each aggregate expression\n for (const [alias, expression] of Object.entries(aggregates)) {\n if (isAggregateExpression(expression)) {\n // Translate abstract expression to MongoDB format\n groupStage[alias] = this.translateAggregateExpression(expression);\n } else {\n // Use raw expression as-is (already in MongoDB format)\n groupStage[alias] = expression;\n }\n }\n\n return { $group: groupStage };\n }\n\n /**\n * Extract field names from GroupByInput for renaming _id.\n *\n * @param fields - The grouping fields\n * @returns Field name(s) to use for renaming _id\n */\n private extractGroupFieldNames(fields: GroupByInput): string | string[] | null {\n if (typeof fields === \"string\") {\n return fields;\n }\n\n if (Array.isArray(fields)) {\n const allStrings = fields.every((field) => typeof field === \"string\");\n if (allStrings) {\n return fields as string[];\n }\n // For complex arrays, return null (don't rename)\n return null;\n }\n\n if (typeof fields === \"object\" && fields !== null) {\n // For object syntax, use the keys as field names\n return Object.keys(fields);\n }\n\n return null;\n }\n\n /**\n * Translate an abstract aggregate expression to MongoDB format.\n *\n * @param expr - Abstract aggregate expression\n * @returns MongoDB aggregation expression\n */\n private translateAggregateExpression(expr: AggregateExpression): Record<string, unknown> {\n switch (expr.__agg) {\n case \"count\":\n return { $sum: 1 };\n\n case \"sum\":\n if (!expr.__field) {\n throw new Error(\"Sum aggregate requires a field name\");\n }\n return { $sum: `$${expr.__field}` };\n\n case \"avg\":\n if (!expr.__field) {\n throw new Error(\"Average aggregate requires a field name\");\n }\n return { $avg: `$${expr.__field}` };\n\n case \"min\":\n if (!expr.__field) {\n throw new Error(\"Min aggregate requires a field name\");\n }\n return { $min: `$${expr.__field}` };\n\n case \"max\":\n if (!expr.__field) {\n throw new Error(\"Max aggregate requires a field name\");\n }\n return { $max: `$${expr.__field}` };\n\n case \"first\":\n if (!expr.__field) {\n throw new Error(\"First aggregate requires a field name\");\n }\n return { $first: `$${expr.__field}` };\n\n case \"last\":\n if (!expr.__field) {\n throw new Error(\"Last aggregate requires a field name\");\n }\n return { $last: `$${expr.__field}` };\n\n case \"distinct\":\n if (!expr.__field) {\n throw new Error(\"Distinct aggregate requires a field name\");\n }\n return { $distinct: `$${expr.__field}` };\n\n case \"floor\":\n if (!expr.__field) {\n throw new Error(\"Floor aggregate requires a field name\");\n }\n\n return { $floor: `$${expr.__field}` };\n\n default:\n throw new Error(`Unknown aggregate function: ${expr.__agg}`);\n }\n }\n\n private buildGroupId(fields: GroupByInput): any {\n if (!fields) {\n return null;\n }\n\n if (typeof fields === \"string\") {\n return `$${fields}`;\n }\n\n if (Array.isArray(fields)) {\n if (fields.length === 0) {\n return null;\n }\n\n const allStrings = fields.every((field) => typeof field === \"string\");\n if (allStrings) {\n const result: Record<string, string> = {};\n for (const field of fields as string[]) {\n result[field] = `$${field}`;\n }\n return result;\n }\n\n // Array of objects - merge them to build complex _id structures\n return (fields as Record<string, unknown>[]).reduce((acc, item) => ({ ...acc, ...item }), {});\n }\n\n if (typeof fields === \"object\") {\n const normalized: Record<string, unknown> = {};\n Object.entries(fields).forEach(([key, value]) => {\n if (typeof value === \"string\" && !value.startsWith(\"$\")) {\n normalized[key] = `$${value}`;\n } else {\n normalized[key] = value;\n }\n });\n return normalized;\n }\n\n return null;\n }\n\n /**\n * Build a $lookup stage from join operations.\n *\n * @param operations - The join operations\n * @returns The $lookup stage or null\n */\n private buildLookupStage(operations: Operation[]): any {\n const op = operations[0];\n const options = op.data;\n\n return {\n $lookup: {\n from: options.table,\n localField: options.localField,\n foreignField: options.foreignField,\n as: options.alias || options.table,\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;AA8BA,IAAa,mBAAb,MAA8B;;;;CAI5B,AAAiB;;;;CAKjB,AAAiB;;;;CAKjB,AAAiB;;;;;CAMjB,AAAiB,kCAAkB,IAAI,IAA+B;;;;;;CAOtE,AAAO,YAAY,SAAkC;EACnD,KAAK,aAAa,QAAQ;EA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,aAAa,QAA2B;EAC9C,IAAI,CAAC,QACH,OAAO;EAGT,IAAI,OAAO,WAAW,UACpB,OAAO,IAAI;EAGb,IAAI,MAAM,QAAQ,MAAM,GAAG;GACzB,IAAI,OAAO,WAAW,GACpB,OAAO;GAIT,IADmB,OAAO,OAAO,UAAU,OAAO,UAAU,QAC/C,GAAG;IACd,MAAM,SAAiC,CAAC;IACxC,KAAK,MAAM,SAAS,QAClB,OAAO,SAAS,IAAI;IAEtB,OAAO;GACT;GAGA,OAAQ,OAAqC,QAAQ,KAAK,UAAU;IAAE,GAAG;IAAK,GAAG;GAAK,IAAI,CAAC,CAAC;EAC9F;EAEA,IAAI,OAAO,WAAW,UAAU;GAC9B,MAAM,aAAsC,CAAC;GAC7C,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;IAC/C,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,WAAW,GAAG,GACpD,WAAW,OAAO,IAAI;SAEtB,WAAW,OAAO;GAEtB,CAAC;GACD,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;CAQA,AAAQ,iBAAiB,YAA8B;EAErD,MAAM,UADK,WAAW,EACJ,CAAC;EAEnB,OAAO,EACL,SAAS;GACP,MAAM,QAAQ;GACd,YAAY,QAAQ;GACpB,cAAc,QAAQ;GACtB,IAAI,QAAQ,SAAS,QAAQ;EAC/B,EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"mongodb-query-parser.mjs","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/mongodb/mongodb-query-parser.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport type { Collection } from \"mongodb\";\nimport type { GroupByInput, RawExpression, WhereOperator } from \"../../contracts\";\nimport {\n isAggregateExpression,\n type AggregateExpression,\n} from \"../../expressions/aggregate-expressions\";\nimport type { ColumnExpression } from \"../../expressions/column-expressions\";\nimport type { MongoQueryBuilder } from \"./mongodb-query-builder\";\nimport type { Operation, PipelineStage } from \"./types\";\n\n/**\n * Options for configuring the MongoDB query parser.\n */\nexport type MongoQueryParserOptions = {\n /** The MongoDB collection being queried */\n collection: Collection;\n /** The ordered list of operations to parse */\n operations: Operation[];\n /** Factory method for creating sub-builders (used for callbacks) */\n createSubBuilder: () => MongoQueryBuilder;\n};\n\n/**\n * Parses query builder operations into MongoDB aggregation pipeline.\n *\n * This parser is responsible for converting the abstract operations collected\n * by the query builder into a concrete MongoDB aggregation pipeline. It handles\n * intelligent grouping of mergeable operations (like multiple where clauses)\n * into single pipeline stages for optimal performance.\n */\nexport class MongoQueryParser {\n /**\n * The MongoDB collection being queried.\n */\n private readonly collection: Collection;\n\n /**\n * The ordered list of operations to parse.\n */\n private readonly operations: Operation[];\n\n /**\n * Factory for creating sub-builders (used when resolving callbacks).\n */\n private readonly createSubBuilder: () => MongoQueryBuilder;\n\n /**\n * Track group field names for automatic _id renaming.\n * Maps pipeline index to field names.\n */\n private readonly groupFieldNames = new Map<number, string | string[]>();\n\n /**\n * Track `countDistinct` aggregate aliases per group stage. The renaming\n * `$project` finalizes these with `{ $size: \"$alias\" }` over the set built\n * by `$addToSet` in the `$group` stage.\n * Maps pipeline index to the set of aliases needing `$size` finalization.\n */\n private readonly countDistinctAliases = new Map<number, Set<string>>();\n\n /**\n * Create a new MongoDB query parser.\n *\n * @param options - Configuration options for the parser\n */\n public constructor(options: MongoQueryParserOptions) {\n this.collection = options.collection;\n this.operations = options.operations;\n this.createSubBuilder = options.createSubBuilder;\n }\n\n /**\n * Parse the operations into a MongoDB aggregation pipeline.\n *\n * This method intelligently groups mergeable operations (e.g., multiple where\n * clauses) into single pipeline stages while maintaining the correct execution\n * order for non-mergeable operations.\n *\n * @returns The MongoDB aggregation pipeline\n *\n * @example\n * ```typescript\n * const parser = new MongoQueryParser({ collection, operations });\n * const pipeline = parser.parse();\n * // [\n * // { $match: { status: 'active', age: { $gt: 18 } } },\n * // { $sort: { createdAt: -1 } },\n * // { $limit: 10 }\n * // ]\n * ```\n */\n public parse(): any[] {\n const pipeline: any[] = [];\n let currentStage: PipelineStage | null = null;\n let currentBuffer: Operation[] = [];\n\n for (const op of this.operations) {\n if (op.mergeable && op.stage === currentStage) {\n // Same mergeable stage, add to buffer\n currentBuffer.push(op);\n } else {\n // Different stage or non-mergeable, flush buffer\n if (currentBuffer.length > 0) {\n const builtStage = this.buildStage(currentStage!, currentBuffer);\n if (builtStage) {\n const stageIndex = pipeline.length;\n pipeline.push(builtStage);\n // Track field names for group stages with aggregates\n this.trackGroupFieldNames(currentStage!, currentBuffer, stageIndex);\n }\n currentBuffer = [];\n }\n\n if (op.mergeable) {\n // Start new buffer\n currentStage = op.stage;\n currentBuffer.push(op);\n } else {\n // Non-mergeable, add directly\n const builtStage = this.buildStage(op.stage, [op]);\n if (builtStage) {\n const stageIndex = pipeline.length;\n pipeline.push(builtStage);\n // Track field names for group stages with aggregates\n this.trackGroupFieldNames(op.stage, [op], stageIndex);\n }\n currentStage = null;\n }\n }\n }\n\n // Flush remaining buffer\n if (currentBuffer.length > 0) {\n const builtStage = this.buildStage(currentStage!, currentBuffer);\n if (builtStage) {\n const stageIndex = pipeline.length;\n pipeline.push(builtStage);\n // Track field names for group stages with aggregates\n this.trackGroupFieldNames(currentStage!, currentBuffer, stageIndex);\n }\n }\n\n // Post-process: Rename _id to actual field names after $group stages with aggregates\n return this.postProcessGroupStages(pipeline);\n }\n\n /**\n * Track field names for group stages that need _id renaming.\n */\n private trackGroupFieldNames(\n stage: PipelineStage,\n operations: Operation[],\n stageIndex: number,\n ): void {\n if (stage === \"$group\") {\n const op = operations[0];\n if (op.type === \"groupByWithAggregates\" && op.data.fields) {\n const fieldNames = this.extractGroupFieldNames(op.data.fields);\n if (fieldNames) {\n this.groupFieldNames.set(stageIndex, fieldNames);\n }\n\n this.trackCountDistinctAliases(stageIndex, op.data.aggregates);\n } else if (op.type === \"groupByDate\") {\n // The `$dateTrunc` bucket becomes `_id`; rename it back to the column.\n this.groupFieldNames.set(stageIndex, op.data.column as string);\n this.trackCountDistinctAliases(stageIndex, op.data.aggregates ?? {});\n }\n }\n }\n\n /**\n * Record which aggregate aliases in a group stage are `countDistinct` so the\n * renaming `$project` can finalize them with `{ $size: \"$alias\" }` over the\n * set built by `$addToSet` (the standard distinct-count-per-group pattern).\n */\n private trackCountDistinctAliases(\n stageIndex: number,\n aggregates: Record<string, RawExpression>,\n ): void {\n const distinctAliases = new Set<string>();\n for (const [alias, expression] of Object.entries(aggregates)) {\n if (isAggregateExpression(expression) && expression.__agg === \"countDistinct\") {\n distinctAliases.add(alias);\n }\n }\n\n if (distinctAliases.size > 0) {\n this.countDistinctAliases.set(stageIndex, distinctAliases);\n }\n }\n\n /**\n * Post-process pipeline to rename _id fields after $group stages.\n *\n * This automatically renames MongoDB's `_id` field to the actual field name(s)\n * used for grouping, making the results more intuitive.\n *\n * @param pipeline - The aggregation pipeline\n * @returns The processed pipeline\n */\n private postProcessGroupStages(pipeline: any[]): any[] {\n const processed: any[] = [];\n\n for (let i = 0; i < pipeline.length; i++) {\n const stage = pipeline[i];\n\n // Check if this is a $group stage that needs _id renaming\n if (stage.$group && this.groupFieldNames.has(i)) {\n const fieldNames = this.groupFieldNames.get(i)!;\n\n // Add the $group stage\n processed.push(stage);\n\n // Add a $project stage to rename _id\n const projection: Record<string, unknown> = {};\n\n if (typeof fieldNames === \"string\") {\n // Single field: rename _id to field name\n projection[fieldNames] = \"$_id\";\n } else if (Array.isArray(fieldNames) && fieldNames.length > 0) {\n // Multiple fields: _id is an object, spread it\n for (const fieldName of fieldNames) {\n projection[fieldName] = `$_id.${fieldName}`;\n }\n }\n\n // Include all aggregate fields. countDistinct aliases are finalized\n // with `{ $size: \"$alias\" }` over the set built by `$addToSet`; every\n // other aggregate is projected through as-is.\n const distinctAliases = this.countDistinctAliases.get(i);\n const aggregateFields = Object.keys(stage.$group).filter((key) => key !== \"_id\");\n for (const field of aggregateFields) {\n if (distinctAliases?.has(field)) {\n projection[field] = { $size: `$${field}` };\n } else {\n projection[field] = 1;\n }\n }\n\n if (Object.keys(projection).length > 0) {\n // now unselect the _id field\n projection._id = 0;\n processed.push({ $project: projection });\n }\n } else {\n // Regular stage, add as-is\n processed.push(stage);\n }\n }\n\n return processed;\n }\n\n /**\n * Convert the parsed pipeline to a pretty-printed string for debugging.\n *\n * This method formats the MongoDB aggregation pipeline in a human-readable\n * way, making it easier to understand and debug complex queries.\n *\n * @returns A formatted string representation of the pipeline\n *\n * @example\n * ```typescript\n * const parser = new MongoQueryParser({ collection, operations });\n * console.log(parser.toPrettyString());\n * // Output:\n * // MongoDB Aggregation Pipeline:\n * // ════════════════════════════\n * // Stage 1: $match\n * // status: \"active\"\n * // age: { $gt: 18 }\n * //\n * // Stage 2: $sort\n * // createdAt: -1\n * ```\n */\n public toPrettyString(): string {\n const pipeline = this.parse();\n\n if (pipeline.length === 0) {\n return \"MongoDB Aggregation Pipeline: (empty)\";\n }\n\n let output = \"MongoDB Aggregation Pipeline:\\n\";\n output += \"═\".repeat(50) + \"\\n\";\n\n pipeline.forEach((stage, index) => {\n const stageName = Object.keys(stage)[0];\n const stageData = stage[stageName];\n\n if (index > 0) {\n output += \"\\n\";\n }\n\n output += `Stage ${index + 1}: ${colors.redBright(stageName)}\\n`;\n output += this.formatStageData(stageData, 2);\n });\n\n return output;\n }\n\n /**\n * Format stage data with proper indentation.\n *\n * @param data - The stage data to format\n * @param indent - The indentation level\n * @returns Formatted string\n */\n private formatStageData(data: any, indent: number = 0): string {\n const spaces = \" \".repeat(indent);\n\n if (typeof data !== \"object\" || data === null) {\n return `${spaces}${JSON.stringify(data)}\\n`;\n }\n\n if (Array.isArray(data)) {\n if (data.length === 0) return `${spaces}[]`;\n\n let result = \"\";\n data.forEach((item, index) => {\n result += `${spaces}[${colors.magenta(index)}]:\\n`;\n result += this.formatStageData(item, indent + 2);\n });\n return result;\n }\n\n let result = \"\";\n Object.entries(data).forEach(([key, value]) => {\n const isOperator = key.startsWith(\"$\");\n const coloredKey = isOperator ? colors.magentaBright(key) : colors.blue(key);\n\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n result += `${spaces}${coloredKey}:\\n`;\n result += this.formatStageData(value, indent + 2);\n } else if (Array.isArray(value)) {\n result += `${spaces}${coloredKey}:\\n`;\n result += this.formatStageData(value, indent + 2);\n } else {\n const formattedValue =\n typeof value === \"number\"\n ? colors.yellowBright(value)\n : typeof value === \"boolean\"\n ? colors.cyanBright(value.toString())\n : typeof value === \"string\"\n ? colors.greenBright(JSON.stringify(value))\n : colors.greenBright(String(value));\n result += `${spaces}${coloredKey}: ${formattedValue}\\n`;\n }\n });\n\n return result.endsWith(\"\\n\") ? result : `${result}\\n`;\n }\n\n /**\n * Build a single pipeline stage from a group of operations.\n *\n * @param stage - The pipeline stage type\n * @param operations - The operations to build the stage from\n * @returns The built pipeline stage or null if no stage should be added\n */\n private buildStage(stage: PipelineStage, operations: Operation[]): any {\n switch (stage) {\n case \"$match\":\n return this.buildMatchStage(operations);\n case \"$project\":\n return this.buildProjectStage(operations);\n case \"$sort\":\n return this.buildSortStage(operations);\n case \"$group\":\n return this.buildGroupStage(operations);\n case \"$lookup\":\n return this.buildLookupStage(operations);\n case \"$limit\":\n return { $limit: operations[0].data.value };\n case \"$skip\":\n return { $skip: operations[0].data.value };\n case \"$setWindowFields\":\n return {\n $setWindowFields: operations[0].data.spec,\n };\n default:\n return null;\n }\n }\n\n /**\n * Build a $match stage from where operations.\n *\n * Query building strategy:\n * - Top-level where() + orWhere() = Pure OR\n * - Use callbacks for AND + OR grouping\n *\n * @param operations - The where operations\n * @returns The $match stage or null\n */\n private buildMatchStage(operations: Operation[]): any {\n const andFilter: Record<string, any> = {};\n const orClauses: any[] = [];\n const pendingSimpleWhere: any[] = [];\n let topLevelOrMode = false;\n\n const pushOr = (clause: any): void => {\n if (!clause) {\n return;\n }\n\n if (this.isPureOrCondition(clause)) {\n orClauses.push(...clause.$or);\n return;\n }\n\n if (Array.isArray(clause)) {\n orClauses.push(...clause);\n return;\n }\n\n orClauses.push(clause);\n };\n\n const mergeAnd = (condition: any): void => {\n if (!condition) {\n return;\n }\n\n Object.entries(condition).forEach(([key, value]) => {\n if (key === \"$or\") {\n pushOr(value);\n return;\n }\n\n if (\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n andFilter[key] &&\n typeof andFilter[key] === \"object\" &&\n !Array.isArray(andFilter[key])\n ) {\n andFilter[key] = { ...andFilter[key], ...value };\n } else {\n andFilter[key] = value;\n }\n });\n };\n\n const queueSimpleWhere = (condition: any): void => {\n if (!condition) {\n return;\n }\n if (topLevelOrMode) {\n pushOr(condition);\n } else {\n pendingSimpleWhere.push(condition);\n }\n };\n\n const enterTopLevelOrMode = (): void => {\n if (topLevelOrMode) {\n return;\n }\n topLevelOrMode = true;\n while (pendingSimpleWhere.length > 0) {\n const condition = pendingSimpleWhere.shift();\n if (condition) {\n pushOr(condition);\n }\n }\n };\n\n const flushPendingSimpleWhere = (): void => {\n if (pendingSimpleWhere.length === 0) {\n return;\n }\n if (topLevelOrMode) {\n pendingSimpleWhere.forEach(pushOr);\n } else {\n pendingSimpleWhere.forEach(mergeAnd);\n }\n pendingSimpleWhere.length = 0;\n };\n\n for (const op of operations) {\n if (op.type === \"where:callback\" || op.type === \"orWhere:callback\") {\n flushPendingSimpleWhere();\n const callbackCondition = this.buildCallbackCondition(op.data);\n if (!callbackCondition) {\n continue;\n }\n\n const treatAsOr =\n op.type === \"orWhere:callback\" ||\n (topLevelOrMode && !this.isPureOrCondition(callbackCondition)) ||\n this.isPureOrCondition(callbackCondition);\n\n if (treatAsOr) {\n if (op.type === \"orWhere:callback\") {\n enterTopLevelOrMode();\n }\n pushOr(callbackCondition);\n } else {\n mergeAnd(callbackCondition);\n }\n continue;\n }\n\n if (op.type === \"where:object\") {\n queueSimpleWhere(op.data);\n continue;\n }\n\n if (\n op.type === \"where:not\" ||\n op.type === \"orWhere:not\" ||\n op.type === \"where:exists\" ||\n op.type === \"where:notExists\"\n ) {\n const negated = op.type === \"where:not\" || op.type === \"where:notExists\";\n const nested = this.buildCallbackCondition(op.data.callback);\n if (nested) {\n const condition = negated ? { $nor: [nested] } : nested;\n if (op.type.startsWith(\"orWhere\")) {\n enterTopLevelOrMode();\n pushOr(condition);\n } else {\n queueSimpleWhere(condition);\n }\n }\n continue;\n }\n\n if (op.type === \"orWhere:object\") {\n enterTopLevelOrMode();\n pushOr(op.data);\n continue;\n }\n\n const condition = this.buildWhereCondition(op);\n if (!condition) {\n continue;\n }\n\n if (op.type.startsWith(\"orWhere\")) {\n enterTopLevelOrMode();\n pushOr(condition);\n } else {\n queueSimpleWhere(condition);\n }\n }\n\n flushPendingSimpleWhere();\n\n const hasAnd = Object.keys(andFilter).length > 0;\n const hasOr = orClauses.length > 0;\n\n if (!hasAnd && !hasOr) {\n return null;\n }\n\n const match: any = {};\n if (hasAnd) {\n Object.assign(match, andFilter);\n }\n if (hasOr) {\n match.$or = orClauses;\n }\n\n return { $match: match };\n }\n\n private isPureOrCondition(condition: any): condition is { $or: any[] } {\n return (\n condition &&\n typeof condition === \"object\" &&\n !Array.isArray(condition) &&\n Object.keys(condition).length === 1 &&\n Array.isArray((condition as any).$or)\n );\n }\n\n /**\n * Build a condition from a callback-based where clause.\n * Creates a sub-builder, executes the callback, and extracts the conditions.\n * If callback has orWhere, all conditions become OR.\n *\n * @param callback - The callback function\n * @returns The built condition or null\n */\n private buildCallbackCondition(callback: any): any {\n // Create a temporary sub-builder\n const subBuilder = this.createSubBuilder();\n\n // Execute the callback with the sub-builder\n callback(subBuilder);\n\n // Extract only match operations from the sub-builder\n const matchOps = subBuilder.operations.filter((op: Operation) => op.stage === \"$match\");\n\n if (matchOps.length === 0) {\n return null;\n }\n\n const andFilter: Record<string, any> = {};\n const orClauses: any[] = [];\n const hasInternalOr = matchOps.some((op) => op.type.startsWith(\"orWhere\"));\n\n const pushOr = (clause: any): void => {\n if (!clause) {\n return;\n }\n if (this.isPureOrCondition(clause)) {\n orClauses.push(...clause.$or);\n return;\n }\n orClauses.push(clause);\n };\n\n if (hasInternalOr) {\n for (const op of matchOps) {\n if (op.type === \"where:callback\" || op.type === \"orWhere:callback\") {\n const nestedCondition = this.buildCallbackCondition(op.data);\n if (nestedCondition) {\n pushOr(nestedCondition);\n }\n continue;\n }\n\n if (op.type === \"where:object\" || op.type === \"orWhere:object\") {\n pushOr(op.data);\n continue;\n }\n\n const condition = this.buildWhereCondition(op);\n if (condition) {\n pushOr(condition);\n }\n }\n\n return orClauses.length > 0 ? { $or: orClauses } : null;\n }\n\n for (const op of matchOps) {\n if (op.type === \"where:callback\") {\n const nestedCondition = this.buildCallbackCondition(op.data);\n if (nestedCondition) {\n Object.assign(andFilter, nestedCondition);\n }\n } else if (op.type === \"where:object\") {\n Object.assign(andFilter, op.data);\n } else {\n const condition = this.buildWhereCondition(op);\n if (condition) {\n Object.assign(andFilter, condition);\n }\n }\n }\n\n return Object.keys(andFilter).length > 0 ? andFilter : null;\n }\n\n /**\n * Build a MongoDB filter condition from a where operation.\n *\n * @param op - The operation to build\n * @returns The MongoDB filter condition\n */\n private buildWhereCondition(op: Operation): any {\n const { field, operator, value } = op.data;\n\n switch (op.type) {\n case \"where\":\n case \"orWhere\":\n return this.buildOperatorCondition(field, operator, value);\n\n case \"whereIn\":\n return { [field]: { $in: value || op.data.values } };\n\n case \"whereNotIn\":\n return { [field]: { $nin: value || op.data.values } };\n\n case \"whereNull\":\n return { [field]: null };\n\n case \"whereNotNull\":\n return { [field]: { $ne: null } };\n\n case \"whereBetween\":\n return {\n [field]: {\n $gte: op.data.range[0],\n $lte: op.data.range[1],\n },\n };\n\n case \"whereNotBetween\":\n return {\n [field]: {\n $not: {\n $gte: op.data.range[0],\n $lte: op.data.range[1],\n },\n },\n };\n\n case \"whereLike\": {\n const pattern =\n typeof op.data.pattern === \"string\" ? op.data.pattern : op.data.pattern.source;\n return { [field]: { $regex: pattern, $options: \"i\" } };\n }\n\n case \"whereNotLike\": {\n const notPattern =\n typeof op.data.pattern === \"string\" ? op.data.pattern : op.data.pattern.source;\n return { [field]: { $not: { $regex: notPattern, $options: \"i\" } } };\n }\n\n case \"whereStartsWith\":\n return { [field]: { $regex: `^${op.data.value}`, $options: \"i\" } };\n\n case \"whereNotStartsWith\":\n return {\n [field]: { $not: { $regex: `^${op.data.value}`, $options: \"i\" } },\n };\n\n case \"whereEndsWith\":\n return { [field]: { $regex: `${op.data.value}$`, $options: \"i\" } };\n\n case \"whereNotEndsWith\":\n return {\n [field]: { $not: { $regex: `${op.data.value}$`, $options: \"i\" } },\n };\n\n case \"whereExists\":\n return { [field]: { $exists: true } };\n\n case \"whereNotExists\":\n return { [field]: { $exists: false } };\n\n case \"whereSize\":\n if (op.data.operator === \"=\") {\n return { [field]: { $size: op.data.size } };\n } else {\n const mongoOp = this.getMongoOperator(op.data.operator);\n return {\n $expr: {\n [mongoOp]: [{ $size: `$${field}` }, op.data.size],\n },\n };\n }\n\n case \"textSearch\":\n return {\n $text: { $search: op.data.query },\n ...(op.data.filters || {}),\n };\n\n case \"whereRaw\":\n case \"orWhereRaw\":\n return this.resolveRawExpression(\n op.data.expression as RawExpression,\n op.data.bindings,\n );\n\n case \"whereColumn\":\n case \"orWhereColumn\":\n return this.buildColumnComparison(op.data.first, op.data.operator, op.data.second);\n\n case \"whereBetweenColumns\":\n return this.buildBetweenColumnsCondition(\n op.data.field,\n op.data.lowerColumn,\n op.data.upperColumn,\n );\n\n case \"whereDate\":\n case \"whereDateEquals\":\n return this.buildDateEqualityCondition(op.data.field, op.data.value);\n\n case \"whereDateBefore\":\n return this.buildDateBeforeCondition(op.data.field, op.data.value);\n\n case \"whereDateAfter\":\n return this.buildDateAfterCondition(op.data.field, op.data.value);\n\n case \"whereTime\":\n return this.buildTimeCondition(op.data.field, op.data.value);\n\n case \"whereDay\":\n return this.buildDatePartCondition(op.data.field, \"$dayOfMonth\", op.data.value);\n\n case \"whereMonth\":\n return this.buildDatePartCondition(op.data.field, \"$month\", op.data.value);\n\n case \"whereYear\":\n return this.buildDatePartCondition(op.data.field, \"$year\", op.data.value);\n\n case \"whereJsonContains\":\n return this.buildJsonContainsCondition(op.data.path, op.data.value);\n\n case \"whereJsonDoesntContain\":\n return this.buildJsonDoesntContainCondition(op.data.path, op.data.value);\n\n case \"whereJsonContainsKey\":\n return this.buildJsonContainsKeyCondition(op.data.path);\n\n case \"whereJsonLength\":\n return this.buildJsonLengthCondition(\n op.data.path,\n op.data.operator,\n op.data.value,\n );\n\n case \"whereJsonIsArray\":\n return this.buildJsonTypeCondition(op.data.path, \"array\");\n\n case \"whereJsonIsObject\":\n return this.buildJsonTypeCondition(op.data.path, \"object\");\n\n case \"whereArrayLength\":\n return this.buildArrayLengthCondition(\n op.data.field,\n op.data.operator,\n op.data.value,\n );\n\n case \"whereFullText\":\n case \"orWhereFullText\":\n return { $text: { $search: op.data.query } };\n\n case \"whereSearch\":\n return {\n [op.data.field]: {\n $regex: op.data.query,\n $options: \"i\",\n },\n };\n\n case \"where:not\":\n case \"orWhere:not\": {\n const nestedNot = this.buildCallbackCondition(op.data.callback);\n return nestedNot ? { $nor: [nestedNot] } : null;\n }\n\n case \"where:exists\":\n return this.buildCallbackCondition(op.data.callback);\n\n case \"where:notExists\": {\n const nestedExists = this.buildCallbackCondition(op.data.callback);\n return nestedExists ? { $nor: [nestedExists] } : null;\n }\n\n case \"whereArrayContains\":\n if (op.data.key) {\n return {\n [field]: {\n $elemMatch: { [op.data.key]: op.data.value },\n },\n };\n } else {\n return { [field]: op.data.value };\n }\n\n default:\n return null;\n }\n }\n\n /**\n * Build a condition based on the operator.\n *\n * @param field - The field name\n * @param operator - The comparison operator\n * @param value - The value to compare\n * @returns The MongoDB filter condition\n */\n private buildOperatorCondition(field: string, operator: string, value: unknown): any {\n switch (operator) {\n case \"=\":\n return { [field]: value };\n case \"!=\":\n return { [field]: { $ne: value } };\n case \">\":\n return { [field]: { $gt: value } };\n case \">=\":\n return { [field]: { $gte: value } };\n case \"<\":\n return { [field]: { $lt: value } };\n case \"<=\":\n return { [field]: { $lte: value } };\n default:\n return { [field]: value };\n }\n }\n\n /**\n * Get MongoDB operator from comparison operator.\n *\n * @param operator - The comparison operator\n * @returns The MongoDB operator\n */\n private getMongoOperator(operator: string): string {\n const map: Record<string, string> = {\n \"=\": \"$eq\",\n \"!=\": \"$ne\",\n \">\": \"$gt\",\n \">=\": \"$gte\",\n \"<\": \"$lt\",\n \"<=\": \"$lte\",\n };\n return map[operator] || \"$eq\";\n }\n\n private resolveRawExpression(expression: RawExpression, bindings?: unknown[]): any {\n if (typeof expression === \"string\") {\n const bound = this.bindRawString(expression, bindings);\n return { $where: bound };\n }\n\n if (typeof expression === \"object\" && expression !== null) {\n return expression;\n }\n\n return null;\n }\n\n private bindRawString(expression: string, bindings?: unknown[]): string {\n if (!bindings || bindings.length === 0) {\n return expression;\n }\n\n let index = 0;\n return expression.replace(/\\?/g, () => {\n const value = bindings[index++];\n return value === undefined ? \"?\" : JSON.stringify(value);\n });\n }\n\n private buildColumnComparison(first: string, operator: WhereOperator, second: string): any {\n const mongoOperator = this.getMongoOperator(operator);\n return {\n $expr: {\n [mongoOperator]: [this.wrapColumn(first), this.wrapColumn(second)],\n },\n };\n }\n\n private buildBetweenColumnsCondition(field: string, lower: string, upper: string): any {\n return {\n $expr: {\n $and: [\n { $gte: [this.wrapColumn(field), this.wrapColumn(lower)] },\n { $lte: [this.wrapColumn(field), this.wrapColumn(upper)] },\n ],\n },\n };\n }\n\n private wrapColumn(column: string): string {\n return column.startsWith(\"$\") ? column : `$${column}`;\n }\n\n private buildDateEqualityCondition(field: string, value: Date | string): any {\n const target = this.normalizeDateInput(value);\n const start = this.startOfDay(target);\n const end = this.endOfDay(target);\n return { [field]: { $gte: start, $lte: end } };\n }\n\n private buildDateBeforeCondition(field: string, value: Date | string): any {\n const target = this.startOfDay(this.normalizeDateInput(value));\n return { [field]: { $lt: target } };\n }\n\n private buildDateAfterCondition(field: string, value: Date | string): any {\n const target = this.endOfDay(this.normalizeDateInput(value));\n return { [field]: { $gt: target } };\n }\n\n private buildTimeCondition(field: string, value: string): any {\n return {\n $expr: {\n $eq: [\n {\n $dateToString: {\n format: \"%H:%M\",\n date: `$${field}`,\n },\n },\n value,\n ],\n },\n };\n }\n\n private buildDatePartCondition(\n field: string,\n operator: \"$dayOfMonth\" | \"$month\" | \"$year\",\n value: number,\n ): any {\n return {\n $expr: {\n $eq: [\n {\n [operator]: `$${field}`,\n },\n value,\n ],\n },\n };\n }\n\n private buildJsonContainsCondition(path: string, value: unknown): any {\n const fieldPath = this.normalizePath(path);\n if (Array.isArray(value)) {\n return { [fieldPath]: { $all: value } };\n }\n return { [fieldPath]: value };\n }\n\n private buildJsonDoesntContainCondition(path: string, value: unknown): any {\n const fieldPath = this.normalizePath(path);\n const values = Array.isArray(value) ? value : [value];\n return { [fieldPath]: { $nin: values } };\n }\n\n private buildJsonContainsKeyCondition(path: string): any {\n return {\n [this.normalizePath(path)]: { $exists: true },\n };\n }\n\n private buildJsonLengthCondition(path: string, operator: WhereOperator, value: number): any {\n const mongoOperator = this.getMongoOperator(operator);\n return {\n $expr: {\n [mongoOperator]: [{ $size: { $ifNull: [`$${this.normalizePath(path)}`, []] } }, value],\n },\n };\n }\n\n private buildJsonTypeCondition(path: string, type: string): any {\n return {\n $expr: {\n $eq: [{ $type: `$${this.normalizePath(path)}` }, type],\n },\n };\n }\n\n private buildArrayLengthCondition(field: string, operator: WhereOperator, value: number): any {\n const mongoOperator = this.getMongoOperator(operator);\n return {\n $expr: {\n [mongoOperator]: [{ $size: { $ifNull: [`$${field}`, []] } }, value],\n },\n };\n }\n\n private normalizeDateInput(value: Date | string): Date {\n if (value instanceof Date) {\n return value;\n }\n const parsed = new Date(value);\n if (Number.isNaN(parsed.getTime())) {\n throw new Error(`Invalid date value: ${value}`);\n }\n return parsed;\n }\n\n private startOfDay(date: Date): Date {\n const copy = new Date(date);\n copy.setHours(0, 0, 0, 0);\n return copy;\n }\n\n private endOfDay(date: Date): Date {\n const copy = new Date(date);\n copy.setHours(23, 59, 59, 999);\n return copy;\n }\n\n private normalizePath(path: string): string {\n return path.replace(/->/g, \".\");\n }\n\n private applyProjectionFields(\n projection: Record<string, unknown>,\n fields: string[],\n value: 0 | 1,\n ): void {\n for (const field of fields) {\n projection[field] = value;\n }\n }\n\n /**\n * Apply projection object with aliases and inclusion/exclusion.\n * @param projection - The projection object to modify\n * @param projectionObj - The projection specification\n */\n private applyProjectionObject(\n projection: Record<string, unknown>,\n projectionObj: Record<string, unknown>,\n ): void {\n for (const [field, value] of Object.entries(projectionObj)) {\n // Handle boolean values (true = 1, false = 0)\n if (typeof value === \"boolean\") {\n projection[field] = value ? 1 : 0;\n continue;\n }\n\n // Handle numeric values (0 or 1)\n if (typeof value === \"number\") {\n projection[field] = value;\n continue;\n }\n\n // Handle string values (aliases)\n if (typeof value === \"string\") {\n // Alias: project the field with a new name\n projection[value] = `$${field}`;\n continue;\n }\n\n // Handle complex expressions (objects)\n if (typeof value === \"object\" && value !== null) {\n projection[field] = value;\n continue;\n }\n\n // Default: include the field\n projection[field] = 1;\n }\n }\n\n private applyRawProjection(\n projection: Record<string, unknown>,\n expression: RawExpression,\n bindings?: unknown[],\n ): void {\n const resolved = this.resolveProjectionExpression(expression, bindings);\n if (!resolved) {\n return;\n }\n\n if (typeof resolved === \"object\" && resolved !== null && !Array.isArray(resolved)) {\n Object.assign(projection, resolved as Record<string, unknown>);\n }\n }\n\n private resolveProjectionExpression(\n expression: RawExpression | unknown,\n bindings?: unknown[],\n ): any {\n if (typeof expression === \"string\") {\n const source =\n bindings && expression.includes(\"?\")\n ? this.bindRawString(expression, bindings)\n : expression;\n if (source.startsWith(\":\")) {\n return source.slice(1);\n }\n return this.normalizeFieldReference(source);\n }\n\n if (typeof expression === \"object\" && expression !== null && !(expression instanceof Date)) {\n return expression;\n }\n\n if (typeof expression === \"number\" || typeof expression === \"boolean\") {\n return expression;\n }\n\n return expression;\n }\n\n private normalizeFieldReference(value: string | RawExpression): any {\n if (typeof value === \"string\") {\n if (value.startsWith(\":\")) {\n return value.slice(1);\n }\n // If already a field reference, return as-is\n if (value.startsWith(\"$\")) {\n return value;\n }\n // Check if it's a string literal (contains spaces or special chars)\n // Field paths are typically: alphanumeric, underscore, dot only\n if (!/^[a-zA-Z0-9_.]+$/.test(value)) {\n return value; // Return as literal\n }\n // Otherwise, treat as field reference\n return `$${value}`;\n }\n return value;\n }\n\n private buildAggregateProjection(field: string, aggregate: string): any {\n if (aggregate === \"count\") {\n return this.buildArraySizeExpression(field);\n }\n\n const map: Record<string, string> = {\n sum: \"$sum\",\n avg: \"$avg\",\n min: \"$min\",\n max: \"$max\",\n first: \"$first\",\n last: \"$last\",\n };\n\n const operator = map[aggregate];\n if (!operator) {\n return null;\n }\n\n return {\n [operator]: this.normalizeFieldReference(field),\n };\n }\n\n private buildExistsProjection(field: string): any {\n return {\n $ne: [{ $type: `$${field}` }, \"missing\"],\n };\n }\n\n private buildArraySizeExpression(field: string): any {\n return {\n $size: { $ifNull: [`$${field}`, []] },\n };\n }\n\n private buildCaseExpression(\n cases: Array<{ when: RawExpression; then: RawExpression | unknown }>,\n otherwise: RawExpression | unknown,\n ): any {\n return {\n $switch: {\n branches: cases.map((item) => ({\n case: this.resolveProjectionExpression(item.when),\n then: this.resolveLiteralOrExpression(item.then),\n })),\n default: this.resolveLiteralOrExpression(otherwise),\n },\n };\n }\n\n private buildCondExpression(\n condition: RawExpression,\n thenValue: RawExpression | unknown,\n elseValue: RawExpression | unknown,\n ): any {\n return {\n $cond: [\n this.resolveProjectionExpression(condition),\n this.resolveLiteralOrExpression(thenValue),\n this.resolveLiteralOrExpression(elseValue),\n ],\n };\n }\n\n /**\n * Resolve a value as a literal (if it's a plain string) or as an expression.\n * Used for `then`/`default` values in CASE/WHEN expressions.\n */\n private resolveLiteralOrExpression(value: RawExpression | unknown): any {\n // If it's a string that starts with $, treat as field reference\n if (typeof value === \"string\" && value.startsWith(\"$\")) {\n return value;\n }\n // If it's a plain string (not starting with $), treat as literal\n if (typeof value === \"string\") {\n return value;\n }\n // For objects (expressions), numbers, booleans, etc., use normal resolution\n return this.resolveProjectionExpression(value);\n }\n\n private inferJsonAlias(path: string): string {\n const normalized = this.normalizePath(path);\n const segments = normalized.split(\".\");\n return segments[segments.length - 1];\n }\n\n private buildConcatExpression(values: Array<string | RawExpression>): any {\n return {\n $concat: values.map((value) => this.normalizeFieldReference(value)),\n };\n }\n\n private buildCoalesceExpression(values: Array<string | RawExpression>): any {\n if (values.length === 0) {\n return null;\n }\n\n let expression = this.normalizeFieldReference(values[values.length - 1]);\n\n for (let index = values.length - 2; index >= 0; index--) {\n expression = {\n $ifNull: [this.normalizeFieldReference(values[index]), expression],\n };\n }\n\n return expression;\n }\n\n /**\n * Build a $project stage from select operations.\n *\n * @param operations - The select operations\n * @returns The $project stage or null\n */\n private buildProjectStage(operations: Operation[]): any {\n if (operations.length === 0) {\n return null;\n }\n\n const projection: Record<string, unknown> = {};\n const driverCallbacks: Array<(projection: Record<string, unknown>) => void> = [];\n\n for (const op of operations) {\n switch (op.type) {\n case \"select\":\n // Handle new projection format with aliases\n if (op.data.projection) {\n this.applyProjectionObject(projection, op.data.projection);\n } else if (op.data.fields) {\n this.applyProjectionFields(projection, op.data.fields, 1);\n }\n break;\n\n case \"deselect\":\n this.applyProjectionFields(projection, op.data.fields, 0);\n break;\n\n case \"addSelect\":\n this.applyProjectionFields(projection, op.data.fields, 1);\n break;\n\n case \"selectRaw\":\n this.applyRawProjection(projection, op.data.expression, op.data.bindings);\n break;\n\n case \"selectSub\":\n case \"addSelectSub\": {\n const expr = this.resolveProjectionExpression(op.data.expression, op.data.bindings);\n if (expr !== undefined) {\n projection[op.data.alias] = expr;\n }\n break;\n }\n\n case \"selectAggregate\":\n projection[op.data.alias] = this.buildAggregateProjection(\n op.data.field,\n op.data.aggregate,\n );\n break;\n\n case \"selectExists\":\n projection[op.data.alias] = this.buildExistsProjection(op.data.field);\n break;\n\n case \"selectCount\":\n projection[op.data.alias] = this.buildArraySizeExpression(op.data.field);\n break;\n\n case \"selectCase\":\n projection[op.data.alias] = this.buildCaseExpression(\n op.data.cases,\n op.data.otherwise,\n );\n break;\n\n case \"selectWhen\":\n projection[op.data.alias] = this.buildCondExpression(\n op.data.condition,\n op.data.thenValue,\n op.data.elseValue,\n );\n break;\n\n case \"selectDriverProjection\":\n driverCallbacks.push(op.data.callback);\n break;\n\n case \"selectJson\": {\n const alias = op.data.alias ?? this.inferJsonAlias(op.data.path);\n projection[alias] = this.normalizeFieldReference(\n `$${this.normalizePath(op.data.path)}`,\n );\n break;\n }\n\n case \"selectJsonRaw\": {\n projection[op.data.alias] = this.resolveProjectionExpression(op.data.expression);\n break;\n }\n\n case \"deselectJson\":\n projection[this.normalizePath(op.data.path)] = 0;\n break;\n\n case \"selectConcat\":\n projection[op.data.alias] = this.buildConcatExpression(op.data.fields);\n break;\n\n case \"selectCoalesce\":\n projection[op.data.alias] = this.buildCoalesceExpression(op.data.fields);\n break;\n\n default:\n break;\n }\n }\n\n for (const callback of driverCallbacks) {\n callback(projection);\n }\n\n return Object.keys(projection).length > 0 ? { $project: projection } : null;\n }\n\n /**\n * Build a $sort stage from order operations.\n *\n * @param operations - The order operations\n * @returns The $sort stage or null\n */\n private buildSortStage(operations: Operation[]): any {\n const sort: any = {};\n\n for (const op of operations) {\n switch (op.type) {\n case \"orderBy\":\n sort[op.data.field] = op.data.direction === \"asc\" ? 1 : -1;\n break;\n\n case \"orderByRandom\":\n return { $sample: { size: op.data.limit } };\n\n case \"orderByRaw\":\n // TODO: Handle raw expressions\n break;\n }\n }\n\n return Object.keys(sort).length > 0 ? { $sort: sort } : null;\n }\n\n /**\n * Build a $group stage from group operations.\n *\n * @param operations - The group operations\n * @returns The $group stage or null\n */\n private buildGroupStage(operations: Operation[]): any {\n const op = operations[0];\n\n switch (op.type) {\n case \"groupBy\": {\n const stage = this.buildGroupByStage(op.data.fields);\n if (stage) {\n return stage;\n }\n break;\n }\n case \"groupByWithAggregates\": {\n const stage = this.buildGroupByWithAggregatesStage(\n op.data.fields,\n op.data.aggregates,\n );\n if (stage) {\n return stage;\n }\n break;\n }\n case \"groupByDate\": {\n const stage = this.buildGroupByDateStage(\n op.data.column,\n op.data.unit,\n op.data.aggregates ?? {},\n );\n if (stage) {\n return stage;\n }\n break;\n }\n case \"groupByRaw\": {\n const expression = op.data.expression;\n if (expression && typeof expression === \"object\") {\n return { $group: expression };\n }\n // If expression is not an object, it might be a string or other type\n // In that case, we should still return it as a $group stage\n if (expression) {\n return { $group: { _id: expression } };\n }\n break;\n }\n case \"distinct\": {\n const stage = this.buildGroupByStage(op.data.fields);\n if (stage) {\n return stage;\n }\n break;\n }\n default:\n break;\n }\n\n return null;\n }\n\n private buildGroupByStage(fields: GroupByInput): any {\n const groupId = this.buildGroupId(fields);\n if (!groupId) {\n return null;\n }\n\n return { $group: { _id: groupId } };\n }\n\n /**\n * Build a $group stage with aggregates from group operations.\n *\n * @param fields - Fields to group by\n * @param aggregates - Aggregate operations (abstract or raw)\n * @returns The $group stage or null\n */\n private buildGroupByWithAggregatesStage(\n fields: GroupByInput,\n aggregates: Record<string, RawExpression>,\n ): any {\n const groupId = this.buildGroupId(fields);\n if (!groupId) {\n return null;\n }\n\n const groupStage: Record<string, unknown> = {\n _id: groupId,\n };\n\n // Translate each aggregate expression\n for (const [alias, expression] of Object.entries(aggregates)) {\n if (isAggregateExpression(expression)) {\n // Translate abstract expression to MongoDB format\n groupStage[alias] = this.translateAggregateExpression(expression);\n } else {\n // Use raw expression as-is (already in MongoDB format)\n groupStage[alias] = expression;\n }\n }\n\n return { $group: groupStage };\n }\n\n /**\n * Build a `$group` stage that buckets documents by a `$dateTrunc` of a date\n * field, optionally running aggregates over each bucket.\n *\n * @param column - The date field to bucket\n * @param unit - The bucket granularity\n * @param aggregates - Aggregate operations (abstract or raw)\n * @returns The `$group` stage\n */\n private buildGroupByDateStage(\n column: string,\n unit: string,\n aggregates: Record<string, RawExpression>,\n ): any {\n const groupStage: Record<string, unknown> = {\n _id: { $dateTrunc: { date: `$${column}`, unit } },\n };\n\n for (const [alias, expression] of Object.entries(aggregates)) {\n if (isAggregateExpression(expression)) {\n groupStage[alias] = this.translateAggregateExpression(expression);\n } else {\n groupStage[alias] = expression;\n }\n }\n\n return { $group: groupStage };\n }\n\n /**\n * Extract field names from GroupByInput for renaming _id.\n *\n * @param fields - The grouping fields\n * @returns Field name(s) to use for renaming _id\n */\n private extractGroupFieldNames(fields: GroupByInput): string | string[] | null {\n if (typeof fields === \"string\") {\n return fields;\n }\n\n if (Array.isArray(fields)) {\n const allStrings = fields.every((field) => typeof field === \"string\");\n if (allStrings) {\n return fields as string[];\n }\n // For complex arrays, return null (don't rename)\n return null;\n }\n\n if (typeof fields === \"object\" && fields !== null) {\n // For object syntax, use the keys as field names\n return Object.keys(fields);\n }\n\n return null;\n }\n\n /**\n * Translate an abstract aggregate expression to MongoDB format.\n *\n * @param expr - Abstract aggregate expression\n * @returns MongoDB aggregation expression\n */\n private translateAggregateExpression(expr: AggregateExpression): Record<string, unknown> {\n switch (expr.__agg) {\n case \"count\":\n return { $sum: 1 };\n\n case \"countDistinct\":\n if (!expr.__field) {\n throw new Error(\"Count distinct aggregate requires a field name\");\n }\n // Accumulate the set of distinct values in the $group stage; the\n // renaming $project then finalizes it with `{ $size: \"$alias\" }`\n // (the standard distinct-count-per-group pattern — `$size` is not a\n // valid $group accumulator).\n return { $addToSet: `$${expr.__field}` };\n\n case \"sum\":\n // When a composed column expression is present, sum operates on it\n // (e.g. SUM(price * quantity) → { $sum: { $multiply: [...] } }) instead\n // of a bare field. This is the only aggregate that accepts `__expr`.\n if (expr.__expr) {\n return { $sum: this.columnExpressionToMongo(expr.__expr) };\n }\n if (!expr.__field) {\n throw new Error(\"Sum aggregate requires a field name\");\n }\n return { $sum: `$${expr.__field}` };\n\n case \"avg\":\n if (!expr.__field) {\n throw new Error(\"Average aggregate requires a field name\");\n }\n return { $avg: `$${expr.__field}` };\n\n case \"min\":\n if (!expr.__field) {\n throw new Error(\"Min aggregate requires a field name\");\n }\n return { $min: `$${expr.__field}` };\n\n case \"max\":\n if (!expr.__field) {\n throw new Error(\"Max aggregate requires a field name\");\n }\n return { $max: `$${expr.__field}` };\n\n case \"first\":\n if (!expr.__field) {\n throw new Error(\"First aggregate requires a field name\");\n }\n return { $first: `$${expr.__field}` };\n\n case \"last\":\n if (!expr.__field) {\n throw new Error(\"Last aggregate requires a field name\");\n }\n return { $last: `$${expr.__field}` };\n\n case \"distinct\":\n if (!expr.__field) {\n throw new Error(\"Distinct aggregate requires a field name\");\n }\n return { $distinct: `$${expr.__field}` };\n\n case \"floor\":\n if (!expr.__field) {\n throw new Error(\"Floor aggregate requires a field name\");\n }\n\n return { $floor: `$${expr.__field}` };\n\n default:\n throw new Error(`Unknown aggregate function: ${expr.__agg}`);\n }\n }\n\n /**\n * Compile a typed {@link ColumnExpression} tree into a MongoDB aggregation\n * expression.\n *\n * Column references become `$field` paths; literals are emitted verbatim;\n * arithmetic ops map to `$add` / `$subtract` / `$multiply` / `$divide`. The\n * `raw` node is rejected — a raw SQL fragment is not portable to a MongoDB\n * pipeline, so callers must use the typed combinators (or `groupByRaw`) here.\n *\n * @param expression - The expression tree to compile\n * @returns A MongoDB aggregation expression (e.g. `{ $multiply: [\"$price\", \"$quantity\"] }`)\n */\n private columnExpressionToMongo(expression: ColumnExpression): unknown {\n switch (expression.__expr) {\n case \"column\":\n return `$${expression.column}`;\n\n case \"literal\":\n return expression.value;\n\n case \"raw\":\n throw new Error(\n `$agg.sumRaw / $expr.raw is not portable to a MongoDB pipeline — a raw ` +\n `SQL fragment has no MongoDB equivalent. Use the typed $expr ` +\n `combinators ($expr.mul / $expr.add / $expr.sub / $expr.div / $expr.col / $expr.lit) or groupByRaw instead.`,\n );\n\n case \"add\":\n case \"subtract\":\n case \"multiply\":\n case \"divide\": {\n const operator = {\n add: \"$add\",\n subtract: \"$subtract\",\n multiply: \"$multiply\",\n divide: \"$divide\",\n }[expression.__expr];\n\n return {\n [operator]: expression.operands.map((operand) => this.columnExpressionToMongo(operand)),\n };\n }\n\n default:\n throw new Error(`Unsupported column expression node: ${JSON.stringify(expression)}`);\n }\n }\n\n private buildGroupId(fields: GroupByInput): any {\n if (!fields) {\n return null;\n }\n\n if (typeof fields === \"string\") {\n return `$${fields}`;\n }\n\n if (Array.isArray(fields)) {\n if (fields.length === 0) {\n return null;\n }\n\n const allStrings = fields.every((field) => typeof field === \"string\");\n if (allStrings) {\n const result: Record<string, string> = {};\n for (const field of fields as string[]) {\n result[field] = `$${field}`;\n }\n return result;\n }\n\n // Array of objects - merge them to build complex _id structures\n return (fields as Record<string, unknown>[]).reduce((acc, item) => ({ ...acc, ...item }), {});\n }\n\n if (typeof fields === \"object\") {\n const normalized: Record<string, unknown> = {};\n Object.entries(fields).forEach(([key, value]) => {\n if (typeof value === \"string\" && !value.startsWith(\"$\")) {\n normalized[key] = `$${value}`;\n } else {\n normalized[key] = value;\n }\n });\n return normalized;\n }\n\n return null;\n }\n\n /**\n * Build a $lookup stage from join operations.\n *\n * @param operations - The join operations\n * @returns The $lookup stage or null\n */\n private buildLookupStage(operations: Operation[]): any {\n const op = operations[0];\n const options = op.data;\n\n return {\n $lookup: {\n from: options.table,\n localField: options.localField,\n foreignField: options.foreignField,\n as: options.alias || options.table,\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,IAAa,mBAAb,MAA8B;;;;CAI5B,AAAiB;;;;CAKjB,AAAiB;;;;CAKjB,AAAiB;;;;;CAMjB,AAAiB,kCAAkB,IAAI,IAA+B;;;;;;;CAQtE,AAAiB,uCAAuB,IAAI,IAAyB;;;;;;CAOrE,AAAO,YAAY,SAAkC;EACnD,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAAa,QAAQ;EAC1B,KAAK,mBAAmB,QAAQ;CAClC;;;;;;;;;;;;;;;;;;;;;CAsBA,AAAO,QAAe;EACpB,MAAM,WAAkB,CAAC;EACzB,IAAI,eAAqC;EACzC,IAAI,gBAA6B,CAAC;EAElC,KAAK,MAAM,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GACL,KAAK,UAQH,OAAO,GAPU;IACf,KAAK;IACL,UAAU;IACV,UAAU;IACV,QAAQ;GACV,EAAE,WAAW,UAGC,WAAW,SAAS,KAAK,YAAY,KAAK,wBAAwB,OAAO,CAAC,EACxF;GAGF,SACE,MAAM,IAAI,MAAM,uCAAuC,KAAK,UAAU,UAAU,GAAG;EACvF;CACF;CAEA,AAAQ,aAAa,QAA2B;EAC9C,IAAI,CAAC,QACH,OAAO;EAGT,IAAI,OAAO,WAAW,UACpB,OAAO,IAAI;EAGb,IAAI,MAAM,QAAQ,MAAM,GAAG;GACzB,IAAI,OAAO,WAAW,GACpB,OAAO;GAIT,IADmB,OAAO,OAAO,UAAU,OAAO,UAAU,QAC/C,GAAG;IACd,MAAM,SAAiC,CAAC;IACxC,KAAK,MAAM,SAAS,QAClB,OAAO,SAAS,IAAI;IAEtB,OAAO;GACT;GAGA,OAAQ,OAAqC,QAAQ,KAAK,UAAU;IAAE,GAAG;IAAK,GAAG;GAAK,IAAI,CAAC,CAAC;EAC9F;EAEA,IAAI,OAAO,WAAW,UAAU;GAC9B,MAAM,aAAsC,CAAC;GAC7C,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;IAC/C,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,WAAW,GAAG,GACpD,WAAW,OAAO,IAAI;SAEtB,WAAW,OAAO;GAEtB,CAAC;GACD,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;CAQA,AAAQ,iBAAiB,YAA8B;EAErD,MAAM,UADK,WAAW,EACJ,CAAC;EAEnB,OAAO,EACL,SAAS;GACP,MAAM,QAAQ;GACd,YAAY,QAAQ;GACpB,cAAc,QAAQ;GACtB,IAAI,QAAQ,SAAS,QAAQ;EAC/B,EACF;CACF;AACF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ColumnExpression } from "../../expressions/column-expressions.mjs";
|
|
1
2
|
import { AggregateExpression } from "../../expressions/aggregate-expressions.mjs";
|
|
2
3
|
import { SqlDialectContract } from "../sql/sql-dialect.contract.mjs";
|
|
3
4
|
|
|
@@ -129,15 +130,42 @@ declare class PostgresDialect implements SqlDialectContract {
|
|
|
129
130
|
/**
|
|
130
131
|
* Translate a database-agnostic aggregate expression to PostgreSQL SQL.
|
|
131
132
|
*
|
|
132
|
-
* The
|
|
133
|
-
* `floor`, `first` and `last` are
|
|
134
|
-
* single-scalar `GROUP BY` equivalent on
|
|
135
|
-
* of emitting a silently-different semantic
|
|
133
|
+
* The scalar aggregates map to their ANSI SQL function, and `countDistinct`
|
|
134
|
+
* maps to `COUNT(DISTINCT …)`. `distinct`, `floor`, `first` and `last` are
|
|
135
|
+
* MongoDB-only for v1 — none has a single-scalar `GROUP BY` equivalent on
|
|
136
|
+
* PostgreSQL, so they throw instead of emitting a silently-different semantic
|
|
137
|
+
* (the footgun this guards).
|
|
136
138
|
*
|
|
137
139
|
* @param expression - The abstract aggregate (`$agg.*`) to translate
|
|
138
140
|
* @returns The SQL fragment (e.g. `SUM("amount")`, `COUNT(*)`)
|
|
139
141
|
*/
|
|
140
142
|
aggregateToSql(expression: AggregateExpression): string;
|
|
143
|
+
/**
|
|
144
|
+
* Compile a typed {@link ColumnExpression} tree into a SQL fragment.
|
|
145
|
+
*
|
|
146
|
+
* Column references flow through {@link quoteIdentifier} (so user-supplied
|
|
147
|
+
* names are quoted/escaped, never raw-interpolated); literals are emitted as
|
|
148
|
+
* numeric/boolean SQL constants; arithmetic ops are parenthesised. The `raw`
|
|
149
|
+
* node is the only path that emits a string verbatim — it is opt-in by name.
|
|
150
|
+
*
|
|
151
|
+
* @param expression - The expression tree to compile
|
|
152
|
+
* @returns A SQL fragment (e.g. `("price" * "quantity")`)
|
|
153
|
+
*/
|
|
154
|
+
columnExpressionToSql(expression: ColumnExpression): string;
|
|
155
|
+
/**
|
|
156
|
+
* Build a `date_trunc` bucket expression for a portable `groupByDate`.
|
|
157
|
+
*
|
|
158
|
+
* @param column - The date/timestamp column to truncate
|
|
159
|
+
* @param unit - The bucket granularity
|
|
160
|
+
* @returns The SQL fragment (e.g. `date_trunc('month', "created_at")`)
|
|
161
|
+
*
|
|
162
|
+
* @example
|
|
163
|
+
* ```typescript
|
|
164
|
+
* dialect.dateTruncSql("created_at", "month");
|
|
165
|
+
* // date_trunc('month', "created_at")
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
dateTruncSql(column: string, unit: "day" | "week" | "month" | "year"): string;
|
|
141
169
|
}
|
|
142
170
|
//#endregion
|
|
143
171
|
export { PostgresDialect };
|