@warlock.js/cascade 4.8.2 → 4.9.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 +7 -0
- package/cjs/index.cjs +160 -124
- package/cjs/index.cjs.map +1 -1
- package/esm/context/database-data-source-context.d.mts +1 -1
- package/esm/context/database-data-source-context.d.mts.map +1 -1
- package/esm/context/database-data-source-context.mjs +1 -1
- package/esm/context/database-data-source-context.mjs.map +1 -1
- package/esm/context/database-transaction-context.d.mts +1 -1
- package/esm/context/database-transaction-context.d.mts.map +1 -1
- package/esm/context/database-transaction-context.mjs +1 -1
- package/esm/context/database-transaction-context.mjs.map +1 -1
- package/esm/contracts/database-driver.contract.d.mts +1 -1
- package/esm/contracts/database-driver.contract.d.mts.map +1 -1
- package/esm/contracts/database-id-generator.contract.d.mts +1 -1
- package/esm/contracts/database-id-generator.contract.d.mts.map +1 -1
- package/esm/contracts/database-remover.contract.d.mts +1 -1
- package/esm/contracts/database-remover.contract.d.mts.map +1 -1
- package/esm/contracts/database-restorer.contract.d.mts +1 -1
- package/esm/contracts/database-restorer.contract.d.mts.map +1 -1
- package/esm/contracts/database-writer.contract.d.mts +1 -1
- package/esm/contracts/database-writer.contract.d.mts.map +1 -1
- package/esm/contracts/driver-blueprint.contract.d.mts +1 -1
- package/esm/contracts/driver-blueprint.contract.d.mts.map +1 -1
- package/esm/contracts/migration-driver.contract.d.mts +1 -1
- package/esm/contracts/migration-driver.contract.d.mts.map +1 -1
- package/esm/contracts/query-builder.contract.d.mts +1 -1
- package/esm/contracts/query-builder.contract.d.mts.map +1 -1
- package/esm/contracts/sync-adapter.contract.d.mts +1 -1
- package/esm/contracts/sync-adapter.contract.d.mts.map +1 -1
- package/esm/data-source/data-source-registry.d.mts +1 -1
- package/esm/data-source/data-source-registry.d.mts.map +1 -1
- package/esm/data-source/data-source-registry.mjs +1 -1
- package/esm/data-source/data-source-registry.mjs.map +1 -1
- package/esm/data-source/data-source.d.mts +1 -1
- package/esm/data-source/data-source.d.mts.map +1 -1
- package/esm/data-source/data-source.mjs +1 -1
- package/esm/data-source/data-source.mjs.map +1 -1
- package/esm/database-dirty-tracker.d.mts +1 -1
- package/esm/database-dirty-tracker.d.mts.map +1 -1
- package/esm/database-dirty-tracker.mjs +1 -1
- package/esm/database-dirty-tracker.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-blueprint.mjs +1 -1
- package/esm/drivers/mongodb/mongodb-blueprint.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.d.mts +1 -1
- package/esm/drivers/mongodb/mongodb-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.mjs +1 -1
- package/esm/drivers/mongodb/mongodb-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-id-generator.d.mts +1 -1
- package/esm/drivers/mongodb/mongodb-id-generator.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-id-generator.mjs +1 -1
- package/esm/drivers/mongodb/mongodb-id-generator.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.d.mts +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.mjs +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.mjs +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-operations.d.mts +1 -1
- package/esm/drivers/mongodb/mongodb-query-operations.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-operations.mjs +1 -1
- package/esm/drivers/mongodb/mongodb-query-operations.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-sync-adapter.d.mts +1 -1
- package/esm/drivers/mongodb/mongodb-sync-adapter.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-sync-adapter.mjs +1 -1
- package/esm/drivers/mongodb/mongodb-sync-adapter.mjs.map +1 -1
- package/esm/drivers/mongodb/types.d.mts +1 -1
- package/esm/drivers/mongodb/types.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-blueprint.d.mts +1 -1
- package/esm/drivers/postgres/postgres-blueprint.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-blueprint.mjs +1 -1
- package/esm/drivers/postgres/postgres-blueprint.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-dialect.d.mts +1 -1
- package/esm/drivers/postgres/postgres-dialect.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-dialect.mjs +1 -1
- package/esm/drivers/postgres/postgres-dialect.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-driver.d.mts +1 -1
- package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-driver.mjs +1 -1
- package/esm/drivers/postgres/postgres-driver.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-migration-driver.d.mts +1 -1
- package/esm/drivers/postgres/postgres-migration-driver.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-migration-driver.mjs +1 -1
- package/esm/drivers/postgres/postgres-migration-driver.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.d.mts +1 -1
- package/esm/drivers/postgres/postgres-query-builder.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.mjs +1 -1
- package/esm/drivers/postgres/postgres-query-builder.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts +1 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.mjs +1 -1
- package/esm/drivers/postgres/postgres-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-sql-serializer.mjs +1 -1
- package/esm/drivers/postgres/postgres-sql-serializer.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-sync-adapter.d.mts +1 -1
- package/esm/drivers/postgres/postgres-sync-adapter.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-sync-adapter.mjs +1 -1
- package/esm/drivers/postgres/postgres-sync-adapter.mjs.map +1 -1
- package/esm/drivers/postgres/types.d.mts +1 -1
- package/esm/drivers/postgres/types.d.mts.map +1 -1
- package/esm/drivers/sql/sql-dialect.contract.d.mts +1 -1
- package/esm/drivers/sql/sql-dialect.contract.d.mts.map +1 -1
- package/esm/drivers/sql/sql-types.d.mts +1 -1
- package/esm/drivers/sql/sql-types.d.mts.map +1 -1
- package/esm/errors/missing-data-source.error.d.mts +1 -1
- package/esm/errors/missing-data-source.error.d.mts.map +1 -1
- package/esm/errors/missing-data-source.error.mjs +1 -1
- package/esm/errors/missing-data-source.error.mjs.map +1 -1
- package/esm/errors/transaction-rollback.error.d.mts +1 -1
- package/esm/errors/transaction-rollback.error.d.mts.map +1 -1
- package/esm/errors/transaction-rollback.error.mjs +1 -1
- package/esm/errors/transaction-rollback.error.mjs.map +1 -1
- package/esm/events/model-events.d.mts +1 -1
- package/esm/events/model-events.d.mts.map +1 -1
- package/esm/events/model-events.mjs +1 -1
- package/esm/events/model-events.mjs.map +1 -1
- package/esm/expressions/aggregate-expressions.d.mts +1 -1
- package/esm/expressions/aggregate-expressions.d.mts.map +1 -1
- package/esm/expressions/aggregate-expressions.mjs +1 -1
- package/esm/expressions/aggregate-expressions.mjs.map +1 -1
- package/esm/expressions/column-expressions.d.mts +1 -1
- package/esm/expressions/column-expressions.d.mts.map +1 -1
- package/esm/expressions/column-expressions.mjs +1 -1
- package/esm/expressions/column-expressions.mjs.map +1 -1
- package/esm/migration/column-builder.d.mts +1 -1
- package/esm/migration/column-builder.d.mts.map +1 -1
- package/esm/migration/column-builder.mjs +1 -1
- package/esm/migration/column-builder.mjs.map +1 -1
- package/esm/migration/column-helpers.d.mts +1 -1
- package/esm/migration/column-helpers.d.mts.map +1 -1
- package/esm/migration/column-helpers.mjs +1 -1
- package/esm/migration/column-helpers.mjs.map +1 -1
- package/esm/migration/foreign-key-builder.d.mts +1 -1
- package/esm/migration/foreign-key-builder.d.mts.map +1 -1
- package/esm/migration/foreign-key-builder.mjs +1 -1
- package/esm/migration/foreign-key-builder.mjs.map +1 -1
- package/esm/migration/migration-runner.d.mts +1 -1
- package/esm/migration/migration-runner.d.mts.map +1 -1
- package/esm/migration/migration-runner.mjs +4 -40
- package/esm/migration/migration-runner.mjs.map +1 -1
- package/esm/migration/migration.d.mts +1 -1
- package/esm/migration/migration.d.mts.map +1 -1
- package/esm/migration/migration.mjs +1 -1
- package/esm/migration/migration.mjs.map +1 -1
- package/esm/migration/parse-created-at.mjs +67 -0
- package/esm/migration/parse-created-at.mjs.map +1 -0
- package/esm/migration/sql-grammar.mjs +16 -6
- package/esm/migration/sql-grammar.mjs.map +1 -1
- package/esm/migration/sql-serializer.d.mts +1 -1
- package/esm/migration/sql-serializer.d.mts.map +1 -1
- package/esm/migration/sql-serializer.mjs +1 -1
- package/esm/migration/sql-serializer.mjs.map +1 -1
- package/esm/migration/types.d.mts +1 -1
- package/esm/migration/types.d.mts.map +1 -1
- package/esm/model/methods/accessor-methods.mjs +1 -1
- package/esm/model/methods/accessor-methods.mjs.map +1 -1
- package/esm/model/methods/delete-methods.mjs +1 -1
- package/esm/model/methods/delete-methods.mjs.map +1 -1
- package/esm/model/methods/dirty-methods.mjs +1 -1
- package/esm/model/methods/dirty-methods.mjs.map +1 -1
- package/esm/model/methods/hydration-methods.mjs +1 -1
- package/esm/model/methods/hydration-methods.mjs.map +1 -1
- package/esm/model/methods/instance-event-methods.mjs +1 -1
- package/esm/model/methods/instance-event-methods.mjs.map +1 -1
- package/esm/model/methods/meta-methods.mjs +1 -1
- package/esm/model/methods/meta-methods.mjs.map +1 -1
- package/esm/model/methods/pivot-methods.mjs +1 -1
- package/esm/model/methods/pivot-methods.mjs.map +1 -1
- package/esm/model/methods/query-methods.mjs +1 -1
- package/esm/model/methods/query-methods.mjs.map +1 -1
- package/esm/model/methods/restore-methods.mjs +1 -1
- package/esm/model/methods/restore-methods.mjs.map +1 -1
- package/esm/model/methods/scope-methods.mjs +1 -1
- package/esm/model/methods/scope-methods.mjs.map +1 -1
- package/esm/model/methods/serialization-methods.mjs +1 -1
- package/esm/model/methods/serialization-methods.mjs.map +1 -1
- package/esm/model/methods/static-event-methods.mjs +1 -1
- package/esm/model/methods/static-event-methods.mjs.map +1 -1
- package/esm/model/methods/write-methods.d.mts +1 -1
- package/esm/model/methods/write-methods.d.mts.map +1 -1
- package/esm/model/methods/write-methods.mjs +1 -1
- package/esm/model/methods/write-methods.mjs.map +1 -1
- package/esm/model/model.d.mts +1 -1
- package/esm/model/model.d.mts.map +1 -1
- package/esm/model/model.mjs +1 -1
- package/esm/model/model.mjs.map +1 -1
- package/esm/model/model.types.d.mts +1 -1
- package/esm/model/model.types.d.mts.map +1 -1
- package/esm/model/register-model.d.mts +1 -1
- package/esm/model/register-model.d.mts.map +1 -1
- package/esm/model/register-model.mjs +1 -1
- package/esm/model/register-model.mjs.map +1 -1
- package/esm/model/relation-decorators.d.mts +1 -1
- package/esm/model/relation-decorators.d.mts.map +1 -1
- package/esm/model/relation-decorators.mjs +1 -1
- package/esm/model/relation-decorators.mjs.map +1 -1
- package/esm/operations/database.d.mts +1 -1
- package/esm/operations/database.d.mts.map +1 -1
- package/esm/operations/database.mjs +1 -1
- package/esm/operations/database.mjs.map +1 -1
- package/esm/operations/migrations.d.mts +1 -1
- package/esm/operations/migrations.d.mts.map +1 -1
- package/esm/operations/migrations.mjs +1 -1
- package/esm/operations/migrations.mjs.map +1 -1
- package/esm/query-builder/query-builder.d.mts +1 -1
- package/esm/query-builder/query-builder.d.mts.map +1 -1
- package/esm/query-builder/query-builder.mjs +1 -1
- package/esm/query-builder/query-builder.mjs.map +1 -1
- package/esm/relations/key-conventions.mjs +1 -1
- package/esm/relations/key-conventions.mjs.map +1 -1
- package/esm/relations/pivot-operations.d.mts +1 -1
- package/esm/relations/pivot-operations.d.mts.map +1 -1
- package/esm/relations/pivot-operations.mjs +1 -1
- package/esm/relations/pivot-operations.mjs.map +1 -1
- package/esm/relations/relation-hydrator.d.mts +1 -1
- package/esm/relations/relation-hydrator.d.mts.map +1 -1
- package/esm/relations/relation-hydrator.mjs +1 -1
- package/esm/relations/relation-hydrator.mjs.map +1 -1
- package/esm/relations/relation-loader.d.mts +1 -1
- package/esm/relations/relation-loader.d.mts.map +1 -1
- package/esm/relations/relation-loader.mjs +1 -1
- package/esm/relations/relation-loader.mjs.map +1 -1
- package/esm/relations/types.d.mts +1 -1
- package/esm/relations/types.d.mts.map +1 -1
- package/esm/remover/database-remover.d.mts +1 -1
- package/esm/remover/database-remover.d.mts.map +1 -1
- package/esm/remover/database-remover.mjs +1 -1
- package/esm/remover/database-remover.mjs.map +1 -1
- package/esm/restorer/database-restorer.d.mts +1 -1
- package/esm/restorer/database-restorer.d.mts.map +1 -1
- package/esm/restorer/database-restorer.mjs +1 -1
- package/esm/restorer/database-restorer.mjs.map +1 -1
- package/esm/sql-database-dirty-tracker.d.mts +1 -1
- package/esm/sql-database-dirty-tracker.d.mts.map +1 -1
- package/esm/sql-database-dirty-tracker.mjs +1 -1
- package/esm/sql-database-dirty-tracker.mjs.map +1 -1
- package/esm/sync/model-events.mjs +1 -1
- package/esm/sync/model-events.mjs.map +1 -1
- package/esm/sync/model-sync-operation.d.mts +1 -1
- package/esm/sync/model-sync-operation.d.mts.map +1 -1
- package/esm/sync/model-sync-operation.mjs +1 -1
- package/esm/sync/model-sync-operation.mjs.map +1 -1
- package/esm/sync/model-sync.d.mts +1 -1
- package/esm/sync/model-sync.d.mts.map +1 -1
- package/esm/sync/model-sync.mjs +1 -1
- package/esm/sync/model-sync.mjs.map +1 -1
- package/esm/sync/sync-context.d.mts +1 -1
- package/esm/sync/sync-context.d.mts.map +1 -1
- package/esm/sync/sync-context.mjs +1 -1
- package/esm/sync/sync-context.mjs.map +1 -1
- package/esm/sync/sync-manager.d.mts +1 -1
- package/esm/sync/sync-manager.d.mts.map +1 -1
- package/esm/sync/sync-manager.mjs +1 -1
- package/esm/sync/sync-manager.mjs.map +1 -1
- package/esm/sync/types.d.mts +1 -1
- package/esm/sync/types.d.mts.map +1 -1
- package/esm/types.d.mts +1 -1
- package/esm/types.d.mts.map +1 -1
- package/esm/utils/connect-to-database.d.mts +1 -1
- package/esm/utils/connect-to-database.d.mts.map +1 -1
- package/esm/utils/connect-to-database.mjs +1 -1
- package/esm/utils/connect-to-database.mjs.map +1 -1
- package/esm/utils/database-writer.utils.d.mts +1 -1
- package/esm/utils/database-writer.utils.d.mts.map +1 -1
- package/esm/utils/database-writer.utils.mjs +1 -1
- package/esm/utils/database-writer.utils.mjs.map +1 -1
- package/esm/utils/define-model.d.mts +1 -1
- package/esm/utils/define-model.d.mts.map +1 -1
- package/esm/utils/define-model.mjs +1 -1
- package/esm/utils/define-model.mjs.map +1 -1
- package/esm/utils/is-valid-date-value.mjs +1 -1
- package/esm/utils/is-valid-date-value.mjs.map +1 -1
- package/esm/utils/once-connected.d.mts +1 -1
- package/esm/utils/once-connected.d.mts.map +1 -1
- package/esm/utils/once-connected.mjs +1 -1
- package/esm/utils/once-connected.mjs.map +1 -1
- package/esm/validation/database-seal-plugins.mjs +1 -1
- package/esm/validation/database-seal-plugins.mjs.map +1 -1
- package/esm/validation/database-writer-validation-error.d.mts +1 -1
- package/esm/validation/database-writer-validation-error.d.mts.map +1 -1
- package/esm/validation/database-writer-validation-error.mjs +1 -1
- package/esm/validation/database-writer-validation-error.mjs.map +1 -1
- package/esm/validation/mutators/embed-mutator.mjs +1 -1
- package/esm/validation/mutators/embed-mutator.mjs.map +1 -1
- package/esm/validation/plugins/database-rules-plugin.d.mts +1 -1
- package/esm/validation/plugins/database-rules-plugin.d.mts.map +1 -1
- package/esm/validation/plugins/database-rules-plugin.mjs +1 -1
- package/esm/validation/plugins/database-rules-plugin.mjs.map +1 -1
- package/esm/validation/plugins/embed-validator-plugin.d.mts +1 -1
- package/esm/validation/plugins/embed-validator-plugin.d.mts.map +1 -1
- package/esm/validation/plugins/embed-validator-plugin.mjs +1 -1
- package/esm/validation/plugins/embed-validator-plugin.mjs.map +1 -1
- package/esm/validation/rules/database-model-rule.mjs +1 -1
- package/esm/validation/rules/database-model-rule.mjs.map +1 -1
- package/esm/validation/rules/exists-rule.mjs +1 -1
- package/esm/validation/rules/exists-rule.mjs.map +1 -1
- package/esm/validation/rules/unique-rule.mjs +1 -1
- package/esm/validation/rules/unique-rule.mjs.map +1 -1
- package/esm/validation/transformers/embed-model-transformer.mjs +1 -1
- package/esm/validation/transformers/embed-model-transformer.mjs.map +1 -1
- package/esm/validation/types.d.mts +1 -1
- package/esm/validation/types.d.mts.map +1 -1
- package/esm/validation/validators/embed-validator.d.mts +1 -1
- package/esm/validation/validators/embed-validator.d.mts.map +1 -1
- package/esm/validation/validators/embed-validator.mjs +1 -1
- package/esm/validation/validators/embed-validator.mjs.map +1 -1
- package/esm/writer/database-writer.d.mts +1 -1
- package/esm/writer/database-writer.d.mts.map +1 -1
- package/esm/writer/database-writer.mjs +1 -1
- package/esm/writer/database-writer.mjs.map +1 -1
- package/llms-full.txt +14 -0
- package/package.json +4 -4
- package/skills/write-migration/SKILL.md +14 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongodb-query-operations.mjs","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/mongodb/mongodb-query-operations.ts"],"sourcesContent":["import type { Operation, PipelineStage } from \"./types\";\n\n/**\n * Helper class for constructing MongoDB aggregation pipeline operations.\n *\n * This class encapsulates the logic for creating operation objects that will be\n * converted to MongoDB aggregation stages by the query parser. It provides a\n * clean abstraction over the low-level operation structure, making the query\n * builder code more maintainable and testable.\n *\n * Each operation consists of:\n * - **stage**: The MongoDB aggregation stage name (e.g., \"$match\", \"$project\")\n * - **type**: An internal identifier for the operation type\n * - **data**: The data associated with the operation\n * - **mergeable**: Whether this operation can be merged with adjacent similar operations\n *\n * @internal This class is for internal use within the MongoDB driver\n *\n * @example\n * ```typescript\n * const operations: Operation[] = [];\n * const helper = new MongoQueryOperations(operations);\n *\n * // Add a match operation\n * helper.addMatchOperation(\"whereIn\", { field: \"status\", values: [\"active\", \"pending\"] });\n *\n * // Add a project operation\n * helper.addProjectOperation(\"select\", { fields: [\"name\", \"email\"] });\n *\n * // Operations array is now populated\n * console.log(operations);\n * // [\n * // { stage: \"$match\", mergeable: true, type: \"whereIn\", data: {...} },\n * // { stage: \"$project\", mergeable: true, type: \"select\", data: {...} }\n * // ]\n * ```\n */\nexport class MongoQueryOperations {\n /**\n * Creates a new operations helper.\n *\n * The helper maintains a reference to the operations array and populates it\n * as methods are called. This allows the query builder to maintain a single\n * ordered list of operations that will be converted to a MongoDB aggregation\n * pipeline.\n *\n * @param operations - Reference to the operations array to populate\n *\n * @example\n * ```typescript\n * const operations: Operation[] = [];\n * const helper = new MongoQueryOperations(operations);\n * ```\n */\n public constructor(private operations: Operation[]) {}\n\n public setOperations(operations: Operation[]): void {\n this.operations = operations;\n }\n\n /**\n * Adds a $match stage operation to the pipeline.\n *\n * Match operations filter documents in the aggregation pipeline, similar to\n * the WHERE clause in SQL. Multiple match operations can be merged together\n * by the parser for optimization.\n *\n * @param type - The operation type identifier (e.g., \"where\", \"whereIn\", \"whereLike\")\n * @param data - The operation data data containing filter criteria\n * @param mergeable - Whether this operation can be merged with adjacent match operations (default: true)\n *\n * @example\n * ```typescript\n * // Simple where operation\n * helper.addMatchOperation(\"where\", { field: \"age\", operator: \">\", value: 18 });\n *\n * // WhereIn operation\n * helper.addMatchOperation(\"whereIn\", { field: \"status\", values: [\"active\", \"pending\"] });\n *\n * // Non-mergeable match (e.g., after a group stage)\n * helper.addMatchOperation(\"having\", { field: \"count\", operator: \">\", value: 5 }, false);\n * ```\n */\n public addMatchOperation(type: string, data: Record<string, unknown>, mergeable = true): void {\n this.operations.push({\n stage: \"$match\",\n mergeable,\n type,\n data,\n });\n }\n\n /**\n * Adds a $project stage operation to the pipeline.\n *\n * Project operations control which fields are included or excluded in the\n * output documents, similar to the SELECT clause in SQL. They can also be\n * used to compute new fields or reshape documents.\n *\n * @param type - The operation type identifier (e.g., \"select\", \"deselect\", \"selectRaw\")\n * @param data - The operation data data containing projection specifications\n * @param mergeable - Whether this operation can be merged with adjacent project operations (default: true)\n *\n * @example\n * ```typescript\n * // Select specific fields\n * helper.addProjectOperation(\"select\", { fields: [\"name\", \"email\", \"age\"] });\n *\n * // Deselect fields\n * helper.addProjectOperation(\"deselect\", { fields: [\"password\", \"secret\"] });\n *\n * // Computed field\n * helper.addProjectOperation(\"selectRaw\", {\n * expression: { fullName: { $concat: [\"$firstName\", \" \", \"$lastName\"] } }\n * });\n * ```\n */\n public addProjectOperation(\n type: string,\n data: Record<string, unknown>,\n mergeable = true,\n ): void {\n this.operations.push({\n stage: \"$project\",\n mergeable,\n type,\n data,\n });\n }\n\n /**\n * Adds a $sort stage operation to the pipeline.\n *\n * Sort operations order the documents in the pipeline, similar to the ORDER BY\n * clause in SQL. Multiple sort operations can be merged to create compound\n * sorting.\n *\n * @param type - The operation type identifier (e.g., \"orderBy\", \"orderByRandom\")\n * @param data - The operation data data containing sort specifications\n * @param mergeable - Whether this operation can be merged with adjacent sort operations (default: true)\n *\n * @example\n * ```typescript\n * // Order by a single field\n * helper.addSortOperation(\"orderBy\", { field: \"createdAt\", direction: \"desc\" });\n *\n * // Random ordering (not mergeable)\n * helper.addSortOperation(\"orderByRandom\", {limit: 1000}, false);\n *\n * // Order by raw expression\n * helper.addSortOperation(\"orderByRaw\", {\n * expression: { score: -1, name: 1 }\n * });\n * ```\n */\n public addSortOperation(type: string, data: Record<string, unknown>, mergeable = true): void {\n this.operations.push({\n stage: \"$sort\",\n mergeable,\n type,\n data,\n });\n }\n\n /**\n * Adds a $group stage operation to the pipeline.\n *\n * Group operations aggregate documents by specified fields and compute\n * aggregate values, similar to the GROUP BY clause in SQL. Group operations\n * are typically not mergeable as they represent distinct aggregation boundaries.\n *\n * @param type - The operation type identifier (e.g., \"groupBy\", \"distinct\")\n * @param data - The operation data data containing grouping specifications\n * @param mergeable - Whether this operation can be merged with adjacent group operations (default: false)\n *\n * @example\n * ```typescript\n * // Group by a single field\n * helper.addGroupOperation(\"groupBy\", { fields: \"category\" });\n *\n * // Group by multiple fields\n * helper.addGroupOperation(\"groupBy\", {\n * fields: { category: \"$category\", status: \"$status\" }\n * });\n *\n * // Distinct operation (special case of grouping)\n * helper.addGroupOperation(\"distinct\", { fields: [\"email\"] });\n * ```\n */\n public addGroupOperation(\n type: string,\n data: Record<string, unknown>,\n mergeable = false,\n ): void {\n this.operations.push({\n stage: \"$group\",\n mergeable,\n type,\n data,\n });\n }\n\n /**\n * Adds a $lookup stage operation to the pipeline.\n *\n * Lookup operations perform left outer joins with other collections, similar\n * to JOIN in SQL. Lookup operations are never mergeable as each represents a\n * distinct join operation.\n *\n * @param type - The operation type identifier (typically \"join\")\n * @param data - The operation data data containing join specifications\n *\n * @example\n * ```typescript\n * // Simple lookup\n * helper.addLookupOperation(\"join\", {\n * table: \"orders\",\n * localField: \"id\",\n * foreignField: \"userId\",\n * alias: \"userOrders\"\n * });\n *\n * // Lookup with pipeline\n * helper.addLookupOperation(\"join\", {\n * table: \"products\",\n * pipeline: [\n * { $match: { inStock: true } },\n * { $sort: { price: 1 } }\n * ],\n * alias: \"availableProducts\"\n * });\n * ```\n */\n public addLookupOperation(type: string, data: Record<string, unknown>): void {\n this.operations.push({\n stage: \"$lookup\",\n mergeable: false,\n type,\n data,\n });\n }\n\n /**\n * Adds a generic stage operation to the pipeline.\n *\n * This method provides flexibility to add any MongoDB aggregation stage,\n * including less common stages like $facet, $bucket, $setWindowFields, etc.\n * Use this for operations that don't fit into the standard categories.\n *\n * @param stage - The MongoDB aggregation stage name (e.g., \"$limit\", \"$skip\", \"$unwind\")\n * @param type - The operation type identifier\n * @param data - The operation data data\n * @param mergeable - Whether this operation can be merged with adjacent operations (default: false)\n *\n * @example\n * ```typescript\n * // Add a limit operation\n * helper.addOperation(\"$limit\", \"limit\", { value: 10 });\n *\n * // Add a skip operation\n * helper.addOperation(\"$skip\", \"skip\", { value: 20 });\n *\n * // Add an unwind operation\n * helper.addOperation(\"$unwind\", \"unwind\", { path: \"$tags\" });\n *\n * // Add a window function\n * helper.addOperation(\"$setWindowFields\", \"selectWindow\", {\n * spec: {\n * partitionBy: \"$category\",\n * sortBy: { price: 1 },\n * output: { rank: { $rank: {} } }\n * }\n * });\n * ```\n */\n public addOperation(\n stage: PipelineStage,\n type: string,\n data: Record<string, unknown>,\n mergeable = false,\n ): void {\n this.operations.push({\n stage,\n mergeable,\n type,\n data,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,uBAAb,MAAkC;CAiBL;;;;;;;;;;;;;;;;;CAA3B,AAAO,YAAY,AAAQ,YAAyB;EAAzB;CAA0B;CAErD,AAAO,cAAc,YAA+B;EAClD,KAAK,aAAa;CACpB;;;;;;;;;;;;;;;;;;;;;;;;CAyBA,AAAO,kBAAkB,MAAc,MAA+B,YAAY,MAAY;EAC5F,KAAK,WAAW,KAAK;GACnB,OAAO;GACP;GACA;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,oBACL,MACA,MACA,YAAY,MACN;EACN,KAAK,WAAW,KAAK;GACnB,OAAO;GACP;GACA;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,iBAAiB,MAAc,MAA+B,YAAY,MAAY;EAC3F,KAAK,WAAW,KAAK;GACnB,OAAO;GACP;GACA;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,kBACL,MACA,MACA,YAAY,OACN;EACN,KAAK,WAAW,KAAK;GACnB,OAAO;GACP;GACA;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCA,AAAO,mBAAmB,MAAc,MAAqC;EAC3E,KAAK,WAAW,KAAK;GACnB,OAAO;GACP,WAAW;GACX;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCA,AAAO,aACL,OACA,MACA,MACA,YAAY,OACN;EACN,KAAK,WAAW,KAAK;GACnB;GACA;GACA;GACA;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"mongodb-query-operations.mjs","names":[],"sources":["../../../../../../../../cascade/src/drivers/mongodb/mongodb-query-operations.ts"],"sourcesContent":["import type { Operation, PipelineStage } from \"./types\";\n\n/**\n * Helper class for constructing MongoDB aggregation pipeline operations.\n *\n * This class encapsulates the logic for creating operation objects that will be\n * converted to MongoDB aggregation stages by the query parser. It provides a\n * clean abstraction over the low-level operation structure, making the query\n * builder code more maintainable and testable.\n *\n * Each operation consists of:\n * - **stage**: The MongoDB aggregation stage name (e.g., \"$match\", \"$project\")\n * - **type**: An internal identifier for the operation type\n * - **data**: The data associated with the operation\n * - **mergeable**: Whether this operation can be merged with adjacent similar operations\n *\n * @internal This class is for internal use within the MongoDB driver\n *\n * @example\n * ```typescript\n * const operations: Operation[] = [];\n * const helper = new MongoQueryOperations(operations);\n *\n * // Add a match operation\n * helper.addMatchOperation(\"whereIn\", { field: \"status\", values: [\"active\", \"pending\"] });\n *\n * // Add a project operation\n * helper.addProjectOperation(\"select\", { fields: [\"name\", \"email\"] });\n *\n * // Operations array is now populated\n * console.log(operations);\n * // [\n * // { stage: \"$match\", mergeable: true, type: \"whereIn\", data: {...} },\n * // { stage: \"$project\", mergeable: true, type: \"select\", data: {...} }\n * // ]\n * ```\n */\nexport class MongoQueryOperations {\n /**\n * Creates a new operations helper.\n *\n * The helper maintains a reference to the operations array and populates it\n * as methods are called. This allows the query builder to maintain a single\n * ordered list of operations that will be converted to a MongoDB aggregation\n * pipeline.\n *\n * @param operations - Reference to the operations array to populate\n *\n * @example\n * ```typescript\n * const operations: Operation[] = [];\n * const helper = new MongoQueryOperations(operations);\n * ```\n */\n public constructor(private operations: Operation[]) {}\n\n public setOperations(operations: Operation[]): void {\n this.operations = operations;\n }\n\n /**\n * Adds a $match stage operation to the pipeline.\n *\n * Match operations filter documents in the aggregation pipeline, similar to\n * the WHERE clause in SQL. Multiple match operations can be merged together\n * by the parser for optimization.\n *\n * @param type - The operation type identifier (e.g., \"where\", \"whereIn\", \"whereLike\")\n * @param data - The operation data data containing filter criteria\n * @param mergeable - Whether this operation can be merged with adjacent match operations (default: true)\n *\n * @example\n * ```typescript\n * // Simple where operation\n * helper.addMatchOperation(\"where\", { field: \"age\", operator: \">\", value: 18 });\n *\n * // WhereIn operation\n * helper.addMatchOperation(\"whereIn\", { field: \"status\", values: [\"active\", \"pending\"] });\n *\n * // Non-mergeable match (e.g., after a group stage)\n * helper.addMatchOperation(\"having\", { field: \"count\", operator: \">\", value: 5 }, false);\n * ```\n */\n public addMatchOperation(type: string, data: Record<string, unknown>, mergeable = true): void {\n this.operations.push({\n stage: \"$match\",\n mergeable,\n type,\n data,\n });\n }\n\n /**\n * Adds a $project stage operation to the pipeline.\n *\n * Project operations control which fields are included or excluded in the\n * output documents, similar to the SELECT clause in SQL. They can also be\n * used to compute new fields or reshape documents.\n *\n * @param type - The operation type identifier (e.g., \"select\", \"deselect\", \"selectRaw\")\n * @param data - The operation data data containing projection specifications\n * @param mergeable - Whether this operation can be merged with adjacent project operations (default: true)\n *\n * @example\n * ```typescript\n * // Select specific fields\n * helper.addProjectOperation(\"select\", { fields: [\"name\", \"email\", \"age\"] });\n *\n * // Deselect fields\n * helper.addProjectOperation(\"deselect\", { fields: [\"password\", \"secret\"] });\n *\n * // Computed field\n * helper.addProjectOperation(\"selectRaw\", {\n * expression: { fullName: { $concat: [\"$firstName\", \" \", \"$lastName\"] } }\n * });\n * ```\n */\n public addProjectOperation(\n type: string,\n data: Record<string, unknown>,\n mergeable = true,\n ): void {\n this.operations.push({\n stage: \"$project\",\n mergeable,\n type,\n data,\n });\n }\n\n /**\n * Adds a $sort stage operation to the pipeline.\n *\n * Sort operations order the documents in the pipeline, similar to the ORDER BY\n * clause in SQL. Multiple sort operations can be merged to create compound\n * sorting.\n *\n * @param type - The operation type identifier (e.g., \"orderBy\", \"orderByRandom\")\n * @param data - The operation data data containing sort specifications\n * @param mergeable - Whether this operation can be merged with adjacent sort operations (default: true)\n *\n * @example\n * ```typescript\n * // Order by a single field\n * helper.addSortOperation(\"orderBy\", { field: \"createdAt\", direction: \"desc\" });\n *\n * // Random ordering (not mergeable)\n * helper.addSortOperation(\"orderByRandom\", {limit: 1000}, false);\n *\n * // Order by raw expression\n * helper.addSortOperation(\"orderByRaw\", {\n * expression: { score: -1, name: 1 }\n * });\n * ```\n */\n public addSortOperation(type: string, data: Record<string, unknown>, mergeable = true): void {\n this.operations.push({\n stage: \"$sort\",\n mergeable,\n type,\n data,\n });\n }\n\n /**\n * Adds a $group stage operation to the pipeline.\n *\n * Group operations aggregate documents by specified fields and compute\n * aggregate values, similar to the GROUP BY clause in SQL. Group operations\n * are typically not mergeable as they represent distinct aggregation boundaries.\n *\n * @param type - The operation type identifier (e.g., \"groupBy\", \"distinct\")\n * @param data - The operation data data containing grouping specifications\n * @param mergeable - Whether this operation can be merged with adjacent group operations (default: false)\n *\n * @example\n * ```typescript\n * // Group by a single field\n * helper.addGroupOperation(\"groupBy\", { fields: \"category\" });\n *\n * // Group by multiple fields\n * helper.addGroupOperation(\"groupBy\", {\n * fields: { category: \"$category\", status: \"$status\" }\n * });\n *\n * // Distinct operation (special case of grouping)\n * helper.addGroupOperation(\"distinct\", { fields: [\"email\"] });\n * ```\n */\n public addGroupOperation(\n type: string,\n data: Record<string, unknown>,\n mergeable = false,\n ): void {\n this.operations.push({\n stage: \"$group\",\n mergeable,\n type,\n data,\n });\n }\n\n /**\n * Adds a $lookup stage operation to the pipeline.\n *\n * Lookup operations perform left outer joins with other collections, similar\n * to JOIN in SQL. Lookup operations are never mergeable as each represents a\n * distinct join operation.\n *\n * @param type - The operation type identifier (typically \"join\")\n * @param data - The operation data data containing join specifications\n *\n * @example\n * ```typescript\n * // Simple lookup\n * helper.addLookupOperation(\"join\", {\n * table: \"orders\",\n * localField: \"id\",\n * foreignField: \"userId\",\n * alias: \"userOrders\"\n * });\n *\n * // Lookup with pipeline\n * helper.addLookupOperation(\"join\", {\n * table: \"products\",\n * pipeline: [\n * { $match: { inStock: true } },\n * { $sort: { price: 1 } }\n * ],\n * alias: \"availableProducts\"\n * });\n * ```\n */\n public addLookupOperation(type: string, data: Record<string, unknown>): void {\n this.operations.push({\n stage: \"$lookup\",\n mergeable: false,\n type,\n data,\n });\n }\n\n /**\n * Adds a generic stage operation to the pipeline.\n *\n * This method provides flexibility to add any MongoDB aggregation stage,\n * including less common stages like $facet, $bucket, $setWindowFields, etc.\n * Use this for operations that don't fit into the standard categories.\n *\n * @param stage - The MongoDB aggregation stage name (e.g., \"$limit\", \"$skip\", \"$unwind\")\n * @param type - The operation type identifier\n * @param data - The operation data data\n * @param mergeable - Whether this operation can be merged with adjacent operations (default: false)\n *\n * @example\n * ```typescript\n * // Add a limit operation\n * helper.addOperation(\"$limit\", \"limit\", { value: 10 });\n *\n * // Add a skip operation\n * helper.addOperation(\"$skip\", \"skip\", { value: 20 });\n *\n * // Add an unwind operation\n * helper.addOperation(\"$unwind\", \"unwind\", { path: \"$tags\" });\n *\n * // Add a window function\n * helper.addOperation(\"$setWindowFields\", \"selectWindow\", {\n * spec: {\n * partitionBy: \"$category\",\n * sortBy: { price: 1 },\n * output: { rank: { $rank: {} } }\n * }\n * });\n * ```\n */\n public addOperation(\n stage: PipelineStage,\n type: string,\n data: Record<string, unknown>,\n mergeable = false,\n ): void {\n this.operations.push({\n stage,\n mergeable,\n type,\n data,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,uBAAb,MAAkC;CAiBL;;;;;;;;;;;;;;;;;CAA3B,AAAO,YAAY,AAAQ,YAAyB;EAAzB;CAA0B;CAErD,AAAO,cAAc,YAA+B;EAClD,KAAK,aAAa;CACpB;;;;;;;;;;;;;;;;;;;;;;;;CAyBA,AAAO,kBAAkB,MAAc,MAA+B,YAAY,MAAY;EAC5F,KAAK,WAAW,KAAK;GACnB,OAAO;GACP;GACA;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,oBACL,MACA,MACA,YAAY,MACN;EACN,KAAK,WAAW,KAAK;GACnB,OAAO;GACP;GACA;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,iBAAiB,MAAc,MAA+B,YAAY,MAAY;EAC3F,KAAK,WAAW,KAAK;GACnB,OAAO;GACP;GACA;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,kBACL,MACA,MACA,YAAY,OACN;EACN,KAAK,WAAW,KAAK;GACnB,OAAO;GACP;GACA;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCA,AAAO,mBAAmB,MAAc,MAAqC;EAC3E,KAAK,WAAW,KAAK;GACnB,OAAO;GACP,WAAW;GACX;GACA;EACF,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCA,AAAO,aACL,OACA,MACA,MACA,YAAY,OACN;EACN,KAAK,WAAW,KAAK;GACnB;GACA;GACA;GACA;EACF,CAAC;CACH;AACF"}
|
|
@@ -2,7 +2,7 @@ import { Operation } from "./types.mjs";
|
|
|
2
2
|
import { MongoQueryBuilder } from "./mongodb-query-builder.mjs";
|
|
3
3
|
import { Collection } from "mongodb";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region ../cascade/src/drivers/mongodb/mongodb-query-parser.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* Options for configuring the MongoDB query parser.
|
|
8
8
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongodb-query-parser.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"mongodb-query-parser.d.mts","names":[],"sources":["../../../../../../../../cascade/src/drivers/mongodb/mongodb-query-parser.ts"],"mappings":";;;;;;;AAcA;KAAY,uBAAA;6CAEV,UAAA,EAAY,UAAA,EAEA;EAAZ,UAAA,EAAY,SAAA,IAE6B;EAAzC,gBAAA,QAAwB,iBAAA;AAAA;;;;;;;AAAiB;AAW3C;cAAa,gBAAA;;;;mBAIM,UAAA;EAUA;;;EAAA,iBALA,UAAA;EA0BW;;;EAAA,iBArBX,gBAAA;EAsJT;;;;EAAA,iBAhJS,eAAA;EAoWT;;;;;;EAAA,iBA5VS,oBAAA;EAm4BT;;;;;cA53BW,OAAA,EAAS,uBAAuB;EAo7B3C;;;;;;;;;;;;;;;;;;;;EA15BD,KAAA;EA2pCC;;;;;;;;;;;;;;;EAAA,QArlCA,WAAA;EA0lDA;;;EAAA,QAzjDA,oBAAA;;;;;;UA2BA,yBAAA;;;;;;;;;;UAyBA,sBAAA;;;;;;;;;;;;;;;;;;;;;;;;EA4ED,cAAA;;;;;;;;UAgCC,eAAA;;;;;;;;UAoDA,UAAA;;;;;;;;;;;UAmCA,eAAA;EAAA,QA8KA,iBAAA;;;;;;;;;UAkBA,sBAAA;;;;;;;UA8EA,mBAAA;;;;;;;;;UAiNA,sBAAA;;;;;;;UAyBA,gBAAA;EAAA,QAYA,oBAAA;EAAA,QAaA,aAAA;EAAA,QAYA,qBAAA;EAAA,QASA,4BAAA;EAAA,QAWA,UAAA;EAAA,QAIA,0BAAA;EAAA,QAOA,wBAAA;EAAA,QAKA,uBAAA;EAAA,QAKA,kBAAA;EAAA,QAgBA,sBAAA;EAAA,QAiBA,0BAAA;EAAA,QAQA,+BAAA;EAAA,QAMA,6BAAA;EAAA,QAMA,wBAAA;EAAA,QASA,sBAAA;EAAA,QAQA,yBAAA;EAAA,QASA,kBAAA;EAAA,QAWA,UAAA;EAAA,QAMA,QAAA;EAAA,QAMA,aAAA;EAAA,QAIA,qBAAA;;;;;;UAeA,qBAAA;EAAA,QAmCA,kBAAA;EAAA,QAeA,2BAAA;EAAA,QA0BA,uBAAA;EAAA,QAoBA,wBAAA;EAAA,QAwBA,qBAAA;EAAA,QAMA,wBAAA;EAAA,QAMA,mBAAA;EAAA,QAeA,mBAAA;;;;;UAkBA,0BAAA;EAAA,QAaA,cAAA;EAAA,QAMA,qBAAA;EAAA,QAMA,uBAAA;;;;;;;UAsBA,iBAAA;;;;;;;UAqHA,cAAA;;;;;;;UA2BA,eAAA;EAAA,QA0DA,iBAAA;;;;;;;;UAgBA,+BAAA;;;;;;;;;;UAoCA,qBAAA;;;;;;;UA0BA,sBAAA;;;;;;;UA4BA,4BAAA;;;;;;;;;;;;;UAuFA,uBAAA;EAAA,QAoCA,YAAA;;;;;;;UAgDA,gBAAA;AAAA"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isAggregateExpression } from "../../expressions/aggregate-expressions.mjs";
|
|
2
2
|
import { colors } from "@mongez/copper";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../cascade/src/drivers/mongodb/mongodb-query-parser.ts
|
|
5
5
|
/**
|
|
6
6
|
* Parses query builder operations into MongoDB aggregation pipeline.
|
|
7
7
|
*
|
|
@@ -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.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,AAAO,YAAY,SAAkC;EACnD,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAAa,QAAQ;EAC1B,KAAK,mBAAmB,QAAQ;CAClC;;;;;;;;;;;;;;;;;;;;;CAsBA,AAAO,QAAe;EACpB,MAAM,WAAkB,CAAC;EACzB,IAAI,eAAqC;EACzC,IAAI,gBAA6B,CAAC;EAElC,KAAK,MAAM,MAAM,KAAK,YAAY,KAAK,UAAU,GAC/C,IAAI,GAAG,aAAa,GAAG,UAAU,cAE/B,cAAc,KAAK,EAAE;OAChB;GAEL,IAAI,cAAc,SAAS,GAAG;IAC5B,MAAM,aAAa,KAAK,WAAW,cAAe,aAAa;IAC/D,IAAI,YAAY;KACd,MAAM,aAAa,SAAS;KAC5B,SAAS,KAAK,UAAU;KAExB,KAAK,qBAAqB,cAAe,eAAe,UAAU;IACpE;IACA,gBAAgB,CAAC;GACnB;GAEA,IAAI,GAAG,W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GACpB,cAAc,QAAQ;GACtB,IAAI,QAAQ,SAAS,QAAQ;EAC/B,EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"mongodb-query-parser.mjs","names":[],"sources":["../../../../../../../../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,AAAO,YAAY,SAAkC;EACnD,KAAK,aAAa,QAAQ;EAC1B,KAAK,aAAa,QAAQ;EAC1B,KAAK,mBAAmB,QAAQ;CAClC;;;;;;;;;;;;;;;;;;;;;CAsBA,AAAO,QAAe;EACpB,MAAM,WAAkB,CAAC;EACzB,IAAI,eAAqC;EACzC,IAAI,gBAA6B,CAAC;EAElC,KAAK,MAAM,MAAM,KAAK,Y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AM,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;IAC/C,IAAI,OAAO,UAAU,YAAY,CAAC,MAAM,WAAW,GAAG,GACpD,WAAW,OAAO,IAAI;SAEtB,WAAW,OAAO;GAEtB,CAAC;GACD,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;CAQA,AAAQ,iBAAiB,YAA8B;EAErD,MAAM,UADK,WAAW,EACJ,CAAC;EAEnB,OAAO,EACL,SAAS;GACP,MAAM,QAAQ;GACd,YAAY,QAAQ;GACpB,cAAc,QAAQ;GACtB,IAAI,QAAQ,SAAS,QAAQ;EAC/B,EACF;CACF;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SyncAdapterContract, SyncInstruction } from "../../contracts/sync-adapter.contract.mjs";
|
|
2
2
|
import { MongoDbDriver } from "./mongodb-driver.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../cascade/src/drivers/mongodb/mongodb-sync-adapter.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* MongoDB implementation of the sync adapter.
|
|
7
7
|
* Handles array updates using positional operators and arrayFilters.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongodb-sync-adapter.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"mongodb-sync-adapter.d.mts","names":[],"sources":["../../../../../../../../cascade/src/drivers/mongodb/mongodb-sync-adapter.ts"],"mappings":";;;;;;;;;cAca,gBAAA,YAA4B,mBAAA;EAAA,iBACtB,MAAA;EADsB;;;;;cAQpB,MAAA,EAAQ,aAAA;EAAA;;;;;;EAUd,YAAA,CAAa,YAAA,EAAc,eAAA,KAAoB,OAAA;EAqBvB;;;;;;;EAAxB,UAAA,CAAW,WAAA,EAAa,eAAA,GAAkB,OAAA;EA0DzC;;;;AAkEwB;;;EA3GzB,kBAAA,CAAmB,WAAA,EAAa,eAAA,GAAkB,OAAA;;;;;;;;UA4BvD,wBAAA;;;;;;;;UAaM,uBAAA;;;;;;;;;;UAyCN,oBAAA;;;;;;;;UAyBA,8BAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongodb-sync-adapter.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"mongodb-sync-adapter.mjs","names":[],"sources":["../../../../../../../../cascade/src/drivers/mongodb/mongodb-sync-adapter.ts"],"sourcesContent":["/**\n * MongoDB-specific sync adapter implementation.\n *\n * @module cascade-next/drivers/mongodb/mongodb-sync-adapter\n */\n\nimport type { SyncAdapterContract, SyncInstruction } from \"../../contracts/sync-adapter.contract\";\nimport type { MongoDbDriver } from \"./mongodb-driver\";\n\n/**\n * MongoDB implementation of the sync adapter.\n * Handles array updates using positional operators and arrayFilters.\n * Automatically participates in active transactions via the driver's session context.\n */\nexport class MongoSyncAdapter implements SyncAdapterContract {\n private readonly driver: MongoDbDriver;\n\n /**\n * Creates a new MongoDB sync adapter.\n *\n * @param driver - The MongoDB driver instance (provides session-aware operations)\n */\n public constructor(driver: MongoDbDriver) {\n this.driver = driver;\n }\n\n /**\n * Executes a batch of sync instructions.\n *\n * @param instructions - Array of sync instructions\n * @returns Total number of documents affected\n */\n public async executeBatch(instructions: SyncInstruction[]): Promise<number> {\n let totalAffected = 0;\n\n for (const instruction of instructions) {\n const affected = instruction.isArrayUpdate\n ? await this.executeArrayUpdate(instruction)\n : await this.executeOne(instruction);\n\n totalAffected += affected;\n }\n\n return totalAffected;\n }\n\n /**\n * Executes a single sync instruction.\n * Uses the driver's updateMany to automatically participate in active transactions.\n *\n * @param instruction - The sync instruction\n * @returns Number of documents affected\n */\n public async executeOne(instruction: SyncInstruction): Promise<number> {\n const result = await this.driver.updateMany(\n instruction.targetTable,\n instruction.filter,\n instruction.update,\n );\n\n return result.modifiedCount;\n }\n\n /**\n * Executes an array update using MongoDB positional operators.\n * Uses the driver's updateMany to automatically participate in active transactions.\n *\n * @param instruction - The sync instruction with array info\n * @returns Number of documents affected\n */\n public async executeArrayUpdate(instruction: SyncInstruction): Promise<number> {\n if (!instruction.arrayField || !instruction.identifierField) {\n throw new Error(\"Array update requires arrayField and identifierField to be specified\");\n }\n\n // Strategy 1: Try positional operator $ (simpler, faster)\n // Works when filter already identifies the array element\n if (this.canUsePositionalOperator(instruction)) {\n const result = await this.driver.updateMany(\n instruction.targetTable,\n instruction.filter,\n instruction.update,\n );\n return result.modifiedCount;\n }\n\n // Strategy 2: Use arrayFilters (more flexible)\n // Works for any array update scenario\n return await this.executeWithArrayFilters(instruction);\n }\n\n /**\n * Checks if positional operator $ can be used.\n * Requires filter to already match the array element.\n *\n * @param instruction - The sync instruction\n * @returns True if positional operator can be used\n */\n private canUsePositionalOperator(instruction: SyncInstruction): boolean {\n // Check if filter already includes array element match\n const arrayElementFilter = `${instruction.arrayField}.${instruction.identifierField}`;\n return arrayElementFilter in instruction.filter;\n }\n\n /**\n * Executes array update using arrayFilters.\n * Uses the driver's updateMany with arrayFilters option to participate in transactions.\n *\n * @param instruction - The sync instruction\n * @returns Number of documents affected\n */\n private async executeWithArrayFilters(instruction: SyncInstruction): Promise<number> {\n // Build arrayFilters to match array elements\n const arrayFilters = [\n {\n [`elem.${instruction.identifierField}`]: instruction.identifierValue,\n },\n ];\n\n // Transform update to use array filter placeholder\n const transformedUpdate = this.transformUpdateForArrayFilters(\n instruction.update,\n instruction.arrayField!,\n );\n\n // Build optimized filter to reduce documents scanned\n const optimizedFilter = this.buildOptimizedFilter(\n instruction.filter,\n instruction.arrayField!,\n instruction.identifierField!,\n );\n\n // Use driver's updateMany (session-aware) with arrayFilters\n const result = await this.driver.updateMany(\n instruction.targetTable,\n optimizedFilter,\n transformedUpdate,\n { arrayFilters },\n );\n\n return result.modifiedCount;\n }\n\n /**\n * Builds an optimized filter to reduce the number of documents scanned.\n * Adds array existence check when filter doesn't already match array elements.\n *\n * @param originalFilter - The original filter from the instruction\n * @param arrayField - The array field path\n * @param identifierField - The identifier field within array elements\n * @returns Optimized filter\n */\n private buildOptimizedFilter(\n originalFilter: Record<string, unknown>,\n arrayField: string,\n identifierField: string,\n ): Record<string, unknown> {\n // If filter already has array element match, use it as-is\n const arrayElementFilter = `${arrayField}.${identifierField}`;\n if (arrayElementFilter in originalFilter) {\n return originalFilter;\n }\n\n // Otherwise, add array existence check to avoid full collection scan\n return {\n ...originalFilter,\n [arrayField]: { $exists: true, $ne: [] }, // Array exists and not empty\n };\n }\n\n /**\n * Transforms update operation to use arrayFilters placeholder.\n *\n * @param update - Original update operation\n * @param arrayField - Array field path\n * @returns Transformed update operation\n */\n private transformUpdateForArrayFilters(\n update: Record<string, unknown>,\n arrayField: string,\n ): Record<string, unknown> {\n const transformed: Record<string, unknown> = {};\n\n for (const [operator, fields] of Object.entries(update)) {\n if (typeof fields === \"object\" && fields !== null) {\n const transformedFields: Record<string, unknown> = {};\n\n for (const [field, value] of Object.entries(fields)) {\n // Replace positional $ with arrayFilters placeholder $[elem]\n const transformedField = field.replace(`${arrayField}.$`, `${arrayField}.$[elem]`);\n transformedFields[transformedField] = value;\n }\n\n transformed[operator] = transformedFields;\n }\n }\n\n return transformed;\n }\n}\n"],"mappings":";;;;;;AAcA,IAAa,mBAAb,MAA6D;CAC3D,AAAiB;;;;;;CAOjB,AAAO,YAAY,QAAuB;EACxC,KAAK,SAAS;CAChB;;;;;;;CAQA,MAAa,aAAa,cAAkD;EAC1E,IAAI,gBAAgB;EAEpB,KAAK,MAAM,eAAe,cAAc;GACtC,MAAM,WAAW,YAAY,gBACzB,MAAM,KAAK,mBAAmB,WAAW,IACzC,MAAM,KAAK,WAAW,WAAW;GAErC,iBAAiB;EACnB;EAEA,OAAO;CACT;;;;;;;;CASA,MAAa,WAAW,aAA+C;EAOrE,QAAO,MANc,KAAK,OAAO,WAC/B,YAAY,aACZ,YAAY,QACZ,YAAY,MACd,EAEa,CAAC;CAChB;;;;;;;;CASA,MAAa,mBAAmB,aAA+C;EAC7E,IAAI,CAAC,YAAY,cAAc,CAAC,YAAY,iBAC1C,MAAM,IAAI,MAAM,sE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","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../cascade/src/drivers/mongodb/types.ts"],"mappings":";;;;;AAKA;KAAY,aAAA;;;AAAa;KAiBb,SAAA;EAAS,8DAEnB,KAAA,EAAO,aAAa,EAAA;EAEpB,SAAA,WAFO;EAIP,IAAA;EAEA,IAAA;AAAA;AAAI;AASN;;;;;AATM,KASM,kBAAA;EAkBV;;;AAAuC;;EAZvC,cAAA;;;;;EAMA,iBAAA;;;;;EAMA,kBAAA,GAAqB,kBAAkB;AAAA"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DriverBlueprintContract, TableIndexInformation } from "../../contracts/driver-blueprint.contract.mjs";
|
|
2
2
|
import { PostgresDriver } from "./postgres-driver.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../cascade/src/drivers/postgres/postgres-blueprint.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* PostgreSQL Blueprint.
|
|
7
7
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-blueprint.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"postgres-blueprint.d.mts","names":[],"sources":["../../../../../../../../cascade/src/drivers/postgres/postgres-blueprint.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;cAgCa,iBAAA,YAA6B,uBAAA;EAAA,iBAMJ,MAAA;EA6EK;;;;;cA7EL,MAAA,EAAQ,cAAA;;;;;;EAO/B,UAAA,IAAc,OAAA;;;;;;;EAkBd,WAAA,CAAY,KAAA,WAAgB,OAAA,CAAQ,qBAAA;;;;;;;EAoDpC,WAAA,CAAY,KAAA,WAAgB,OAAA;;;;;;;EAmB5B,WAAA,CAAY,KAAA,WAAgB,OAAA;AAAA"}
|