Skip to main content

utopia_query/builder/
mongodb.rs

1//! MongoDB: [`MongoDb`], a builder that compiles to MongoDB operation
2//! documents (JSON) instead of SQL.
3//!
4//! A select compiles to a `find` (filter, projection, sort, skip, limit) or,
5//! when it needs stages a `find` cannot express (grouping, joins, window
6//! functions, unions, subqueries, search, pipeline stages), to an
7//! `aggregate` pipeline. Writes compile to `insertMany`, `updateMany`,
8//! `updateOne` (upserts) and `deleteMany`. Values are bound as `?` strings
9//! in the document, in order, as with the SQL builders.
10//!
11//! | PHP | Rust |
12//! |---|---|
13//! | `Builder\MongoDB` | [`MongoDb`] ([`MongoDbDialect`]) |
14//! | `Builder\MongoDB\Operation` | [`Operation`] |
15//! | `Builder\MongoDB\PipelineStage` | [`PipelineStage`] |
16//! | `Builder\MongoDB\UpdateOperator` | [`UpdateOperator`] |
17//! | `Builder\MongoDB\UpdateOperation` | [`UpdateOperation`] |
18//! | `hint(string\|array)` | [`MongoDb::hint`] with an [`IndexHint`] |
19//! | `push()`, `pull()`, `addToSet()`, `increment()`, `unsetFields()` | inherent methods of [`MongoDb`] |
20//! | `Feature\MongoDB\FieldUpdates` | [`MongoDb::rename`], [`MongoDb::multiply`], [`MongoDb::pop_first`], [`MongoDb::pop_last`], [`MongoDb::pull_all`], [`MongoDb::update_min`], [`MongoDb::update_max`], [`MongoDb::current_date`] |
21//! | `Feature\MongoDB\ArrayPushModifiers` | [`MongoDb::push_each`] |
22//! | `Feature\MongoDB\ConditionalArrayUpdates` | [`MongoDb::array_filter`] |
23//! | `Feature\MongoDB\PipelineStages` | [`MongoDb::bucket`], [`MongoDb::bucket_auto`], [`MongoDb::facet`], [`MongoDb::graph_lookup`], [`MongoDb::merge_into_collection`], [`MongoDb::output_to_collection`], [`MongoDb::replace_root`] |
24//! | `Feature\MongoDB\AtlasSearch` | [`MongoDb::search`], [`MongoDb::search_meta`], [`MongoDb::vector_search`] |
25//! | `Feature\Upsert`, `Feature\InsertOrIgnore`, `Feature\FullTextSearch`, `Feature\TableSampling` | the [`feature`](crate::builder::feature) traits |
26
27use php_std::ArrayKey;
28use php_std::json::{self, Flags};
29
30use crate::builder::AnyBuilder;
31use crate::builder::core::{Builder, Dialect, first, is_empty_string, on_values};
32use crate::builder::feature::{FullTextSearch, InsertOrIgnore, TableSampling, Upsert};
33use crate::builder::types::{Statement, WindowSelect};
34use crate::error::{Error, Result};
35use crate::hook::Hook;
36use crate::method::{Method, backed_enum};
37use crate::query::{ParsedQuery, Query};
38use crate::value::{self, Array, IntoValue, IntoValues, Object, Param, Value};
39
40backed_enum! {
41    /// The operation a compiled document runs.
42    ///
43    /// PHP: `Utopia\Query\Builder\MongoDB\Operation`.
44    pub enum Operation: "Utopia\\Query\\Builder\\MongoDB\\Operation" {
45        /// `insertMany`.
46        InsertMany = "insertMany",
47        /// `updateMany`.
48        UpdateMany = "updateMany",
49        /// `deleteMany`.
50        DeleteMany = "deleteMany",
51        /// `updateOne` (upserts).
52        UpdateOne = "updateOne",
53        /// `find`.
54        Find = "find",
55        /// `aggregate`.
56        Aggregate = "aggregate",
57    }
58}
59
60backed_enum! {
61    /// An aggregation pipeline stage (and the `$text` operator).
62    ///
63    /// PHP: `Utopia\Query\Builder\MongoDB\PipelineStage`.
64    pub enum PipelineStage: "Utopia\\Query\\Builder\\MongoDB\\PipelineStage" {
65        /// `$match`.
66        Match = "$match",
67        /// `$group`.
68        Group = "$group",
69        /// `$project`.
70        Project = "$project",
71        /// `$sort`.
72        Sort = "$sort",
73        /// `$skip`.
74        Skip = "$skip",
75        /// `$limit`.
76        Limit = "$limit",
77        /// `$lookup`.
78        Lookup = "$lookup",
79        /// `$graphLookup`.
80        GraphLookup = "$graphLookup",
81        /// `$facet`.
82        Facet = "$facet",
83        /// `$bucket`.
84        Bucket = "$bucket",
85        /// `$bucketAuto`.
86        BucketAuto = "$bucketAuto",
87        /// `$setWindowFields`.
88        SetWindowFields = "$setWindowFields",
89        /// `$search` (Atlas).
90        Search = "$search",
91        /// `$searchMeta` (Atlas).
92        SearchMeta = "$searchMeta",
93        /// `$vectorSearch` (Atlas).
94        VectorSearch = "$vectorSearch",
95        /// `$sample`.
96        Sample = "$sample",
97        /// `$text`.
98        Text = "$text",
99        /// `$unwind`.
100        Unwind = "$unwind",
101        /// `$addFields`.
102        AddFields = "$addFields",
103        /// `$replaceRoot`.
104        ReplaceRoot = "$replaceRoot",
105        /// `$unionWith`.
106        UnionWith = "$unionWith",
107        /// `$unset`.
108        Unset = "$unset",
109        /// `$merge`.
110        Merge = "$merge",
111        /// `$out`.
112        Out = "$out",
113    }
114}
115
116backed_enum! {
117    /// An update operator.
118    ///
119    /// PHP: `Utopia\Query\Builder\MongoDB\UpdateOperator`.
120    pub enum UpdateOperator: "Utopia\\Query\\Builder\\MongoDB\\UpdateOperator" {
121        /// `$set`.
122        Set = "$set",
123        /// `$push`.
124        Push = "$push",
125        /// `$pull`.
126        Pull = "$pull",
127        /// `$pullAll`.
128        PullAll = "$pullAll",
129        /// `$addToSet`.
130        AddToSet = "$addToSet",
131        /// `$inc`.
132        Increment = "$inc",
133        /// `$mul`.
134        Multiply = "$mul",
135        /// `$unset`.
136        Unset = "$unset",
137        /// `$rename`.
138        Rename = "$rename",
139        /// `$pop`.
140        Pop = "$pop",
141        /// `$min`.
142        Min = "$min",
143        /// `$max`.
144        Max = "$max",
145        /// `$currentDate`.
146        CurrentDate = "$currentDate",
147    }
148}
149
150/// An update operator with its fields (field => value).
151///
152/// PHP: `Utopia\Query\Builder\MongoDB\UpdateOperation`.
153#[derive(Debug, Clone, PartialEq)]
154pub struct UpdateOperation {
155    /// The operator.
156    pub operator: UpdateOperator,
157    /// Field => value (or modifier document).
158    pub fields: Array,
159}
160
161impl UpdateOperation {
162    /// An operator with its fields.
163    ///
164    /// PHP: `new UpdateOperation($operator, $fields)`.
165    pub fn new(operator: UpdateOperator, fields: Array) -> Self {
166        UpdateOperation { operator, fields }
167    }
168}
169
170/// The index a query must use: a name, or a key pattern (`{"name": 1}`).
171///
172/// PHP: the `string|array` of `MongoDB::hint()`.
173#[derive(Debug, Clone, PartialEq)]
174pub enum IndexHint {
175    /// An index name.
176    Name(String),
177    /// A key pattern: field => direction.
178    Keys(Array),
179}
180
181impl From<&str> for IndexHint {
182    /// [`IndexHint::Name`].
183    fn from(name: &str) -> Self {
184        IndexHint::Name(name.to_owned())
185    }
186}
187
188impl From<String> for IndexHint {
189    /// [`IndexHint::Name`].
190    fn from(name: String) -> Self {
191        IndexHint::Name(name)
192    }
193}
194
195impl From<Array> for IndexHint {
196    /// [`IndexHint::Keys`].
197    fn from(keys: Array) -> Self {
198        IndexHint::Keys(keys)
199    }
200}
201
202impl IndexHint {
203    fn to_value(&self) -> Value {
204        match self {
205            IndexHint::Name(name) => value::string(name),
206            IndexHint::Keys(keys) => Value::Array(keys.clone()),
207        }
208    }
209}
210
211/// A compiled facet: its pipeline and the bindings of its sub-builder.
212#[derive(Debug, Clone)]
213struct Facet {
214    name: ArrayKey,
215    pipeline: Array,
216    bindings: Vec<Value>,
217}
218
219/// A MongoDB builder: compiles to operation documents (JSON).
220///
221/// PHP: `Utopia\Query\Builder\MongoDB`.
222///
223/// ```
224/// use utopia_query::Query;
225/// use utopia_query::builder::MongoDb;
226///
227/// let statement = MongoDb::new()
228///     .from("users", "")
229///     .select(["name"])
230///     .filter([Query::greater_than("age", 18)])
231///     .sort_desc("age", None)
232///     .limit(10)
233///     .build()?;
234/// assert_eq!(
235///     statement.query,
236///     r#"{"collection":"users","operation":"find","filter":{"age":{"$gt":"?"}},"projection":{"name":1,"_id":0},"sort":{"age":-1},"limit":10}"#
237/// );
238/// assert_eq!(statement.bindings, vec![18.into()]);
239/// # Ok::<(), utopia_query::Error>(())
240/// ```
241///
242/// ```php
243/// use Utopia\Query\Builder\MongoDB;
244/// use Utopia\Query\Query;
245///
246/// $statement = (new MongoDB())
247///     ->from('users')
248///     ->select(['name'])
249///     ->filter([Query::greaterThan('age', 18)])
250///     ->sortDesc('age')
251///     ->limit(10)
252///     ->build();
253/// echo $statement->query, "\n";
254/// // {"collection":"users","operation":"find","filter":{"age":{"$gt":"?"}},"projection":{"name":1,"_id":0},"sort":{"age":-1},"limit":10}
255/// ```
256pub type MongoDb = Builder<MongoDbDialect>;
257
258/// The MongoDB dialect, and its own state: update operators, pipeline
259/// stages, search stages and the index hint.
260#[derive(Debug, Clone, Default)]
261pub struct MongoDbDialect {
262    update_operations: Vec<(UpdateOperator, Array)>,
263    text_search: Option<String>,
264    sample_size: Option<f64>,
265    array_filters: Vec<Array>,
266    bucket: Option<Array>,
267    bucket_auto: Option<Array>,
268    facets: Option<Vec<Facet>>,
269    graph_lookup: Option<Array>,
270    merge: Option<Array>,
271    out: Option<(Option<String>, String)>,
272    replace_root: Option<String>,
273    search: Option<Array>,
274    search_meta: Option<Array>,
275    vector_search: Option<Array>,
276    index_hint: Option<IndexHint>,
277}
278
279const FILTER_HOOKS_UNSUPPORTED: &str = "Filter hooks are not supported on the MongoDB builder: \
280    Utopia\\Query\\Hook\\Filter returns a SQL expression, which has no place in an operation document. \
281    Express the constraint as a Query passed to filter() instead.";
282
283impl Dialect for MongoDbDialect {
284    const CLASS: &'static str = "Utopia\\Query\\Builder\\MongoDB";
285
286    /// Identifiers are field paths: no quoting.
287    fn quote(_b: &Builder<Self>, identifier: &str) -> Result<String> {
288        Ok(identifier.to_owned())
289    }
290
291    fn compile_random(_b: &Builder<Self>) -> String {
292        "$rand".to_owned()
293    }
294
295    fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
296        b.add_binding(first(values), column);
297        Ok(format!("{attribute} REGEX ?"))
298    }
299
300    fn build(b: &mut Builder<Self>) -> Result<Statement> {
301        b.compile_select()
302    }
303
304    fn insert(b: &mut Builder<Self>) -> Result<Statement> {
305        b.compile_insert(false)
306    }
307
308    fn update(b: &mut Builder<Self>) -> Result<Statement> {
309        b.compile_update()
310    }
311
312    fn delete(b: &mut Builder<Self>) -> Result<Statement> {
313        b.compile_delete()
314    }
315
316    fn reset(b: &mut Builder<Self>) {
317        b.dialect = MongoDbDialect::default();
318    }
319
320    /// Filter and join-filter hooks return SQL, which an operation document
321    /// cannot hold: they are refused rather than silently dropped.
322    fn add_hook(b: &mut Builder<Self>, hook: Hook) -> Result<()> {
323        if hook.filter.is_some() || hook.join_filter.is_some() {
324            return Err(Error::Unsupported(FILTER_HOOKS_UNSUPPORTED.to_owned()));
325        }
326        b.base_add_hook(hook);
327        Ok(())
328    }
329
330    /// Refuses empty and `$`-prefixed field names.
331    fn set(b: &mut Builder<Self>, row: Array) -> Result<()> {
332        for key in row.keys() {
333            validate_field_name(&key_text(&key.to_owned()))?;
334        }
335        b.core.rows.push(row);
336        Ok(())
337    }
338}
339
340impl FullTextSearch for MongoDbDialect {
341    /// A `$text` search on the collection's text index (the attribute is ignored).
342    fn filter_search(b: &mut Builder<Self>, _attribute: &str, value: &str) -> Result<()> {
343        b.dialect.text_search = Some(value.to_owned());
344        Ok(())
345    }
346}
347
348impl TableSampling for MongoDbDialect {
349    /// A `$sample` stage of `ceil(percent)` documents (the method is ignored).
350    fn tablesample(b: &mut Builder<Self>, percent: f64, _method: &str) -> Result<()> {
351        b.dialect.sample_size = Some(percent);
352        Ok(())
353    }
354}
355
356impl Upsert for MongoDbDialect {
357    fn upsert(b: &mut Builder<Self>) -> Result<Statement> {
358        b.compile_upsert_one()
359    }
360}
361
362impl InsertOrIgnore for MongoDbDialect {
363    fn insert_or_ignore(b: &mut Builder<Self>) -> Result<Statement> {
364        b.compile_insert(true)
365    }
366}
367
368fn validate_field_name(field: &str) -> Result<()> {
369    if field.is_empty() || field.starts_with('$') {
370        return Err(Error::Validation(format!("Invalid MongoDB field name: {field}")));
371    }
372    Ok(())
373}
374
375/// An array key as the string PHP's `(string)` gives.
376fn key_text(key: &ArrayKey) -> String {
377    match key {
378        ArrayKey::Int(i) => i.to_string(),
379        ArrayKey::Str(s) => String::from_utf8_lossy(s.as_bytes()).into_owned(),
380    }
381}
382
383fn key(name: &str) -> ArrayKey {
384    ArrayKey::from(name)
385}
386
387/// A document of `entries` (keys as PHP array keys).
388fn doc<const N: usize>(entries: [(&str, Value); N]) -> Array {
389    let mut out = Array::with_capacity(N);
390    for (k, v) in entries {
391        out.set(key(k), v);
392    }
393    out
394}
395
396/// `{stage: body}`.
397fn stage(stage: PipelineStage, body: impl Into<Value>) -> Value {
398    Value::Array(doc([(stage.as_str(), body.into())]))
399}
400
401fn append(list: &mut Array, item: Value) {
402    let _ = list.push(item);
403}
404
405fn placeholder() -> Value {
406    value::string("?")
407}
408
409fn quoted(bytes: &[u8]) -> Vec<u8> {
410    php_std::pcre::preg_quote(bytes, Some(b"/"))
411}
412
413/// The nested query a logical or having query holds.
414fn sub_query(value: &Value) -> Result<&Query> {
415    match value {
416        Value::Ext(Object::Query(q)) => Ok(q),
417        other => Err(Error::Type(format!(
418            "Utopia\\Query\\Builder\\MongoDB::buildFilterQuery(): Argument #1 ($query) must be of type Utopia\\Query\\Query, {} given",
419            other.debug_type()
420        ))),
421    }
422}
423
424/// `json_decode($json, true)`, `None` where PHP returns `null`.
425fn decode(json: &str) -> Option<Value> {
426    match json::decode_ext(json.as_bytes(), Some(true), json::DEFAULT_DEPTH, Flags::NONE).ok()? {
427        Value::Null => None,
428        other => Some(other),
429    }
430}
431
432/// `json_encode($operation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)`.
433fn encode(operation: Array) -> Result<String> {
434    value::json_encode(&Value::Array(operation), Flags::THROW_ON_ERROR | Flags::UNESCAPED_SLASHES)
435        .map_err(|e| Error::Json { message: e.message().to_owned(), code: e.code().code() })
436}
437
438/// `isset($array[$name])`.
439fn isset<'a>(value: &'a Value, name: &str) -> Option<&'a Value> {
440    match value {
441        Value::Array(a) => a.get_str(name).filter(|v| !matches!(v, Value::Null)),
442        _ => None,
443    }
444}
445
446/// The pipeline of a decoded operation: an `aggregate`'s pipeline as is, a
447/// `find`'s filter, projection, sort, skip and limit as stages.
448fn operation_to_pipeline(op: &Value) -> Result<Array> {
449    let Value::Array(op) = op else {
450        return Err(Error::Type(format!(
451            "Utopia\\Query\\Builder\\MongoDB::operationToPipeline(): Argument #1 ($op) must be of type array, {} given",
452            op.debug_type()
453        )));
454    };
455    let field = |name: &str| op.get_str(name).filter(|v| !matches!(v, Value::Null));
456    if field("operation").is_some_and(|o| matches!(o, Value::Str(s) if s.as_bytes() == b"aggregate")) {
457        return Ok(match field("pipeline") {
458            Some(Value::Array(pipeline)) => pipeline.clone(),
459            _ => Array::default(),
460        });
461    }
462    let mut pipeline = Array::default();
463    for (name, kind) in
464        [("filter", PipelineStage::Match), ("projection", PipelineStage::Project), ("sort", PipelineStage::Sort)]
465    {
466        if let Some(v) = field(name).filter(|v| v.truthy()) {
467            append(&mut pipeline, stage(kind, v.clone()));
468        }
469    }
470    for (name, kind) in [("skip", PipelineStage::Skip), ("limit", PipelineStage::Limit)] {
471        if let Some(v) = field(name) {
472            append(&mut pipeline, stage(kind, v.clone()));
473        }
474    }
475    Ok(pipeline)
476}
477
478/// The first field a pipeline's `$project` includes (`_id` when none).
479fn extract_projection_field(pipeline: &Array) -> String {
480    for stage in pipeline.values() {
481        if let Some(Value::Array(projection)) = isset(stage, PipelineStage::Project.as_str()) {
482            for (field, value) in projection.iter() {
483                let field = key_text(&field.to_owned());
484                if field != "_id" && matches!(value, Value::Int(1)) {
485                    return field;
486                }
487            }
488        }
489    }
490    "_id".to_owned()
491}
492
493/// The last segment of a dotted field (`users.id` -> `id`).
494fn strip_table_prefix(field: &str) -> &str {
495    field.rsplit('.').next().unwrap_or(field)
496}
497
498/// `/^(\w+)\((.+)\)$/`: the function name and its argument text.
499fn split_call(function: &str) -> Option<(&str, &str)> {
500    let text = function.strip_suffix('\n').unwrap_or(function);
501    let name = text.bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b'_').count();
502    if name == 0 || text.as_bytes().get(name) != Some(&b'(') || !text.ends_with(')') || text.len() < name + 3 {
503        return None;
504    }
505    let inner = &text[name + 1..text.len() - 1];
506    if inner.contains('\n') {
507        return None;
508    }
509    Some((&text[..name], inner))
510}
511
512impl Builder<MongoDbDialect> {
513    fn resolve_filter_field(&mut self, attribute: &str) -> Result<String> {
514        let field = self.resolve_attribute(attribute)?;
515        validate_field_name(&field)?;
516        Ok(field)
517    }
518
519    fn set_update_field(&mut self, operator: UpdateOperator, field: &str, payload: Value) -> Result<&mut Self> {
520        validate_field_name(field)?;
521        let operations = &mut self.dialect.update_operations;
522        let index = match operations.iter().position(|(o, _)| *o == operator) {
523            Some(i) => i,
524            None => {
525                operations.push((operator, Array::default()));
526                operations.len() - 1
527            }
528        };
529        operations[index].1.set(key(field), payload);
530        Ok(self)
531    }
532
533    /// Appends `value` to the array `field` (`$push`).
534    ///
535    /// PHP: `MongoDB::push()`.
536    pub fn push(&mut self, field: &str, value: impl IntoValue) -> Result<&mut Self> {
537        self.set_update_field(UpdateOperator::Push, field, value.into_value())
538    }
539
540    /// Removes `value` (or the elements matching a condition) from the array `field` (`$pull`).
541    ///
542    /// PHP: `MongoDB::pull()`.
543    pub fn pull(&mut self, field: &str, value: impl IntoValue) -> Result<&mut Self> {
544        self.set_update_field(UpdateOperator::Pull, field, value.into_value())
545    }
546
547    /// Adds `value` to the array `field` unless present (`$addToSet`).
548    ///
549    /// PHP: `MongoDB::addToSet()`.
550    pub fn add_to_set(&mut self, field: &str, value: impl IntoValue) -> Result<&mut Self> {
551        self.set_update_field(UpdateOperator::AddToSet, field, value.into_value())
552    }
553
554    /// Adds `amount` (an integer or a float) to `field` (`$inc`).
555    ///
556    /// PHP: `MongoDB::increment()`.
557    pub fn increment(&mut self, field: &str, amount: impl IntoValue) -> Result<&mut Self> {
558        self.set_update_field(UpdateOperator::Increment, field, amount.into_value())
559    }
560
561    /// Removes the fields from the documents (`$unset`).
562    ///
563    /// PHP: `MongoDB::unsetFields()`.
564    pub fn unset_fields<S: AsRef<str>>(&mut self, fields: impl IntoIterator<Item = S>) -> Result<&mut Self> {
565        for field in fields {
566            self.set_update_field(UpdateOperator::Unset, field.as_ref(), value::string(""))?;
567        }
568        Ok(self)
569    }
570
571    /// The index the query uses: a name or a key pattern.
572    ///
573    /// PHP: `MongoDB::hint()`.
574    pub fn hint(&mut self, hint: impl Into<IndexHint>) -> &mut Self {
575        self.dialect.index_hint = Some(hint.into());
576        self
577    }
578
579    /// Renames `old_field` to `new_field` (`$rename`).
580    ///
581    /// PHP: `rename()` (`Feature\MongoDB\FieldUpdates`).
582    pub fn rename(&mut self, old_field: &str, new_field: &str) -> Result<&mut Self> {
583        validate_field_name(old_field)?;
584        validate_field_name(new_field)?;
585        self.set_update_field(UpdateOperator::Rename, old_field, value::string(new_field))
586    }
587
588    /// Multiplies `field` by `factor` (`$mul`).
589    ///
590    /// PHP: `multiply()` (`Feature\MongoDB\FieldUpdates`).
591    pub fn multiply(&mut self, field: &str, factor: impl IntoValue) -> Result<&mut Self> {
592        self.set_update_field(UpdateOperator::Multiply, field, factor.into_value())
593    }
594
595    /// Removes the first element of the array `field` (`$pop: -1`).
596    ///
597    /// PHP: `popFirst()` (`Feature\MongoDB\FieldUpdates`).
598    pub fn pop_first(&mut self, field: &str) -> Result<&mut Self> {
599        self.set_update_field(UpdateOperator::Pop, field, Value::Int(-1))
600    }
601
602    /// Removes the last element of the array `field` (`$pop: 1`).
603    ///
604    /// PHP: `popLast()` (`Feature\MongoDB\FieldUpdates`).
605    pub fn pop_last(&mut self, field: &str) -> Result<&mut Self> {
606        self.set_update_field(UpdateOperator::Pop, field, Value::Int(1))
607    }
608
609    /// Removes every occurrence of `values` from the array `field` (`$pullAll`).
610    ///
611    /// PHP: `pullAll()` (`Feature\MongoDB\FieldUpdates`).
612    pub fn pull_all(&mut self, field: &str, values: impl IntoValues) -> Result<&mut Self> {
613        self.set_update_field(UpdateOperator::PullAll, field, Value::Array(values.into_values()))
614    }
615
616    /// Sets `field` to `value` when `value` is smaller (`$min`).
617    ///
618    /// PHP: `updateMin()` (`Feature\MongoDB\FieldUpdates`).
619    pub fn update_min(&mut self, field: &str, value: impl IntoValue) -> Result<&mut Self> {
620        self.set_update_field(UpdateOperator::Min, field, value.into_value())
621    }
622
623    /// Sets `field` to `value` when `value` is larger (`$max`).
624    ///
625    /// PHP: `updateMax()` (`Feature\MongoDB\FieldUpdates`).
626    pub fn update_max(&mut self, field: &str, value: impl IntoValue) -> Result<&mut Self> {
627        self.set_update_field(UpdateOperator::Max, field, value.into_value())
628    }
629
630    /// Sets `field` to the current date (`type` is `date` or `timestamp`) (`$currentDate`).
631    ///
632    /// PHP: `currentDate()` (`Feature\MongoDB\FieldUpdates`).
633    pub fn current_date(&mut self, field: &str, date_type: &str) -> Result<&mut Self> {
634        self.set_update_field(
635            UpdateOperator::CurrentDate,
636            field,
637            Value::Array(doc([("$type", value::string(date_type))])),
638        )
639    }
640
641    /// Appends each of `values` to the array `field`, at `position`, keeping
642    /// `slice` elements, sorted by `sort` (`$push` with `$each`).
643    ///
644    /// PHP: `pushEach()` (`Feature\MongoDB\ArrayPushModifiers`).
645    ///
646    /// ```
647    /// use utopia_query::Query;
648    /// use utopia_query::builder::MongoDb;
649    ///
650    /// let statement = MongoDb::new()
651    ///     .from("users", "")
652    ///     .filter([Query::equal("_id", ["u1"])])
653    ///     .push_each("scores", [90, 85], None, Some(-5), None)?
654    ///     .increment("visits", 1)?
655    ///     .update()?;
656    /// assert_eq!(
657    ///     statement.query,
658    ///     r#"{"collection":"users","operation":"updateMany","filter":{"_id":"?"},"update":{"$push":{"scores":{"$each":["?","?"],"$slice":-5}},"$inc":{"visits":1}}}"#
659    /// );
660    /// assert_eq!(statement.bindings.len(), 3);
661    /// # Ok::<(), utopia_query::Error>(())
662    /// ```
663    ///
664    /// ```php
665    /// use Utopia\Query\Builder\MongoDB;
666    /// use Utopia\Query\Query;
667    ///
668    /// $statement = (new MongoDB())
669    ///     ->from('users')
670    ///     ->filter([Query::equal('_id', ['u1'])])
671    ///     ->pushEach('scores', [90, 85], slice: -5)
672    ///     ->increment('visits', 1)
673    ///     ->update();
674    /// echo $statement->query, "\n";
675    /// // {"collection":"users","operation":"updateMany","filter":{"_id":"?"},"update":{"$push":{"scores":{"$each":["?","?"],"$slice":-5}},"$inc":{"visits":1}}}
676    /// ```
677    pub fn push_each(
678        &mut self,
679        field: &str,
680        values: impl IntoValues,
681        position: Option<i64>,
682        slice: Option<i64>,
683        sort: Option<Array>,
684    ) -> Result<&mut Self> {
685        let values = Array::from_list(values.into_values().values().cloned().collect());
686        let mut modifier = doc([("values", Value::Array(values))]);
687        if let Some(position) = position {
688            modifier.set(key("position"), Value::Int(position));
689        }
690        if let Some(slice) = slice {
691            modifier.set(key("slice"), Value::Int(slice));
692        }
693        if let Some(sort) = sort {
694            modifier.set(key("sort"), Value::Array(sort));
695        }
696        // Wrapped in an `__each` marker, as PHP stores it: a plain push value
697        // shaped like the marker compiles the same way.
698        self.set_update_field(UpdateOperator::Push, field, Value::Array(doc([("__each", Value::Array(modifier))])))
699    }
700
701    /// Adds an `arrayFilters` condition for a filtered positional update
702    /// (`field.$[identifier]`); the identifier is informational and must be
703    /// the root of the condition's paths.
704    ///
705    /// PHP: `arrayFilter()` (`Feature\MongoDB\ConditionalArrayUpdates`).
706    pub fn array_filter(&mut self, _identifier: &str, condition: Array) -> &mut Self {
707        self.dialect.array_filters.push(condition);
708        self
709    }
710
711    /// A `$bucket` stage grouping by `group_by` between `boundaries`.
712    ///
713    /// PHP: `bucket()` (`Feature\MongoDB\PipelineStages`).
714    pub fn bucket(
715        &mut self,
716        group_by: &str,
717        boundaries: impl IntoValues,
718        default_bucket: Option<&str>,
719        output: Array,
720    ) -> &mut Self {
721        let mut stage = doc([
722            ("groupBy", value::string(format!("${group_by}"))),
723            ("boundaries", Value::Array(boundaries.into_values())),
724        ]);
725        if let Some(default) = default_bucket {
726            stage.set(key("default"), value::string(default));
727        }
728        if !output.is_empty() {
729            stage.set(key("output"), Value::Array(output));
730        }
731        self.dialect.bucket = Some(stage);
732        self
733    }
734
735    /// A `$bucketAuto` stage of `buckets` buckets over `group_by`.
736    ///
737    /// PHP: `bucketAuto()` (`Feature\MongoDB\PipelineStages`).
738    pub fn bucket_auto(&mut self, group_by: &str, buckets: i64, output: Array) -> &mut Self {
739        let mut stage = doc([("groupBy", value::string(format!("${group_by}"))), ("buckets", Value::Int(buckets))]);
740        if !output.is_empty() {
741            stage.set(key("output"), Value::Array(output));
742        }
743        self.dialect.bucket_auto = Some(stage);
744        self
745    }
746
747    /// A `$facet` stage: each named builder (built now) becomes a sub-pipeline.
748    ///
749    /// PHP: `facet()` (`Feature\MongoDB\PipelineStages`).
750    pub fn facet<'a, K: AsRef<str>>(
751        &mut self,
752        facets: impl IntoIterator<Item = (K, &'a mut dyn AnyBuilder)>,
753    ) -> Result<&mut Self> {
754        self.dialect.facets = Some(Vec::new());
755        for (name, builder) in facets {
756            let result = builder.build()?;
757            let op = decode(&result.query)
758                .ok_or_else(|| Error::Validation("Cannot parse facet query for MongoDB.".into()))?;
759            let facet =
760                Facet { name: key(name.as_ref()), pipeline: operation_to_pipeline(&op)?, bindings: result.bindings };
761            if let Some(stages) = self.dialect.facets.as_mut() {
762                stages.push(facet);
763            }
764        }
765        Ok(self)
766    }
767
768    /// A `$graphLookup` stage: a recursive lookup in `from`.
769    ///
770    /// PHP: `graphLookup()` (`Feature\MongoDB\PipelineStages`).
771    #[allow(clippy::too_many_arguments)]
772    pub fn graph_lookup(
773        &mut self,
774        from: &str,
775        start_with: &str,
776        connect_from_field: &str,
777        connect_to_field: &str,
778        as_field: &str,
779        max_depth: Option<i64>,
780        depth_field: Option<&str>,
781    ) -> &mut Self {
782        let mut stage = doc([
783            ("from", value::string(from)),
784            ("startWith", value::string(format!("${start_with}"))),
785            ("connectFromField", value::string(connect_from_field)),
786            ("connectToField", value::string(connect_to_field)),
787            ("as", value::string(as_field)),
788        ]);
789        if let Some(depth) = max_depth {
790            stage.set(key("maxDepth"), Value::Int(depth));
791        }
792        if let Some(field) = depth_field {
793            stage.set(key("depthField"), value::string(field));
794        }
795        self.dialect.graph_lookup = Some(stage);
796        self
797    }
798
799    /// A terminal `$merge` stage into `collection`.
800    ///
801    /// PHP: `mergeIntoCollection()` (`Feature\MongoDB\PipelineStages`).
802    pub fn merge_into_collection(
803        &mut self,
804        collection: &str,
805        on: Option<Array>,
806        when_matched: Option<Array>,
807        when_not_matched: Option<Array>,
808    ) -> &mut Self {
809        let mut stage = doc([("into", value::string(collection))]);
810        for (name, part) in [("on", on), ("whenMatched", when_matched), ("whenNotMatched", when_not_matched)] {
811            if let Some(part) = part {
812                stage.set(key(name), Value::Array(part));
813            }
814        }
815        self.dialect.merge = Some(stage);
816        self
817    }
818
819    /// A terminal `$out` stage into `collection` (of `database`).
820    ///
821    /// PHP: `outputToCollection()` (`Feature\MongoDB\PipelineStages`).
822    pub fn output_to_collection(&mut self, collection: &str, database: Option<&str>) -> &mut Self {
823        self.dialect.out = Some((database.map(str::to_owned), collection.to_owned()));
824        self
825    }
826
827    /// A `$replaceRoot` stage with `new_root_expression` as the new root.
828    ///
829    /// PHP: `replaceRoot()` (`Feature\MongoDB\PipelineStages`).
830    pub fn replace_root(&mut self, new_root_expression: &str) -> &mut Self {
831        self.dialect.replace_root = Some(new_root_expression.to_owned());
832        self
833    }
834
835    /// An Atlas `$search` stage (first in the pipeline), on `index` if given.
836    ///
837    /// PHP: `search()` (`Feature\MongoDB\AtlasSearch`).
838    pub fn search(&mut self, definition: Array, index: Option<&str>) -> &mut Self {
839        self.dialect.search = Some(with_index(definition, index));
840        self
841    }
842
843    /// An Atlas `$searchMeta` stage: the pipeline returns search metadata only.
844    ///
845    /// PHP: `searchMeta()` (`Feature\MongoDB\AtlasSearch`).
846    pub fn search_meta(&mut self, definition: Array, index: Option<&str>) -> &mut Self {
847        self.dialect.search_meta = Some(with_index(definition, index));
848        self
849    }
850
851    /// An Atlas `$vectorSearch` stage over `path`.
852    ///
853    /// PHP: `vectorSearch()` (`Feature\MongoDB\AtlasSearch`).
854    pub fn vector_search(
855        &mut self,
856        path: &str,
857        query_vector: impl IntoValues,
858        num_candidates: i64,
859        limit: i64,
860        index: Option<&str>,
861        filter: Option<Array>,
862    ) -> &mut Self {
863        let mut stage = doc([
864            ("path", value::string(path)),
865            ("queryVector", Value::Array(query_vector.into_values())),
866            ("numCandidates", Value::Int(num_candidates)),
867            ("limit", Value::Int(limit)),
868        ]);
869        if let Some(index) = index {
870            stage.set(key("index"), value::string(index));
871        }
872        if let Some(filter) = filter {
873            stage.set(key("filter"), Value::Array(filter));
874        }
875        self.dialect.vector_search = Some(stage);
876        self
877    }
878
879    fn statement_of(&mut self, operation: Array, read_only: bool) -> Result<Statement> {
880        Ok(Statement::with_parts(
881            encode(operation)?,
882            self.binding_values(),
883            read_only,
884            self.core.executor.clone(),
885            None,
886        ))
887    }
888
889    fn has_random_order(&self) -> bool {
890        !Query::by_type(&self.core.pending, &[Method::OrderRandom]).is_empty()
891    }
892
893    fn compile_select(&mut self) -> Result<Statement> {
894        self.core.bindings.clear();
895        for callback in self.before_build.clone() {
896            callback(self)?;
897        }
898        self.validate_table()?;
899        let grouped = Query::group_by_type(&self.core.pending);
900        let mut result =
901            if self.needs_aggregation(&grouped) { self.build_aggregate(&grouped)? } else { self.build_find(&grouped)? };
902        for callback in self.core.after_build.clone() {
903            result = callback(self.core.owner, result)?;
904        }
905        Ok(result)
906    }
907
908    fn documents(&mut self) -> Array {
909        let mut documents = Array::with_capacity(self.core.rows.len());
910        for row in self.core.rows.clone() {
911            let mut document = Array::with_capacity(row.len());
912            for (column, value) in row.iter() {
913                self.add_binding(value.clone(), None);
914                document.set(column.to_owned(), placeholder());
915            }
916            append(&mut documents, Value::Array(document));
917        }
918        documents
919    }
920
921    fn compile_insert(&mut self, ignore: bool) -> Result<Statement> {
922        self.core.bindings.clear();
923        self.validate_table()?;
924        self.validate_rows("insert")?;
925        let documents = self.documents();
926        let mut operation = doc([
927            ("collection", value::string(&self.core.table)),
928            ("operation", value::string(Operation::InsertMany.as_str())),
929            ("documents", Value::Array(documents)),
930        ]);
931        if ignore {
932            operation.set(key("options"), Value::Array(doc([("ordered", Value::Bool(false))])));
933        }
934        self.statement_of(operation, false)
935    }
936
937    fn compile_update(&mut self) -> Result<Statement> {
938        self.core.bindings.clear();
939        self.validate_table()?;
940        let grouped = Query::group_by_type(&self.core.pending);
941        let filter = self.build_filter(&grouped)?;
942        let update = self.build_update();
943        if update.is_empty() {
944            return Err(Error::Validation("No update operations specified. Call set() before update().".into()));
945        }
946        let mut operation = doc([
947            ("collection", value::string(&self.core.table)),
948            ("operation", value::string(Operation::UpdateMany.as_str())),
949            ("filter", non_empty_or_object(filter)),
950            ("update", Value::Array(update)),
951        ]);
952        if !self.dialect.array_filters.is_empty() {
953            let filters = Array::from_list(self.dialect.array_filters.iter().cloned().map(Value::Array).collect());
954            operation.set(key("options"), Value::Array(doc([("arrayFilters", Value::Array(filters))])));
955        }
956        self.statement_of(operation, false)
957    }
958
959    fn compile_delete(&mut self) -> Result<Statement> {
960        self.core.bindings.clear();
961        self.validate_table()?;
962        let grouped = Query::group_by_type(&self.core.pending);
963        let filter = self.build_filter(&grouped)?;
964        let operation = doc([
965            ("collection", value::string(&self.core.table)),
966            ("operation", value::string(Operation::DeleteMany.as_str())),
967            ("filter", non_empty_or_object(filter)),
968        ]);
969        self.statement_of(operation, false)
970    }
971
972    fn compile_upsert_one(&mut self) -> Result<Statement> {
973        self.core.bindings.clear();
974        self.validate_table()?;
975        self.validate_rows("upsert")?;
976        let row = self.core.rows[0].clone();
977        let mut filter = Array::default();
978        for conflict in self.core.conflict_keys.clone() {
979            let Some(value) = row.get_str(&conflict).filter(|v| !matches!(v, Value::Null)) else {
980                return Err(Error::Validation(format!("Conflict key '{conflict}' not found in row data.")));
981            };
982            self.add_binding(value.clone(), None);
983            filter.set(key(&conflict), placeholder());
984        }
985        let columns: Vec<ArrayKey> = if self.core.conflict_update_columns.is_empty() {
986            row.keys()
987                .map(|k| k.to_owned())
988                .filter(|k| !self.core.conflict_keys.iter().any(|c| *c == key_text(k)))
989                .collect()
990        } else {
991            self.core.conflict_update_columns.iter().map(|c| key(c)).collect()
992        };
993        let mut set = Array::default();
994        for column in columns {
995            self.add_binding(row.get(&column).cloned().unwrap_or(Value::Null), None);
996            set.set(column, placeholder());
997        }
998        let operation = doc([
999            ("collection", value::string(&self.core.table)),
1000            ("operation", value::string(Operation::UpdateOne.as_str())),
1001            ("filter", Value::Array(filter)),
1002            ("update", Value::Array(doc([(UpdateOperator::Set.as_str(), Value::Array(set))]))),
1003            ("options", Value::Array(doc([("upsert", Value::Bool(true))]))),
1004        ]);
1005        self.statement_of(operation, false)
1006    }
1007
1008    fn needs_aggregation(&self, grouped: &ParsedQuery) -> bool {
1009        self.has_random_order() || self.has_pipeline_only_feature(grouped) || self.has_subquery_feature(grouped)
1010    }
1011
1012    fn has_pipeline_only_feature(&self, grouped: &ParsedQuery) -> bool {
1013        let d = &self.dialect;
1014        !grouped.aggregations.is_empty()
1015            || !grouped.group_by.is_empty()
1016            || !grouped.having.is_empty()
1017            || !self.core.window_selects.is_empty()
1018            || grouped.distinct
1019            || d.text_search.is_some()
1020            || d.sample_size.is_some()
1021            || d.bucket.is_some()
1022            || d.bucket_auto.is_some()
1023            || d.facets.is_some()
1024            || d.graph_lookup.is_some()
1025            || d.merge.is_some()
1026            || d.out.is_some()
1027            || d.replace_root.is_some()
1028            || d.search.is_some()
1029            || d.search_meta.is_some()
1030            || d.vector_search.is_some()
1031    }
1032
1033    fn has_subquery_feature(&self, grouped: &ParsedQuery) -> bool {
1034        let c = &self.core;
1035        !grouped.joins.is_empty()
1036            || !c.unions.is_empty()
1037            || !c.ctes.is_empty()
1038            || !c.sub_selects.is_empty()
1039            || !c.raw_selects.is_empty()
1040            || !c.lateral_joins.is_empty()
1041            || !c.where_in_subqueries.is_empty()
1042            || !c.exists_subqueries.is_empty()
1043    }
1044
1045    fn build_find(&mut self, grouped: &ParsedQuery) -> Result<Statement> {
1046        let filter = self.build_filter(grouped)?;
1047        let projection = self.build_projection(grouped)?;
1048        let sort = self.build_sort()?;
1049        let mut operation = doc([
1050            ("collection", value::string(&self.core.table)),
1051            ("operation", value::string(Operation::Find.as_str())),
1052        ]);
1053        if !filter.is_empty() {
1054            operation.set(key("filter"), Value::Array(filter));
1055        }
1056        if !projection.is_empty() {
1057            operation.set(key("projection"), Value::Array(projection));
1058        }
1059        if !sort.is_empty() {
1060            operation.set(key("sort"), Value::Array(sort));
1061        }
1062        if let Some(offset) = grouped.offset {
1063            operation.set(key("skip"), Value::Int(offset));
1064        }
1065        if let Some(limit) = grouped.limit {
1066            operation.set(key("limit"), Value::Int(limit));
1067        }
1068        if let Some(hint) = &self.dialect.index_hint {
1069            operation.set(key("hint"), hint.to_value());
1070        }
1071        self.statement_of(operation, true)
1072    }
1073
1074    fn build_aggregate(&mut self, grouped: &ParsedQuery) -> Result<Statement> {
1075        let mut pipeline = Array::default();
1076        // $searchMeta short-circuits: it returns metadata only.
1077        if let Some(meta) = self.dialect.search_meta.clone() {
1078            append(&mut pipeline, stage(PipelineStage::SearchMeta, meta));
1079            return self.aggregate_statement(pipeline);
1080        }
1081        self.append_search_stages(&mut pipeline);
1082        self.append_join_stages(&mut pipeline, grouped)?;
1083        self.append_filter_stages(&mut pipeline, grouped)?;
1084        self.append_grouping_stages(&mut pipeline, grouped)?;
1085        self.append_window_stages(&mut pipeline)?;
1086        self.append_projection_stage(&mut pipeline, grouped)?;
1087        self.append_union_stages(&mut pipeline)?;
1088        self.append_ordering_stages(&mut pipeline)?;
1089        append_pagination_stages(&mut pipeline, grouped);
1090        self.append_output_stages(&mut pipeline);
1091        self.aggregate_statement(pipeline)
1092    }
1093
1094    fn aggregate_statement(&mut self, pipeline: Array) -> Result<Statement> {
1095        let mut operation = doc([
1096            ("collection", value::string(&self.core.table)),
1097            ("operation", value::string(Operation::Aggregate.as_str())),
1098            ("pipeline", Value::Array(pipeline)),
1099        ]);
1100        if let Some(hint) = &self.dialect.index_hint {
1101            operation.set(key("hint"), hint.to_value());
1102        }
1103        self.statement_of(operation, true)
1104    }
1105
1106    fn append_search_stages(&mut self, pipeline: &mut Array) {
1107        if let Some(search) = self.dialect.search.clone() {
1108            append(pipeline, stage(PipelineStage::Search, search));
1109        }
1110        if let Some(vector) = self.dialect.vector_search.clone() {
1111            append(pipeline, stage(PipelineStage::VectorSearch, vector));
1112        }
1113        if let Some(term) = self.dialect.text_search.clone() {
1114            self.add_binding(value::string(term), None);
1115            let text = doc([(PipelineStage::Text.as_str(), Value::Array(doc([("$search", placeholder())])))]);
1116            append(pipeline, stage(PipelineStage::Match, text));
1117        }
1118        if let Some(size) = self.dialect.sample_size {
1119            let size = php_std::format::dval_to_lval(size.ceil());
1120            append(pipeline, stage(PipelineStage::Sample, doc([("size", Value::Int(size))])));
1121        }
1122    }
1123
1124    fn append_join_stages(&mut self, pipeline: &mut Array, grouped: &ParsedQuery) -> Result<()> {
1125        for join in &grouped.joins {
1126            for stage in self.build_join_stages(join)? {
1127                append(pipeline, stage);
1128            }
1129        }
1130        if let Some(lookup) = self.dialect.graph_lookup.clone() {
1131            append(pipeline, stage(PipelineStage::GraphLookup, lookup));
1132        }
1133        Ok(())
1134    }
1135
1136    fn append_filter_stages(&mut self, pipeline: &mut Array, grouped: &ParsedQuery) -> Result<()> {
1137        for (index, sub) in self.core.where_in_subqueries.clone().into_iter().enumerate() {
1138            self.append_where_in_subquery(pipeline, sub.column.as_str(), sub.subquery, sub.not, index)?;
1139        }
1140        for (index, sub) in self.core.exists_subqueries.clone().into_iter().enumerate() {
1141            self.append_exists_subquery(pipeline, sub.subquery, sub.not, index)?;
1142        }
1143        let filter = self.build_filter(grouped)?;
1144        if !filter.is_empty() {
1145            append(pipeline, stage(PipelineStage::Match, filter));
1146        }
1147        Ok(())
1148    }
1149
1150    fn append_grouping_stages(&mut self, pipeline: &mut Array, grouped: &ParsedQuery) -> Result<()> {
1151        if grouped.distinct && grouped.group_by.is_empty() && grouped.aggregations.is_empty() {
1152            self.append_distinct(pipeline, grouped)?;
1153        }
1154        if let Some(bucket) = self.dialect.bucket.clone() {
1155            append(pipeline, stage(PipelineStage::Bucket, bucket));
1156        } else if let Some(bucket) = self.dialect.bucket_auto.clone() {
1157            append(pipeline, stage(PipelineStage::BucketAuto, bucket));
1158        } else if !grouped.group_by.is_empty() || !grouped.aggregations.is_empty() {
1159            append(pipeline, stage(PipelineStage::Group, build_group(grouped)?));
1160            let reshape = build_project_from_group(grouped)?;
1161            if !reshape.is_empty() {
1162                append(pipeline, stage(PipelineStage::Project, reshape));
1163            }
1164        }
1165        if let Some(root) = self.dialect.replace_root.clone() {
1166            append(pipeline, stage(PipelineStage::ReplaceRoot, doc([("newRoot", value::string(root))])));
1167        }
1168        if !grouped.having.is_empty() || !self.core.raw_havings.is_empty() {
1169            let having = self.build_having(grouped)?;
1170            if !having.is_empty() {
1171                append(pipeline, stage(PipelineStage::Match, having));
1172            }
1173        }
1174        Ok(())
1175    }
1176
1177    fn append_window_stages(&mut self, pipeline: &mut Array) -> Result<()> {
1178        for window in self.core.window_selects.clone() {
1179            append(pipeline, build_window_stage(&window)?);
1180        }
1181        Ok(())
1182    }
1183
1184    fn append_projection_stage(&mut self, pipeline: &mut Array, grouped: &ParsedQuery) -> Result<()> {
1185        if !grouped.group_by.is_empty() || !grouped.aggregations.is_empty() || grouped.distinct {
1186            return Ok(());
1187        }
1188        if self.dialect.bucket.is_some() || self.dialect.bucket_auto.is_some() {
1189            return Ok(());
1190        }
1191        let mut projection = self.build_projection(grouped)?;
1192        if projection.is_empty() {
1193            return Ok(());
1194        }
1195        // Window function outputs stay in the projection.
1196        for window in &self.core.window_selects {
1197            projection.set(key(&window.alias), Value::Int(1));
1198        }
1199        append(pipeline, stage(PipelineStage::Project, projection));
1200        Ok(())
1201    }
1202
1203    fn append_union_stages(&mut self, pipeline: &mut Array) -> Result<()> {
1204        if let Some(facets) = self.dialect.facets.clone() {
1205            let mut facet = Array::with_capacity(facets.len());
1206            for entry in facets {
1207                facet.set(entry.name, Value::Array(entry.pipeline));
1208                self.add_bindings(entry.bindings);
1209            }
1210            append(pipeline, stage(PipelineStage::Facet, facet));
1211        }
1212        for union in self.core.unions.clone() {
1213            let op = decode(&union.query)
1214                .ok_or_else(|| Error::Validation("Cannot parse union query for MongoDB.".into()))?;
1215            let sub_pipeline = operation_to_pipeline(&op)?;
1216            let collection = match &op {
1217                Value::Array(a) => a.get_str("collection").cloned().unwrap_or(Value::Null),
1218                _ => Value::Null,
1219            };
1220            let mut union_with = doc([("coll", collection)]);
1221            if !sub_pipeline.is_empty() {
1222                union_with.set(key("pipeline"), Value::Array(sub_pipeline));
1223            }
1224            append(pipeline, stage(PipelineStage::UnionWith, union_with));
1225            self.add_bindings(union.bindings);
1226        }
1227        Ok(())
1228    }
1229
1230    fn append_ordering_stages(&mut self, pipeline: &mut Array) -> Result<()> {
1231        let random = self.has_random_order();
1232        if random {
1233            let rand = doc([("$rand", Value::Object(Array::default()))]);
1234            append(pipeline, stage(PipelineStage::AddFields, doc([("_rand", Value::Array(rand))])));
1235        }
1236        let mut sort = self.build_sort()?;
1237        if random {
1238            sort.set(key("_rand"), Value::Int(1));
1239        }
1240        if !sort.is_empty() {
1241            append(pipeline, stage(PipelineStage::Sort, sort));
1242        }
1243        if random {
1244            append(pipeline, stage(PipelineStage::Unset, value::string("_rand")));
1245        }
1246        Ok(())
1247    }
1248
1249    fn append_output_stages(&self, pipeline: &mut Array) {
1250        if let Some(merge) = self.dialect.merge.clone() {
1251            append(pipeline, stage(PipelineStage::Merge, merge));
1252            return;
1253        }
1254        if let Some((database, collection)) = &self.dialect.out {
1255            let out = match database {
1256                Some(db) => Value::Array(doc([("db", value::string(db)), ("coll", value::string(collection))])),
1257                None => value::string(collection),
1258            };
1259            append(pipeline, stage(PipelineStage::Out, out));
1260        }
1261    }
1262
1263    fn build_filter(&mut self, grouped: &ParsedQuery) -> Result<Array> {
1264        let mut conditions = Vec::with_capacity(grouped.filters.len());
1265        for filter in &grouped.filters {
1266            conditions.push(self.build_filter_query(filter)?);
1267        }
1268        Ok(combine(conditions, "$and"))
1269    }
1270
1271    fn build_filter_query(&mut self, query: &Query) -> Result<Array> {
1272        match query.method() {
1273            Method::And => self.build_logical(query, "$and"),
1274            Method::Or => self.build_logical(query, "$or"),
1275            Method::Exists => self.build_field_exists(query, true),
1276            Method::NotExists => self.build_field_exists(query, false),
1277            _ => self.build_field_filter(query),
1278        }
1279    }
1280
1281    fn build_field_filter(&mut self, query: &Query) -> Result<Array> {
1282        let method = query.method();
1283        let attribute = self.resolve_filter_field(query.attribute())?;
1284        let values = query.values();
1285        use Method::*;
1286        match method {
1287            Equal => Ok(self.build_in(&attribute, values)),
1288            NotEqual => Ok(self.build_not_in(&attribute, values)),
1289            LessThan => Ok(self.build_comparison(&attribute, "$lt", values)),
1290            LessThanEqual => Ok(self.build_comparison(&attribute, "$lte", values)),
1291            GreaterThan => Ok(self.build_comparison(&attribute, "$gt", values)),
1292            GreaterThanEqual => Ok(self.build_comparison(&attribute, "$gte", values)),
1293            Between => Ok(self.build_between(&attribute, values, false)),
1294            NotBetween => Ok(self.build_between(&attribute, values, true)),
1295            StartsWith => self.build_regex_filter(&attribute, values, "^", "", false),
1296            NotStartsWith => self.build_regex_filter(&attribute, values, "^", "", true),
1297            EndsWith => self.build_regex_filter(&attribute, values, "", "$", false),
1298            NotEndsWith => self.build_regex_filter(&attribute, values, "", "$", true),
1299            Contains => self.build_contains(&attribute, values),
1300            ContainsAny => {
1301                if query.on_array() {
1302                    Ok(self.build_in(&attribute, values))
1303                } else {
1304                    self.build_contains(&attribute, values)
1305                }
1306            }
1307            ContainsAll => self.build_contains_each(&attribute, values, false),
1308            NotContains => self.build_not_contains(&attribute, values),
1309            Regex => {
1310                self.add_binding(first(values), None);
1311                Ok(field_doc(&attribute, Value::Array(doc([("$regex", placeholder())]))))
1312            }
1313            IsNull => Ok(field_doc(&attribute, Value::Null)),
1314            IsNotNull => Ok(field_doc(&attribute, Value::Array(doc([("$ne", Value::Null)])))),
1315            other => Err(Error::Unsupported(format!("Unsupported filter type for MongoDB: {}", other.as_str()))),
1316        }
1317    }
1318
1319    fn bind_placeholders(&mut self, values: Vec<Value>) -> Value {
1320        let mut placeholders = Array::with_capacity(values.len());
1321        for value in values {
1322            self.add_binding(value, None);
1323            append(&mut placeholders, placeholder());
1324        }
1325        Value::Array(placeholders)
1326    }
1327
1328    fn build_in(&mut self, attribute: &str, values: &Array) -> Array {
1329        let has_null = values.values().any(|v| matches!(v, Value::Null));
1330        let mut non_nulls: Vec<Value> = values.values().filter(|v| !matches!(v, Value::Null)).cloned().collect();
1331        if has_null && non_nulls.is_empty() {
1332            return field_doc(attribute, Value::Null);
1333        }
1334        if non_nulls.len() == 1 && !has_null {
1335            self.add_binding(non_nulls.remove(0), None);
1336            return field_doc(attribute, placeholder());
1337        }
1338        let placeholders = self.bind_placeholders(non_nulls);
1339        let in_ = field_doc(attribute, Value::Array(doc([("$in", placeholders)])));
1340        if has_null {
1341            let either = Array::from_list(vec![Value::Array(in_), Value::Array(field_doc(attribute, Value::Null))]);
1342            return doc([("$or", Value::Array(either))]);
1343        }
1344        in_
1345    }
1346
1347    fn build_not_in(&mut self, attribute: &str, values: &Array) -> Array {
1348        let has_null = values.values().any(|v| matches!(v, Value::Null));
1349        let mut non_nulls: Vec<Value> = values.values().filter(|v| !matches!(v, Value::Null)).cloned().collect();
1350        let not_null = || Value::Array(doc([("$ne", Value::Null)]));
1351        if has_null && non_nulls.is_empty() {
1352            return field_doc(attribute, not_null());
1353        }
1354        if non_nulls.len() == 1 && !has_null {
1355            self.add_binding(non_nulls.remove(0), None);
1356            return field_doc(attribute, Value::Array(doc([("$ne", placeholder())])));
1357        }
1358        let placeholders = self.bind_placeholders(non_nulls);
1359        let nin = field_doc(attribute, Value::Array(doc([("$nin", placeholders)])));
1360        if has_null {
1361            let both = Array::from_list(vec![Value::Array(nin), Value::Array(field_doc(attribute, not_null()))]);
1362            return doc([("$and", Value::Array(both))]);
1363        }
1364        nin
1365    }
1366
1367    fn build_comparison(&mut self, attribute: &str, operator: &str, values: &Array) -> Array {
1368        self.add_binding(first(values), None);
1369        field_doc(attribute, Value::Array(doc([(operator, placeholder())])))
1370    }
1371
1372    fn build_between(&mut self, attribute: &str, values: &Array, not: bool) -> Array {
1373        self.add_binding(first(values), None);
1374        self.add_binding(values.get(&ArrayKey::Int(1)).cloned().unwrap_or(Value::Null), None);
1375        if not {
1376            let either = Array::from_list(vec![
1377                Value::Array(field_doc(attribute, Value::Array(doc([("$lt", placeholder())])))),
1378                Value::Array(field_doc(attribute, Value::Array(doc([("$gt", placeholder())])))),
1379            ]);
1380            return doc([("$or", Value::Array(either))]);
1381        }
1382        field_doc(attribute, Value::Array(doc([("$gte", placeholder()), ("$lte", placeholder())])))
1383    }
1384
1385    fn build_regex_filter(
1386        &mut self,
1387        attribute: &str,
1388        values: &Array,
1389        prefix: &str,
1390        suffix: &str,
1391        not: bool,
1392    ) -> Result<Array> {
1393        const STR: Param<'static> = Param::internal("preg_quote", 1, "str");
1394        let raw = first(values);
1395        let raw = STR.bytes(&raw)?;
1396        let mut pattern = prefix.as_bytes().to_vec();
1397        pattern.extend(quoted(&raw));
1398        pattern.extend_from_slice(suffix.as_bytes());
1399        self.add_binding(value::string(pattern), None);
1400        Ok(field_doc(attribute, regex_condition(not)))
1401    }
1402
1403    /// `preg_quote((string) $value, '/')` as a binding.
1404    fn bind_pattern(&mut self, value: &Value) -> Result<()> {
1405        let pattern = quoted(&value::concat_bytes(value)?);
1406        self.add_binding(value::string(pattern), None);
1407        Ok(())
1408    }
1409
1410    fn build_contains(&mut self, attribute: &str, values: &Array) -> Result<Array> {
1411        if values.len() == 1 {
1412            self.bind_pattern(&first(values))?;
1413            return Ok(field_doc(attribute, regex_condition(false)));
1414        }
1415        let mut conditions = Array::with_capacity(values.len());
1416        for value in values.values() {
1417            self.bind_pattern(value)?;
1418            append(&mut conditions, Value::Array(field_doc(attribute, regex_condition(false))));
1419        }
1420        Ok(doc([("$or", Value::Array(conditions))]))
1421    }
1422
1423    fn build_contains_each(&mut self, attribute: &str, values: &Array, not: bool) -> Result<Array> {
1424        let mut conditions = Array::with_capacity(values.len());
1425        for value in values.values() {
1426            self.bind_pattern(value)?;
1427            append(&mut conditions, Value::Array(field_doc(attribute, regex_condition(not))));
1428        }
1429        Ok(doc([("$and", Value::Array(conditions))]))
1430    }
1431
1432    fn build_not_contains(&mut self, attribute: &str, values: &Array) -> Result<Array> {
1433        if values.len() == 1 {
1434            self.bind_pattern(&first(values))?;
1435            return Ok(field_doc(attribute, regex_condition(true)));
1436        }
1437        self.build_contains_each(attribute, values, true)
1438    }
1439
1440    fn build_logical(&mut self, query: &Query, operator: &str) -> Result<Array> {
1441        let mut conditions = Array::with_capacity(query.values().len());
1442        for value in query.values().values() {
1443            let condition = self.build_filter_query(sub_query(value)?)?;
1444            append(&mut conditions, Value::Array(condition));
1445        }
1446        if conditions.is_empty() {
1447            return Ok(if operator == "$or" { doc([("$expr", Value::Bool(false))]) } else { Array::default() });
1448        }
1449        Ok(doc([(operator, Value::Array(conditions))]))
1450    }
1451
1452    /// SQL parity: `IS NOT NULL` is a present non-null value
1453    /// (`{$exists: true, $ne: null}`), `IS NULL` an explicit null (`{$type: 10}`).
1454    fn build_field_exists(&mut self, query: &Query, exists: bool) -> Result<Array> {
1455        let mut conditions = Vec::with_capacity(query.values().len());
1456        const FIELD: Param<'static> = Param::method(
1457            "Utopia\\Query\\Builder\\MongoDB::resolveFilterField",
1458            1,
1459            "attribute",
1460            "Builder/MongoDB.php",
1461            1159,
1462        );
1463        for attribute in query.values().values() {
1464            let field = self.resolve_filter_field(&FIELD.string(attribute)?)?;
1465            let condition = if exists {
1466                doc([("$exists", Value::Bool(true)), ("$ne", Value::Null)])
1467            } else {
1468                doc([("$type", Value::Int(10))])
1469            };
1470            conditions.push(field_doc(&field, Value::Array(condition)));
1471        }
1472        if conditions.len() == 1 {
1473            return Ok(conditions.remove(0));
1474        }
1475        Ok(doc([("$and", Value::Array(Array::from_list(conditions.into_iter().map(Value::Array).collect())))]))
1476    }
1477
1478    fn build_projection(&mut self, grouped: &ParsedQuery) -> Result<Array> {
1479        let Some(selection) = grouped.selections.first() else {
1480            return Ok(Array::default());
1481        };
1482        const FIELD: Param<'static> =
1483            Param::method("Utopia\\Query\\Builder::resolveAttribute", 1, "attribute", "Builder/MongoDB.php", 1188);
1484        let mut projection = Array::with_capacity(selection.values().len() + 1);
1485        for field in selection.values().values() {
1486            let resolved = self.resolve_attribute(&FIELD.string(field)?)?;
1487            projection.set(key(&resolved), Value::Int(1));
1488        }
1489        if !projection.contains_key(&key("_id")) {
1490            projection.set(key("_id"), Value::Int(0));
1491        }
1492        Ok(projection)
1493    }
1494
1495    fn build_sort(&mut self) -> Result<Array> {
1496        let mut sort = Array::default();
1497        let orders: Vec<Query> =
1498            Query::by_type(&self.core.pending, &[Method::OrderAsc, Method::OrderDesc]).into_iter().cloned().collect();
1499        for order in &orders {
1500            let attribute = self.resolve_attribute(order.attribute())?;
1501            let direction = if order.method() == Method::OrderAsc { 1 } else { -1 };
1502            sort.set(key(&attribute), Value::Int(direction));
1503        }
1504        Ok(sort)
1505    }
1506
1507    fn build_join_stages(&mut self, join: &Query) -> Result<Vec<Value>> {
1508        let table = join.attribute();
1509        if matches!(join.method(), Method::CrossJoin | Method::NaturalJoin) {
1510            return Err(Error::Unsupported(
1511                "Cross and natural joins cannot be expressed as a MongoDB $lookup. Reached via \
1512                 queries([Query::crossJoin(...)]); the MongoDB builder does not implement Feature\\CrossJoins."
1513                    .into(),
1514            ));
1515        }
1516        let conditions = join.join_on_queries();
1517        let Some(condition) = conditions.first() else {
1518            return Err(Error::Validation("Join query must have values.".into()));
1519        };
1520        if conditions.len() > 1 || condition.method() != Method::On {
1521            return Err(Error::Unsupported(
1522                "MongoDB $lookup in localField/foreignField form only supports a single on() condition. \
1523                 Use a pipeline-form $lookup via a raw stage for filtered joins."
1524                    .into(),
1525            ));
1526        }
1527        let (left, operator, right) = on_values(condition);
1528        let alias = if join.alias().is_empty() { table } else { join.alias() };
1529        if is_empty_string(&left) || is_empty_string(&right) {
1530            return Err(Error::Validation("Join ON requires left and right columns".into()));
1531        }
1532        if !matches!(&operator, Value::Str(s) if s.as_bytes() == b"=") {
1533            return Err(Error::Unsupported(format!(
1534                "MongoDB $lookup in localField/foreignField form only supports equality joins. Got operator \
1535                 '{}'. Use a pipeline-form $lookup via a raw stage for non-equality joins.",
1536                value::concat(&operator)?
1537            )));
1538        }
1539        let field = |line: u32, value: &Value| -> Result<String> {
1540            let param = Param::method(
1541                "Utopia\\Query\\Builder\\MongoDB::stripTablePrefix",
1542                1,
1543                "field",
1544                "Builder/MongoDB.php",
1545                line,
1546            );
1547            Ok(strip_table_prefix(&param.string(value)?).to_owned())
1548        };
1549        let local = field(1340, &left)?;
1550        let foreign = field(1341, &right)?;
1551        let lookup = doc([
1552            ("from", value::string(table)),
1553            ("localField", value::string(local)),
1554            ("foreignField", value::string(foreign)),
1555            ("as", value::string(alias)),
1556        ]);
1557        let path = value::string(format!("${alias}"));
1558        let unwind = if join.method() == Method::LeftJoin {
1559            Value::Array(doc([("path", path), ("preserveNullAndEmptyArrays", Value::Bool(true))]))
1560        } else {
1561            path
1562        };
1563        Ok(vec![stage(PipelineStage::Lookup, lookup), stage(PipelineStage::Unwind, unwind)])
1564    }
1565
1566    fn append_distinct(&mut self, pipeline: &mut Array, grouped: &ParsedQuery) -> Result<()> {
1567        let Some(selection) = grouped.selections.first() else {
1568            return Ok(());
1569        };
1570        const FIELD: Param<'static> =
1571            Param::method("Utopia\\Query\\Builder::resolveAttribute", 1, "attribute", "Builder/MongoDB.php", 1375);
1572        // Each attribute resolved once, kept by the field as an array key
1573        // (`$resolved[$field]`): fields sharing a key share the last resolution.
1574        let mut by_key = Array::with_capacity(selection.values().len());
1575        for field in selection.values().values() {
1576            let name = self.resolve_attribute(&FIELD.string(field)?)?;
1577            by_key.set(value::array_key(field)?, value::string(name));
1578        }
1579        let mut resolved = Vec::with_capacity(selection.values().len());
1580        for field in selection.values().values() {
1581            resolved.push(value::to_php_string(by_key.get(&value::array_key(field)?).unwrap_or(&Value::Null)));
1582        }
1583        let mut id = Array::with_capacity(resolved.len());
1584        for field in &resolved {
1585            id.set(key(field), value::string(format!("${field}")));
1586        }
1587        append(pipeline, stage(PipelineStage::Group, doc([("_id", Value::Array(id))])));
1588        let mut project = doc([("_id", Value::Int(0))]);
1589        for field in &resolved {
1590            project.set(key(field), value::string(format!("$_id.{field}")));
1591        }
1592        append(pipeline, stage(PipelineStage::Project, project));
1593        Ok(())
1594    }
1595
1596    fn build_having(&mut self, grouped: &ParsedQuery) -> Result<Array> {
1597        let mut conditions = Vec::new();
1598        for having in &grouped.having {
1599            for value in having.values().values() {
1600                conditions.push(self.build_filter_query(sub_query(value)?)?);
1601            }
1602        }
1603        Ok(combine(conditions, "$and"))
1604    }
1605
1606    fn append_where_in_subquery(
1607        &mut self,
1608        pipeline: &mut Array,
1609        column: &str,
1610        mut subquery: Box<dyn AnyBuilder>,
1611        not: bool,
1612        index: usize,
1613    ) -> Result<()> {
1614        let result = subquery.build()?;
1615        let op = decode(&result.query)
1616            .ok_or_else(|| Error::Validation("Cannot parse subquery for MongoDB WHERE IN.".into()))?;
1617        self.add_bindings(result.bindings);
1618        let collection = sub_collection(&op);
1619        let sub_pipeline = operation_to_pipeline(&op)?;
1620        let sub_field = extract_projection_field(&sub_pipeline);
1621        let lookup_alias = format!("_sub_{index}");
1622        let ids = format!("_sub_ids_{index}");
1623        append(
1624            pipeline,
1625            stage(
1626                PipelineStage::Lookup,
1627                doc([
1628                    ("from", collection),
1629                    ("pipeline", Value::Array(sub_pipeline)),
1630                    ("as", value::string(&lookup_alias)),
1631                ]),
1632            ),
1633        );
1634        let map = doc([
1635            ("input", value::string(format!("${lookup_alias}"))),
1636            ("as", value::string("s")),
1637            ("in", value::string(format!("$$s.{sub_field}"))),
1638        ]);
1639        append(
1640            pipeline,
1641            stage(PipelineStage::AddFields, doc([(ids.as_str(), Value::Array(doc([("$map", Value::Array(map))])))])),
1642        );
1643        let column = self.resolve_attribute(column)?;
1644        let operands = Array::from_list(vec![value::string(format!("${column}")), value::string(format!("${ids}"))]);
1645        let in_ = Value::Array(doc([("$in", Value::Array(operands))]));
1646        let expr = if not { Value::Array(doc([("$not", in_)])) } else { in_ };
1647        append(pipeline, stage(PipelineStage::Match, doc([("$expr", expr)])));
1648        let unset = Array::from_list(vec![value::string(&lookup_alias), value::string(&ids)]);
1649        append(pipeline, stage(PipelineStage::Unset, Value::Array(unset)));
1650        Ok(())
1651    }
1652
1653    fn append_exists_subquery(
1654        &mut self,
1655        pipeline: &mut Array,
1656        mut subquery: Box<dyn AnyBuilder>,
1657        not: bool,
1658        index: usize,
1659    ) -> Result<()> {
1660        let result = subquery.build()?;
1661        let op = decode(&result.query)
1662            .ok_or_else(|| Error::Validation("Cannot parse subquery for MongoDB EXISTS.".into()))?;
1663        self.add_bindings(result.bindings);
1664        let collection = sub_collection(&op);
1665        let mut sub_pipeline = operation_to_pipeline(&op)?;
1666        // An existence check needs one document.
1667        if !sub_pipeline.values().any(|s| isset(s, PipelineStage::Limit.as_str()).is_some()) {
1668            append(&mut sub_pipeline, stage(PipelineStage::Limit, Value::Int(1)));
1669        }
1670        let alias = format!("_exists_{index}");
1671        append(
1672            pipeline,
1673            stage(
1674                PipelineStage::Lookup,
1675                doc([("from", collection), ("pipeline", Value::Array(sub_pipeline)), ("as", value::string(&alias))]),
1676            ),
1677        );
1678        let condition =
1679            if not { doc([("$size", Value::Int(0))]) } else { doc([("$ne", Value::Array(Array::default()))]) };
1680        append(pipeline, stage(PipelineStage::Match, field_doc(&alias, Value::Array(condition))));
1681        append(pipeline, stage(PipelineStage::Unset, value::string(&alias)));
1682        Ok(())
1683    }
1684
1685    fn build_update(&mut self) -> Array {
1686        let mut update = Array::default();
1687        if let Some(row) = self.core.rows.first().cloned() {
1688            let mut set = Array::with_capacity(row.len());
1689            for (column, value) in row.iter() {
1690                self.add_binding(value.clone(), None);
1691                set.set(column.to_owned(), placeholder());
1692            }
1693            update.set(key(UpdateOperator::Set.as_str()), Value::Array(set));
1694        }
1695        for (operator, fields) in self.dialect.update_operations.clone() {
1696            if fields.is_empty() {
1697                continue;
1698            }
1699            let payload = match operator {
1700                UpdateOperator::Push => self.emit_push_fields(&fields),
1701                UpdateOperator::Pull | UpdateOperator::AddToSet | UpdateOperator::Min | UpdateOperator::Max => {
1702                    self.emit_bound_values(&fields)
1703                }
1704                UpdateOperator::PullAll => self.emit_pull_all_fields(&fields),
1705                _ => fields,
1706            };
1707            update.set(key(operator.as_str()), Value::Array(payload));
1708        }
1709        update
1710    }
1711
1712    fn emit_push_fields(&mut self, fields: &Array) -> Array {
1713        let mut push = Array::with_capacity(fields.len());
1714        for (field, value) in fields.iter() {
1715            let modifier = match value {
1716                Value::Array(a) => a.get_str("__each").cloned(),
1717                _ => None,
1718            };
1719            let Some(modifier) = modifier else {
1720                self.add_binding(value.clone(), None);
1721                push.set(field.to_owned(), placeholder());
1722                continue;
1723            };
1724            let entry = |name: &str| isset(&modifier, name).cloned();
1725            let mut each = Array::default();
1726            if let Some(Value::Array(values)) = entry("values") {
1727                for value in values.values() {
1728                    self.add_binding(value.clone(), None);
1729                    append(&mut each, placeholder());
1730                }
1731            }
1732            let mut each_doc = doc([("$each", Value::Array(each))]);
1733            for (name, modifier_key) in [("position", "$position"), ("slice", "$slice"), ("sort", "$sort")] {
1734                if let Some(value) = entry(name) {
1735                    each_doc.set(key(modifier_key), value);
1736                }
1737            }
1738            push.set(field.to_owned(), Value::Array(each_doc));
1739        }
1740        push
1741    }
1742
1743    fn emit_bound_values(&mut self, fields: &Array) -> Array {
1744        let mut out = Array::with_capacity(fields.len());
1745        for (field, value) in fields.iter() {
1746            self.add_binding(value.clone(), None);
1747            out.set(field.to_owned(), placeholder());
1748        }
1749        out
1750    }
1751
1752    fn emit_pull_all_fields(&mut self, fields: &Array) -> Array {
1753        let mut out = Array::with_capacity(fields.len());
1754        for (field, values) in fields.iter() {
1755            let mut placeholders = Array::default();
1756            if let Value::Array(values) = values {
1757                for value in values.values() {
1758                    self.add_binding(value.clone(), None);
1759                    append(&mut placeholders, placeholder());
1760                }
1761            }
1762            out.set(field.to_owned(), Value::Array(placeholders));
1763        }
1764        out
1765    }
1766}
1767
1768/// `$definition` with `index` set when given.
1769fn with_index(mut definition: Array, index: Option<&str>) -> Array {
1770    if let Some(index) = index {
1771        definition.set(key("index"), value::string(index));
1772    }
1773    definition
1774}
1775
1776/// `{field: value}`.
1777fn field_doc(field: &str, value: Value) -> Array {
1778    doc([(field, value)])
1779}
1780
1781/// `{$regex: ?}` or `{$not: {$regex: ?}}`.
1782fn regex_condition(not: bool) -> Value {
1783    let regex = Value::Array(doc([("$regex", placeholder())]));
1784    if not { Value::Array(doc([("$not", regex)])) } else { regex }
1785}
1786
1787/// The filter, or `{}` when empty.
1788fn non_empty_or_object(filter: Array) -> Value {
1789    if filter.is_empty() { Value::Object(Array::default()) } else { Value::Array(filter) }
1790}
1791
1792/// No conditions: empty; one: itself; more: `{operator: [...]}`.
1793fn combine(mut conditions: Vec<Array>, operator: &str) -> Array {
1794    match conditions.len() {
1795        0 => Array::default(),
1796        1 => conditions.remove(0),
1797        _ => doc([(operator, Value::Array(Array::from_list(conditions.into_iter().map(Value::Array).collect())))]),
1798    }
1799}
1800
1801/// `$subOp['collection'] ?? ''`.
1802fn sub_collection(op: &Value) -> Value {
1803    isset(op, "collection").cloned().unwrap_or_else(|| value::string(""))
1804}
1805
1806fn append_pagination_stages(pipeline: &mut Array, grouped: &ParsedQuery) {
1807    if let Some(offset) = grouped.offset {
1808        append(pipeline, stage(PipelineStage::Skip, Value::Int(offset)));
1809    }
1810    if let Some(limit) = grouped.limit {
1811        append(pipeline, stage(PipelineStage::Limit, Value::Int(limit)));
1812    }
1813}
1814
1815fn aggregate_alias(aggregate: &Query) -> String {
1816    if aggregate.alias().is_empty() { aggregate.method().as_str().to_owned() } else { aggregate.alias().to_owned() }
1817}
1818
1819fn build_group(grouped: &ParsedQuery) -> Result<Array> {
1820    let id = match grouped.group_by.as_slice() {
1821        [] => Value::Null,
1822        [column] => value::string(format!("${}", value::concat(column)?)),
1823        columns => {
1824            let mut id = Array::with_capacity(columns.len());
1825            for column in columns {
1826                let path = value::string(format!("${}", value::concat(column)?));
1827                id.set(value::array_key(column)?, path);
1828            }
1829            Value::Array(id)
1830        }
1831    };
1832    let mut group = doc([("_id", id)]);
1833    for aggregate in &grouped.aggregations {
1834        let method = aggregate.method();
1835        let column = || value::string(format!("${}", aggregate.attribute()));
1836        let accumulator = match method {
1837            Method::Count => doc([("$sum", Value::Int(1))]),
1838            Method::Sum => doc([("$sum", column())]),
1839            Method::Avg => doc([("$avg", column())]),
1840            Method::Min => doc([("$min", column())]),
1841            Method::Max => doc([("$max", column())]),
1842            other => {
1843                return Err(Error::Unsupported(format!("Unsupported aggregation for MongoDB: {}", other.as_str())));
1844            }
1845        };
1846        group.set(key(&aggregate_alias(aggregate)), Value::Array(accumulator));
1847    }
1848    Ok(group)
1849}
1850
1851/// After `$group`, the `_id` fields flattened back to the top level.
1852fn build_project_from_group(grouped: &ParsedQuery) -> Result<Array> {
1853    let mut project = doc([("_id", Value::Int(0))]);
1854    match grouped.group_by.as_slice() {
1855        [] => {}
1856        [column] => {
1857            project.set(value::array_key(column)?, value::string("$_id"));
1858        }
1859        columns => {
1860            for column in columns {
1861                let path = value::string(format!("$_id.{}", value::concat(column)?));
1862                project.set(value::array_key(column)?, path);
1863            }
1864        }
1865    }
1866    for aggregate in &grouped.aggregations {
1867        project.set(key(&aggregate_alias(aggregate)), Value::Int(1));
1868    }
1869    Ok(project)
1870}
1871
1872/// A `$setWindowFields` stage for a window function.
1873fn build_window_stage(window: &WindowSelect) -> Result<Value> {
1874    let function = &window.function;
1875    let name = function.trim_matches(['(', ')']).to_ascii_lowercase();
1876    let ranking = match name.as_str() {
1877        "row_number" => Some("$documentNumber"),
1878        "rank" => Some("$rank"),
1879        "dense_rank" => Some("$denseRank"),
1880        _ => None,
1881    };
1882    let order_by = window.order_by.as_ref().filter(|o| !o.is_empty());
1883    let output = match ranking {
1884        Some(operator) => {
1885            if order_by.is_none() {
1886                return Err(Error::Validation(format!(
1887                    "Window function '{function}' requires an ORDER BY clause on MongoDB."
1888                )));
1889            }
1890            doc([(operator, Value::Object(Array::default()))])
1891        }
1892        None => {
1893            let Some((aggregate, argument)) = split_call(function) else {
1894                return Err(Error::Unsupported(format!("Unsupported window function: {function}")));
1895            };
1896            let argument = argument.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
1897            // $setWindowFields takes a single expression.
1898            if argument.contains(',') {
1899                return Err(Error::Unsupported(format!(
1900                    "Multi-argument window functions are not supported on MongoDB: {function}"
1901                )));
1902            }
1903            let aggregate = aggregate.to_ascii_lowercase();
1904            let operator = match aggregate.as_str() {
1905                "sum" | "count" => "$sum",
1906                "avg" => "$avg",
1907                "min" => "$min",
1908                "max" => "$max",
1909                _ => return Err(Error::Unsupported(format!("Unsupported window function: {function}"))),
1910            };
1911            let operand = if aggregate == "count" { Value::Int(1) } else { value::string(format!("${argument}")) };
1912            let bounds = Array::from_list(vec![value::string("unbounded"), value::string("current")]);
1913            doc([(operator, operand), ("window", Value::Array(doc([("documents", Value::Array(bounds))])))])
1914        }
1915    };
1916    let mut body = doc([("output", Value::Array(doc([(window.alias.as_str(), Value::Array(output))])))]);
1917    if let Some(partition) = window.partition_by.as_ref().filter(|p| !p.is_empty()) {
1918        let partition_by = match partition.as_slice() {
1919            [column] => value::string(format!("${column}")),
1920            columns => {
1921                let mut by = Array::with_capacity(columns.len());
1922                for column in columns {
1923                    by.set(key(column), value::string(format!("${column}")));
1924                }
1925                Value::Array(by)
1926            }
1927        };
1928        body.set(key("partitionBy"), partition_by);
1929    }
1930    if let Some(order) = order_by {
1931        let mut sort_by = Array::with_capacity(order.len());
1932        for column in order {
1933            match column.strip_prefix('-') {
1934                Some(name) => sort_by.set(key(name), Value::Int(-1)),
1935                None => sort_by.set(key(column), Value::Int(1)),
1936            };
1937        }
1938        body.set(key("sortBy"), Value::Array(sort_by));
1939    }
1940    Ok(stage(PipelineStage::SetWindowFields, body))
1941}
1942
1943#[cfg(test)]
1944mod tests {
1945    use super::*;
1946
1947    #[test]
1948    fn split_call_matches_php_pattern() {
1949        assert_eq!(split_call("SUM(amount)"), Some(("SUM", "amount")));
1950        assert_eq!(split_call("SUM(amount)\n"), Some(("SUM", "amount")));
1951        assert_eq!(split_call("f()"), None);
1952        assert_eq!(split_call("(x)"), None);
1953        assert_eq!(split_call("f(a)(b)"), Some(("f", "a)(b")));
1954    }
1955
1956    #[test]
1957    fn strips_table_prefix() {
1958        assert_eq!(strip_table_prefix("users.id"), "id");
1959        assert_eq!(strip_table_prefix("id"), "id");
1960    }
1961}