@warlock.js/cascade 4.6.0 → 4.7.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 +28 -0
- package/cjs/index.cjs +372 -56
- package/cjs/index.cjs.map +1 -1
- package/esm/contracts/database-driver.contract.d.mts +8 -0
- package/esm/contracts/database-driver.contract.d.mts.map +1 -1
- package/esm/contracts/index.d.mts +1 -1
- package/esm/contracts/query-builder.contract.d.mts +36 -1
- package/esm/contracts/query-builder.contract.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.d.mts +5 -0
- package/esm/drivers/mongodb/mongodb-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.mjs +10 -4
- package/esm/drivers/mongodb/mongodb-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.d.mts +4 -0
- package/esm/drivers/mongodb/mongodb-migration-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.mjs +5 -2
- package/esm/drivers/mongodb/mongodb-migration-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts +15 -0
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.mjs +24 -0
- package/esm/drivers/mongodb/mongodb-query-builder.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts +16 -0
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs +33 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-driver.d.mts +69 -13
- package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-driver.mjs +155 -27
- package/esm/drivers/postgres/postgres-driver.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.d.mts +14 -3
- package/esm/drivers/postgres/postgres-query-builder.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.mjs +44 -8
- package/esm/drivers/postgres/postgres-query-builder.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts +6 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.mjs +13 -0
- package/esm/drivers/postgres/postgres-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-sql-serializer.mjs +15 -4
- package/esm/drivers/postgres/postgres-sql-serializer.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/migration/migration-runner.d.mts.map +1 -1
- package/esm/migration/migration-runner.mjs +25 -3
- package/esm/migration/migration-runner.mjs.map +1 -1
- package/esm/migration/migration.d.mts +6 -3
- package/esm/migration/migration.d.mts.map +1 -1
- package/esm/migration/migration.mjs +6 -3
- package/esm/migration/migration.mjs.map +1 -1
- package/esm/model/methods/scope-methods.mjs +18 -4
- package/esm/model/methods/scope-methods.mjs.map +1 -1
- package/esm/model/model.d.mts +6 -0
- package/esm/model/model.d.mts.map +1 -1
- package/esm/model/model.mjs +6 -0
- package/esm/model/model.mjs.map +1 -1
- package/esm/query-builder/query-builder.d.mts +12 -1
- package/esm/query-builder/query-builder.d.mts.map +1 -1
- package/esm/query-builder/query-builder.mjs +19 -0
- package/esm/query-builder/query-builder.mjs.map +1 -1
- package/llms-full.txt +41 -7
- package/llms.txt +1 -1
- package/package.json +4 -4
- package/skills/README.md +1 -1
- package/skills/manage-transactions/SKILL.md +41 -7
|
@@ -69,7 +69,7 @@ var MongoQueryParser = class {
|
|
|
69
69
|
const pipeline = [];
|
|
70
70
|
let currentStage = null;
|
|
71
71
|
let currentBuffer = [];
|
|
72
|
-
for (const op of this.operations) if (op.mergeable && op.stage === currentStage) currentBuffer.push(op);
|
|
72
|
+
for (const op of this.orderStages(this.operations)) if (op.mergeable && op.stage === currentStage) currentBuffer.push(op);
|
|
73
73
|
else {
|
|
74
74
|
if (currentBuffer.length > 0) {
|
|
75
75
|
const builtStage = this.buildStage(currentStage, currentBuffer);
|
|
@@ -104,6 +104,38 @@ var MongoQueryParser = class {
|
|
|
104
104
|
return this.postProcessGroupStages(pipeline);
|
|
105
105
|
}
|
|
106
106
|
/**
|
|
107
|
+
* Reorder operations so filters run before projections, mirroring SQL
|
|
108
|
+
* semantics: in `select(...).where(...)`, the WHERE always applies to the
|
|
109
|
+
* source columns regardless of call order. Without this, a `$project` that
|
|
110
|
+
* strips the filter column would run before the `$match` and silently drop
|
|
111
|
+
* every document (`select(["a"]).where("b", x)` → `[]`).
|
|
112
|
+
*
|
|
113
|
+
* Only *mergeable* `$match` operations are hoisted, and only within a
|
|
114
|
+
* segment of neighboring mergeable `$match` / `$project` / `$sort`
|
|
115
|
+
* operations. Any other operation — `$group`, `$lookup`, `$limit`, `$skip`,
|
|
116
|
+
* `$setWindowFields`, or a non-mergeable op (raw escapes, having-style
|
|
117
|
+
* post-group matches, `$sample`) — is a barrier: nothing moves across it.
|
|
118
|
+
* So `groupBy(...).where(...)` still filters AFTER the group, and
|
|
119
|
+
* `limit(...)` / `random()` keep their call-order meaning.
|
|
120
|
+
*/
|
|
121
|
+
orderStages(operations) {
|
|
122
|
+
const reordered = [];
|
|
123
|
+
let segment = [];
|
|
124
|
+
const flushSegment = () => {
|
|
125
|
+
if (segment.length === 0) return;
|
|
126
|
+
reordered.push(...segment.filter((op) => op.stage === "$match"));
|
|
127
|
+
reordered.push(...segment.filter((op) => op.stage !== "$match"));
|
|
128
|
+
segment = [];
|
|
129
|
+
};
|
|
130
|
+
for (const op of operations) if (op.mergeable && (op.stage === "$match" || op.stage === "$project" || op.stage === "$sort")) segment.push(op);
|
|
131
|
+
else {
|
|
132
|
+
flushSegment();
|
|
133
|
+
reordered.push(op);
|
|
134
|
+
}
|
|
135
|
+
flushSegment();
|
|
136
|
+
return reordered;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
107
139
|
* Track field names for group stages that need _id renaming.
|
|
108
140
|
*/
|
|
109
141
|
trackGroupFieldNames(stage, operations, stageIndex) {
|
|
@@ -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 { 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"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,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.orderStages(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 * Reorder operations so filters run before projections, mirroring SQL\n * semantics: in `select(...).where(...)`, the WHERE always applies to the\n * source columns regardless of call order. Without this, a `$project` that\n * strips the filter column would run before the `$match` and silently drop\n * every document (`select([\"a\"]).where(\"b\", x)` → `[]`).\n *\n * Only *mergeable* `$match` operations are hoisted, and only within a\n * segment of neighboring mergeable `$match` / `$project` / `$sort`\n * operations. Any other operation — `$group`, `$lookup`, `$limit`, `$skip`,\n * `$setWindowFields`, or a non-mergeable op (raw escapes, having-style\n * post-group matches, `$sample`) — is a barrier: nothing moves across it.\n * So `groupBy(...).where(...)` still filters AFTER the group, and\n * `limit(...)` / `random()` keep their call-order meaning.\n */\n private orderStages(operations: Operation[]): Operation[] {\n const reordered: Operation[] = [];\n let segment: Operation[] = [];\n\n const flushSegment = (): void => {\n if (segment.length === 0) {\n return;\n }\n reordered.push(...segment.filter((op) => op.stage === \"$match\"));\n reordered.push(...segment.filter((op) => op.stage !== \"$match\"));\n segment = [];\n };\n\n for (const op of operations) {\n const isReorderable =\n op.mergeable &&\n (op.stage === \"$match\" || op.stage === \"$project\" || op.stage === \"$sort\");\n\n if (isReorderable) {\n segment.push(op);\n } else {\n flushSegment();\n reordered.push(op);\n }\n }\n\n flushSegment();\n return reordered;\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,AAA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,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"}
|
|
@@ -90,12 +90,21 @@ declare class PostgresDriver implements DriverContract {
|
|
|
90
90
|
*/
|
|
91
91
|
private _syncAdapter;
|
|
92
92
|
/**
|
|
93
|
-
*
|
|
94
|
-
* (`JSONB[]`, `TEXT[]`, …) and must NOT be JSON-text
|
|
93
|
+
* Explicit, table-agnostic override list of column names that hold native
|
|
94
|
+
* PostgreSQL arrays (`JSONB[]`, `TEXT[]`, …) and must NOT be JSON-text
|
|
95
|
+
* encoded. Merged with (and superseded per-table by) the schema
|
|
96
|
+
* introspection below; kept as a manual escape hatch.
|
|
95
97
|
*
|
|
96
98
|
* @see PostgresPoolConfig.nativeArrayColumns
|
|
97
99
|
*/
|
|
98
100
|
private readonly _nativeArrayColumns;
|
|
101
|
+
/**
|
|
102
|
+
* Native-array columns discovered by introspecting the live schema on
|
|
103
|
+
* connect, keyed `table → { column, … }`. Authoritative and table-scoped, so
|
|
104
|
+
* a column that is `TEXT[]` in one table and `jsonb` in another is encoded
|
|
105
|
+
* correctly for each — no app configuration required.
|
|
106
|
+
*/
|
|
107
|
+
private _introspectedArrayColumns;
|
|
99
108
|
/**
|
|
100
109
|
* Create a new PostgreSQL driver instance.
|
|
101
110
|
*
|
|
@@ -148,9 +157,11 @@ declare class PostgresDriver implements DriverContract {
|
|
|
148
157
|
* that need special handling for PostgreSQL storage.
|
|
149
158
|
*
|
|
150
159
|
* @param data - The data object to serialize
|
|
160
|
+
* @param table - Optional table name; when given, columns introspected as
|
|
161
|
+
* native arrays on that table are bound raw (see {@link serializeValue}).
|
|
151
162
|
* @returns Serialized data ready for PostgreSQL
|
|
152
163
|
*/
|
|
153
|
-
serialize(data: Record<string, unknown
|
|
164
|
+
serialize(data: Record<string, unknown>, table?: string): Record<string, unknown>;
|
|
154
165
|
/**
|
|
155
166
|
* Serialize a single column value into a node-pg bindable parameter.
|
|
156
167
|
*
|
|
@@ -167,25 +178,54 @@ declare class PostgresDriver implements DriverContract {
|
|
|
167
178
|
* `JSON.stringify`. node-pg renders a raw JS array as a PostgreSQL array
|
|
168
179
|
* literal `{...}` (and `[]` as `{}`), which a `json` / `jsonb` column
|
|
169
180
|
* rejects — so we bind the value as JSON text instead, the form those
|
|
170
|
-
* columns accept. Columns
|
|
171
|
-
*
|
|
172
|
-
*
|
|
181
|
+
* columns accept. Columns known to be native arrays — via schema
|
|
182
|
+
* introspection or the `nativeArrayColumns` config — are exempt: their raw
|
|
183
|
+
* array is passed through so node-pg emits the `{...}` literal a genuine
|
|
184
|
+
* `JSONB[]` / `TEXT[]` column needs.
|
|
173
185
|
* - plain object → `JSON.stringify`. Equivalent to node-pg's own object
|
|
174
186
|
* handling, made explicit so both write paths agree.
|
|
175
187
|
* - everything else (scalars: string, number, boolean, null) → untouched.
|
|
176
188
|
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
189
|
+
* Distinguishing native-array from `json` / `jsonb` columns: a value alone
|
|
190
|
+
* can't tell them apart, so the driver introspects the live schema on connect
|
|
191
|
+
* (see {@link loadNativeArrayColumns}) and consults that per-table map here
|
|
192
|
+
* via {@link isNativeArrayColumn}. The explicit `nativeArrayColumns` config
|
|
193
|
+
* still works as a table-agnostic override. No `::jsonb` placeholder cast is
|
|
194
|
+
* added: a JSON-text string binds correctly to `json` / `jsonb` without one,
|
|
195
|
+
* and a blind cast would misfire on columns we cannot positively identify as
|
|
196
|
+
* jsonb.
|
|
183
197
|
*
|
|
184
|
-
* @param key - Column name (used to
|
|
198
|
+
* @param key - Column name (used to resolve native-array columns)
|
|
185
199
|
* @param value - The raw value to serialize (never `undefined`)
|
|
200
|
+
* @param table - Optional table name; enables the per-table native-array lookup
|
|
186
201
|
* @returns The value ready to bind as a query parameter
|
|
187
202
|
*/
|
|
188
203
|
private serializeValue;
|
|
204
|
+
/**
|
|
205
|
+
* Whether `column` on `table` is a native PostgreSQL array. True when the
|
|
206
|
+
* connect-time schema introspection saw it as `data_type = 'ARRAY'` for that
|
|
207
|
+
* table (authoritative, per-table), or when it's listed in the table-agnostic
|
|
208
|
+
* `nativeArrayColumns` config override.
|
|
209
|
+
*/
|
|
210
|
+
private isNativeArrayColumn;
|
|
211
|
+
/**
|
|
212
|
+
* Introspect the live schema for native-array columns so array values bind
|
|
213
|
+
* correctly with zero app configuration.
|
|
214
|
+
*
|
|
215
|
+
* A JS array must be bound two opposite ways depending on the column: as JSON
|
|
216
|
+
* text for a `json` / `jsonb` column, but as a raw array (which node-pg
|
|
217
|
+
* renders `{...}`) for a native `TEXT[]` / `JSONB[]` / `INTEGER[]` column. The
|
|
218
|
+
* serializer sees values, not types, so without this it JSON-stringifies
|
|
219
|
+
* every array — which a native-array column rejects with "malformed array
|
|
220
|
+
* literal". One `information_schema` query at connect, cached for the
|
|
221
|
+
* connection lifetime, removes the need to hand-list `nativeArrayColumns`.
|
|
222
|
+
*
|
|
223
|
+
* Best-effort: any failure (e.g. restricted catalog access) is logged and
|
|
224
|
+
* leaves the map empty so the config override still applies — it never blocks
|
|
225
|
+
* connect. A schema change made within a live connection isn't reflected
|
|
226
|
+
* until the next connect.
|
|
227
|
+
*/
|
|
228
|
+
private loadNativeArrayColumns;
|
|
189
229
|
/**
|
|
190
230
|
* Get the dirty tracker for this driver.
|
|
191
231
|
*/
|
|
@@ -348,6 +388,9 @@ declare class PostgresDriver implements DriverContract {
|
|
|
348
388
|
* Perform an atomic update operation.
|
|
349
389
|
*
|
|
350
390
|
* Builds and executes an UPDATE query for the given filter and operations.
|
|
391
|
+
* Updates EVERY matching row — the MongoDB driver's atomic() delegates to
|
|
392
|
+
* updateMany, and Model.findAndUpdate documents multi-row semantics, so the
|
|
393
|
+
* two drivers must agree.
|
|
351
394
|
*
|
|
352
395
|
* @param table - Target table name
|
|
353
396
|
* @param filter - Filter conditions
|
|
@@ -393,11 +436,24 @@ declare class PostgresDriver implements DriverContract {
|
|
|
393
436
|
/**
|
|
394
437
|
* Build a simple WHERE clause from a filter object.
|
|
395
438
|
*
|
|
439
|
+
* Values are bound as plain equality, except Mongo-style operator objects
|
|
440
|
+
* (`{ $in: [...] }`, `{ $gt: 5 }`, ...) which are translated to their SQL
|
|
441
|
+
* equivalents — driver-level callers (e.g. pivot detach) build filters in
|
|
442
|
+
* that portable form. An unrecognized `$` operator throws instead of being
|
|
443
|
+
* bound literally, which would only surface as a cryptic type error from
|
|
444
|
+
* Postgres.
|
|
445
|
+
*
|
|
396
446
|
* @param filter - Filter conditions
|
|
397
447
|
* @param startParamIndex - Starting parameter index
|
|
398
448
|
* @returns Object with WHERE clause string and parameters
|
|
399
449
|
*/
|
|
400
450
|
private buildWhereClause;
|
|
451
|
+
/**
|
|
452
|
+
* A filter value is an operator object when it is a plain object whose keys
|
|
453
|
+
* ALL start with `$`. Arrays, Dates, and value objects (e.g. jsonb equality
|
|
454
|
+
* payloads) keep their existing bind-as-value behavior.
|
|
455
|
+
*/
|
|
456
|
+
private isOperatorFilter;
|
|
401
457
|
/**
|
|
402
458
|
* Build an UPDATE query from update operations.
|
|
403
459
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-driver.d.mts","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/postgres/postgres-driver.ts"],"mappings":";;;;;;;;;;;;;AAgD2C;AA0D3C;;AA1D2C,KADtC,MAAA,gBAAsB,IAAI;AAAA,KAC1B,YAAA,gBAA4B,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0D9B,cAAA,YAA0B,cAAA;EAAA,
|
|
1
|
+
{"version":3,"file":"postgres-driver.d.mts","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/postgres/postgres-driver.ts"],"mappings":";;;;;;;;;;;;;AAgD2C;AA0D3C;;AA1D2C,KADtC,MAAA,gBAAsB,IAAI;AAAA,KAC1B,YAAA,gBAA4B,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0D9B,cAAA,YAA0B,cAAA;EAAA,iBAoFD,MAAA;EAqf1B;;;EAAA,SArkBM,IAAA,EAAqB,cAAA;EA0lB3B;;;EAAA,SArlBM,OAAA,EAAO,eAAA;EAwlBpB;;;;;;;;;EAAA,SA7kBa,aAAA,EAAe,OAAA,CAAQ,aAAA;EA2oBpC;;;EAAA,QA7nBK,KAAA;EA4rBL;;;EAAA,iBAvrBc,eAAA;EAquBN;;;EAAA,QAhuBH,YAAA;EAowB8D;;;EAAA,QA/vB9D,UAAA;EA+wBG;;;EAAA,QA1wBH,gBAAA;EAmzB2B;;;EAAA,QA9yB3B,YAAA;EAk3BE;;;;;;;;EAAA,iBAx2BO,mBAAA;EAk6Bc;;;;;;EAAA,QA15BvB,yBAAA;EA8vCmC;;;;;cAvvCP,MAAA,EAAQ,kBAAA;EApFO;;;;;EAAA,IA6FxC,IAAA,IAAQ,MAAA;EApFH;;;EA8FT,SAAA,UAAmB,MAAA,KAAW,MAAA;EAnFE;;;EAAA,IA0F5B,WAAA;EA7DH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