Skip to main content

utopia_query/
query.rs

1//! [`Query`]: one filter, order, page, selection, aggregate, join or union,
2//! as data; parsing it from JSON and grouping a list of them.
3
4use std::cmp::Ordering;
5
6use md5::{Digest, Md5};
7use php_std::ArrayKey;
8use php_std::json::{self, Flags};
9
10use crate::enums::{CursorDirection, NullsPosition};
11use crate::error::{Error, Result};
12use crate::method::Method;
13use crate::value::{self, Array, IntoValue, IntoValues, Object, Param, Value};
14
15/// One query: a [`Method`], the attribute it applies to, its values, and the
16/// alias a join or an aggregate is exposed under.
17///
18/// Values are PHP values ([`Value`]); nested queries (the children of `and`,
19/// `or`, `having`, the conditions of a join) are values too.
20///
21/// PHP: `Utopia\Query\Query`.
22///
23/// ```
24/// use utopia_query::{Method, Query};
25///
26/// let query = Query::equal("status", ["active", "pending"]);
27/// assert_eq!(query.method(), Method::Equal);
28/// assert_eq!(query.to_string()?, r#"{"method":"equal","attribute":"status","values":["active","pending"]}"#);
29/// # Ok::<(), utopia_query::Error>(())
30/// ```
31///
32/// ```php
33/// use Utopia\Query\Query;
34///
35/// $query = Query::equal('status', ['active', 'pending']);
36/// echo $query->getMethod()->value, "\n"; // equal
37/// echo $query->toString(), "\n";         // {"method":"equal","attribute":"status","values":["active","pending"]}
38/// ```
39#[derive(Debug, Clone, PartialEq)]
40pub struct Query {
41    method: Method,
42    attribute: String,
43    attribute_type: String,
44    on_array: bool,
45    values: Array,
46    alias: String,
47    alias_defaulted: bool,
48}
49
50/// The queries grouped by what they do, as builders compile them.
51///
52/// PHP: `Utopia\Query\Builder\ParsedQuery`.
53#[derive(Debug, Clone, PartialEq, Default)]
54pub struct ParsedQuery {
55    /// Filters (everything that is not grouped elsewhere).
56    pub filters: Vec<Query>,
57    /// `select` queries.
58    pub selections: Vec<Query>,
59    /// Aggregates.
60    pub aggregations: Vec<Query>,
61    /// `groupBy` columns, as the queries hold them (PHP does not check
62    /// their type until it compiles them).
63    pub group_by: Vec<Value>,
64    /// `having` queries.
65    pub having: Vec<Query>,
66    /// Whether a `distinct` query is present.
67    pub distinct: bool,
68    /// Joins.
69    pub joins: Vec<Query>,
70    /// `union` / `unionAll` queries.
71    pub unions: Vec<Query>,
72    /// The first `limit`.
73    pub limit: Option<i64>,
74    /// The first `offset`.
75    pub offset: Option<i64>,
76    /// The first cursor's row.
77    pub cursor: Option<Value>,
78    /// The first cursor's direction.
79    pub cursor_direction: Option<CursorDirection>,
80    /// `groupByTimeBucket` queries: attribute and interval.
81    pub time_buckets: Vec<TimeBucket>,
82}
83
84impl ParsedQuery {
85    /// A parsed query from its parts.
86    ///
87    /// PHP: `new ParsedQuery(...)`.
88    #[allow(clippy::too_many_arguments)]
89    pub fn new(
90        filters: Vec<Query>,
91        selections: Vec<Query>,
92        aggregations: Vec<Query>,
93        group_by: Vec<Value>,
94        having: Vec<Query>,
95        distinct: bool,
96        joins: Vec<Query>,
97        unions: Vec<Query>,
98        limit: Option<i64>,
99        offset: Option<i64>,
100        cursor: Option<Value>,
101        cursor_direction: Option<CursorDirection>,
102        time_buckets: Vec<TimeBucket>,
103    ) -> Self {
104        ParsedQuery {
105            filters,
106            selections,
107            aggregations,
108            group_by,
109            having,
110            distinct,
111            joins,
112            unions,
113            limit,
114            offset,
115            cursor,
116            cursor_direction,
117            time_buckets,
118        }
119    }
120}
121
122/// A `groupByTimeBucket` query: the attribute and the bucket size.
123#[derive(Debug, Clone, PartialEq)]
124pub struct TimeBucket {
125    /// The attribute bucketed.
126    pub attribute: String,
127    /// The bucket size (`1m`, `5m`, `15m`, `1h`, `1d`, `1w`, `1M`), as the
128    /// query holds it (`''` when absent).
129    pub interval: Value,
130}
131
132/// What [`Query::fingerprint`] accepts: a query, or its JSON.
133#[derive(Debug, Clone, Copy)]
134pub enum QueryOrJson<'a> {
135    /// A query.
136    Query(&'a Query),
137    /// A query as JSON, parsed (raw queries refused).
138    Json(&'a str),
139}
140
141/// Something that compiles queries: a builder.
142///
143/// PHP: `Utopia\Query\Compiler`.
144pub trait Compiler {
145    /// A filter (comparisons, spatial, vector, logical, ...).
146    fn compile_filter(&mut self, query: &Query) -> Result<String>;
147    /// An order (`orderAsc`, `orderDesc`, `orderRandom`).
148    fn compile_order(&mut self, query: &Query) -> Result<String>;
149    /// A limit.
150    fn compile_limit(&mut self, query: &Query) -> Result<String>;
151    /// An offset.
152    fn compile_offset(&mut self, query: &Query) -> Result<String>;
153    /// A selection.
154    fn compile_select(&mut self, query: &Query) -> Result<String>;
155    /// A cursor (`cursorAfter`, `cursorBefore`).
156    fn compile_cursor(&mut self, query: &Query) -> Result<String>;
157    /// An aggregate.
158    fn compile_aggregate(&mut self, query: &Query) -> Result<String>;
159    /// A group by.
160    fn compile_group_by(&mut self, query: &Query) -> Result<String>;
161    /// A join.
162    fn compile_join(&mut self, query: &Query) -> Result<String>;
163}
164
165/// The bucket sizes `groupByTimeBucket` accepts.
166///
167/// PHP: `Query::GROUP_BY_TIME_BUCKET_INTERVALS`.
168pub const GROUP_BY_TIME_BUCKET_INTERVALS: [&str; 7] = ["1m", "5m", "15m", "1h", "1d", "1w", "1M"];
169
170/// The alias a builder gives its main table when none is set.
171///
172/// PHP: `Query::DEFAULT_ALIAS`.
173pub const DEFAULT_ALIAS: &str = "main";
174
175fn list(values: Vec<Value>) -> Array {
176    Array::from_list(values)
177}
178
179fn strings<S: Into<String>>(items: impl IntoIterator<Item = S>) -> Array {
180    list(items.into_iter().map(|s| value::string(s.into())).collect())
181}
182
183fn queries(items: impl IntoIterator<Item = Query>) -> Array {
184    list(items.into_iter().map(Value::from).collect())
185}
186
187/// `gettype()`.
188fn gettype(value: &Value) -> &'static str {
189    value.type_name()
190}
191
192impl Query {
193    /// A query of `method` on `attribute` with `values` and `alias`.
194    ///
195    /// PHP: `new Query($method, $attribute, $values, $alias)`.
196    pub fn new(method: Method, attribute: impl Into<String>, values: Array, alias: impl Into<String>) -> Self {
197        let attribute = attribute.into();
198        let alias = alias.into();
199        let alias_defaulted = method.is_join() && !alias.is_empty() && alias == attribute;
200        Query { method, attribute, attribute_type: String::new(), on_array: false, values, alias, alias_defaulted }
201    }
202
203    fn of(method: Method, attribute: impl Into<String>, values: Vec<Value>) -> Self {
204        Query::new(method, attribute, list(values), "")
205    }
206
207    /// What the query does.
208    ///
209    /// PHP: `getMethod()`.
210    pub fn method(&self) -> Method {
211        self.method
212    }
213
214    /// The attribute (for a join: the joined collection; for `raw`: the SQL).
215    ///
216    /// PHP: `getAttribute()`.
217    pub fn attribute(&self) -> &str {
218        &self.attribute
219    }
220
221    /// The values.
222    ///
223    /// PHP: `getValues()`.
224    pub fn values(&self) -> &Array {
225        &self.values
226    }
227
228    /// The first value (`values[0]`), if any.
229    ///
230    /// PHP: `getValue($default)` is `value().unwrap_or(default)`.
231    pub fn value(&self) -> Option<&Value> {
232        self.values.get(&ArrayKey::Int(0)).filter(|v| !matches!(v, Value::Null))
233    }
234
235    /// The name a join or an aggregate is exposed under, or `""`.
236    ///
237    /// PHP: `getAlias()`.
238    pub fn alias(&self) -> &str {
239        &self.alias
240    }
241
242    /// Whether a join is read under the name of the collection it joins, as
243    /// a join given no alias is. Decided when the query is built, so it
244    /// holds after the collection is renamed.
245    ///
246    /// PHP: `isAliasDefaulted()`.
247    pub fn is_alias_defaulted(&self) -> bool {
248        self.alias_defaulted
249    }
250
251    /// Whether the attribute holds arrays (set by the database layer).
252    ///
253    /// PHP: `onArray()`.
254    pub fn on_array(&self) -> bool {
255        self.on_array
256    }
257
258    /// The attribute's type (set by the database layer), or `""`.
259    ///
260    /// PHP: `getAttributeType()`.
261    pub fn attribute_type(&self) -> &str {
262        &self.attribute_type
263    }
264
265    /// Sets the method.
266    ///
267    /// PHP: `setMethod()`.
268    pub fn set_method(&mut self, method: Method) -> &mut Self {
269        self.method = method;
270        self
271    }
272
273    /// Sets the attribute.
274    ///
275    /// PHP: `setAttribute()`.
276    pub fn set_attribute(&mut self, attribute: impl Into<String>) -> &mut Self {
277        self.attribute = attribute.into();
278        self
279    }
280
281    /// Replaces the values.
282    ///
283    /// PHP: `setValues()`.
284    pub fn set_values(&mut self, values: Array) -> &mut Self {
285        self.values = values;
286        self
287    }
288
289    /// Replaces the values with one value.
290    ///
291    /// PHP: `setValue()`.
292    pub fn set_value(&mut self, value: Value) -> &mut Self {
293        self.values = list(vec![value]);
294        self
295    }
296
297    /// Sets whether the attribute holds arrays.
298    ///
299    /// PHP: `setOnArray()`.
300    pub fn set_on_array(&mut self, on_array: bool) {
301        self.on_array = on_array;
302    }
303
304    /// Sets the attribute's type.
305    ///
306    /// PHP: `setAttributeType()`.
307    pub fn set_attribute_type(&mut self, attribute_type: impl Into<String>) {
308        self.attribute_type = attribute_type.into();
309    }
310
311    /// Whether this is a join whose values hold ON conditions.
312    ///
313    /// PHP: `isNestedJoin()`.
314    pub fn is_nested_join(&self) -> bool {
315        self.method.is_join() && self.values.values().any(|v| matches!(v, Value::Ext(Object::Query(_))))
316    }
317
318    /// The ON conditions of a join (empty for other queries).
319    ///
320    /// PHP: `getJoinOnQueries()`.
321    pub fn join_on_queries(&self) -> Vec<&Query> {
322        if !self.is_nested_join() {
323            return Vec::new();
324        }
325        self.nested().collect()
326    }
327
328    /// The queries among the values, in order.
329    pub fn nested(&self) -> impl Iterator<Item = &Query> {
330        self.values.values().filter_map(|v| match v {
331            Value::Ext(Object::Query(q)) => Some(&**q),
332            _ => None,
333        })
334    }
335
336    /// Whether `value` is the name of a method.
337    ///
338    /// PHP: `Query::isMethod()`.
339    pub fn is_method(value: &str) -> bool {
340        Method::try_from_value(value).is_some()
341    }
342
343    /// Whether the method is spatial.
344    ///
345    /// PHP: `isSpatialQuery()`.
346    pub fn is_spatial_query(&self) -> bool {
347        self.method.is_spatial()
348    }
349
350    /// Whether the method holds other queries.
351    ///
352    /// PHP: `isNested()`.
353    pub fn is_nested(&self) -> bool {
354        self.method.is_nested()
355    }
356
357    /// Parses a query from JSON. Raw queries are refused unless `allow_raw`:
358    /// they bypass bindings, so JSON from an untrusted source must not carry them.
359    ///
360    /// PHP: `Query::parse($query, $allowRaw)`.
361    ///
362    /// ```
363    /// use utopia_query::{Method, Query};
364    ///
365    /// let query = Query::parse(r#"{"method":"greaterThan","attribute":"age","values":[18]}"#, false)?;
366    /// assert_eq!(query.method(), Method::GreaterThan);
367    /// assert!(Query::parse(r#"{"method":"raw","attribute":"1 = 1"}"#, false).is_err());
368    /// # Ok::<(), utopia_query::Error>(())
369    /// ```
370    ///
371    /// ```php
372    /// use Utopia\Query\Query;
373    ///
374    /// $query = Query::parse('{"method":"greaterThan","attribute":"age","values":[18]}');
375    /// echo $query->getMethod()->value, "\n"; // greaterThan
376    /// ```
377    pub fn parse(query: &str, allow_raw: bool) -> Result<Query> {
378        Query::parse_bytes(query.as_bytes(), allow_raw)
379    }
380
381    /// [`Query::parse`] on bytes (PHP strings need not be UTF-8).
382    pub fn parse_bytes(query: &[u8], allow_raw: bool) -> Result<Query> {
383        let decoded: Value = json::decode_ext(query, Some(true), json::DEFAULT_DEPTH, Flags::THROW_ON_ERROR)
384            .map_err(|e| Error::query(format!("Invalid query: {}", e.message())))?;
385        match decoded {
386            Value::Array(array) => Query::parse_query(&array, allow_raw),
387            other => Err(Error::query(format!("Invalid query. Must be an array, got {}", gettype(&other)))),
388        }
389    }
390
391    /// Parses a query from its decoded array form (`method`, `attribute`,
392    /// `values`, `alias`). Raw queries are refused unless `allow_raw`.
393    ///
394    /// PHP: `Query::parseQuery($query, $allowRaw)`.
395    pub fn parse_query(query: &Array, allow_raw: bool) -> Result<Query> {
396        let get = |key: &str| query.get_str(key).filter(|v| !matches!(v, Value::Null));
397        let method = get("method").cloned().unwrap_or_else(|| value::string(""));
398        let attribute = get("attribute").cloned().unwrap_or_else(|| value::string(""));
399        let values = get("values").cloned().unwrap_or(Value::Array(Array::default()));
400        let alias = get("alias").cloned().unwrap_or_else(|| value::string(""));
401
402        let Value::Str(method) = method else {
403            return Err(Error::query(format!("Invalid query method. Must be a string, got {}", gettype(&method))));
404        };
405        let Some(method) = method.as_str().and_then(Method::try_from_value) else {
406            return Err(Error::query(format!("Invalid query method: {}", String::from_utf8_lossy(method.as_bytes()))));
407        };
408        let Value::Str(attribute) = attribute else {
409            return Err(Error::query(format!(
410                "Invalid query attribute. Must be a string, got {}",
411                gettype(&attribute)
412            )));
413        };
414        let Value::Array(mut values) = values else {
415            return Err(Error::query(format!("Invalid query values. Must be an array, got {}", gettype(&values))));
416        };
417        let Value::Str(alias) = alias else {
418            return Err(Error::query(format!("Invalid query alias. Must be a string, got {}", gettype(&alias))));
419        };
420        let attribute = lossy(attribute.as_bytes());
421        let mut alias = lossy(alias.as_bytes());
422
423        if method == Method::Raw && !allow_raw {
424            return Err(Error::Validation(
425                "Raw queries cannot be parsed from untrusted input; construct via Query::raw() in code".into(),
426            ));
427        }
428
429        if method == Method::Distinct && (!attribute.is_empty() || !values.is_empty()) {
430            return Err(Error::query(
431                "Invalid distinct query: distinct takes no attribute or values, it deduplicates the attributes a select names",
432            ));
433        }
434
435        if method.is_join() {
436            return Query::parse_join(method, attribute, &values, alias, allow_raw);
437        }
438
439        if method.is_aggregate() {
440            if alias.is_empty()
441                && let Some(Value::Str(legacy)) = values.get(&ArrayKey::Int(0))
442            {
443                alias = lossy(legacy.as_bytes());
444            }
445            return Ok(Query::new(method, attribute, Array::default(), alias));
446        }
447
448        if method.is_nested() {
449            let mut parsed = Array::with_capacity(values.len());
450            for (key, value) in values.iter() {
451                let child =
452                    Param::method("Utopia\\Query\\Query::parseQuery", 1, "query", "Query.php", 285).array(value)?;
453                parsed.set(key.to_owned(), Value::from(Query::parse_query(child, allow_raw)?));
454            }
455            values = parsed;
456        }
457
458        Ok(Query::new(method, attribute, values, alias))
459    }
460
461    /// A join in its array form, accepting the 0.6 layouts as well: the alias
462    /// as the first value (cross, natural and alias-first joins) and the
463    /// column form `[left, operator, right, alias]`.
464    fn parse_join(method: Method, collection: String, values: &Array, alias: String, allow_raw: bool) -> Result<Query> {
465        let mut on = Vec::new();
466        let mut names: Vec<String> = Vec::new();
467        for value in values.values() {
468            match value {
469                Value::Array(child) => on.push(Query::parse_query(child, allow_raw)?),
470                Value::Str(s) => names.push(lossy(s.as_bytes())),
471                other => {
472                    return Err(Error::query(format!(
473                        "Invalid join value. Must be a query or a string, got {}",
474                        gettype(other)
475                    )));
476                }
477            }
478        }
479        let column_form = on.is_empty() && names.len() >= 3;
480        if column_form {
481            on.push(Query::on(&names[0], &names[2], &names[1]));
482        }
483        let legacy = if column_form { names.get(3) } else { names.first() }.cloned().unwrap_or_default();
484        if names.len() > if column_form { 4 } else { 1 } {
485            return Err(Error::query(format!("Invalid join values for {} {}", method.as_str(), collection)));
486        }
487        Query::create_join(method, collection, if alias.is_empty() { legacy } else { alias }, on)
488    }
489
490    /// Parses each query of `queries` (see [`Query::parse`]).
491    ///
492    /// PHP: `Query::parseQueries()`.
493    pub fn parse_queries<S: AsRef<str>>(queries: &[S], allow_raw: bool) -> Result<Vec<Query>> {
494        queries.iter().map(|q| Query::parse(q.as_ref(), allow_raw)).collect()
495    }
496
497    /// A fingerprint of the queries' shape: methods and attributes, without
498    /// values, independent of order, as an MD5 hex digest. Two lists that
499    /// differ only in values have the same fingerprint (useful to group slow
500    /// queries).
501    ///
502    /// PHP: `Query::fingerprint()`.
503    ///
504    /// ```
505    /// use utopia_query::{Query, QueryOrJson};
506    ///
507    /// let a = Query::equal("status", ["active"]);
508    /// let b = Query::equal("status", ["archived"]);
509    /// assert_eq!(Query::fingerprint(&[QueryOrJson::Query(&a)])?, Query::fingerprint(&[QueryOrJson::Query(&b)])?);
510    /// # Ok::<(), utopia_query::Error>(())
511    /// ```
512    ///
513    /// ```php
514    /// use Utopia\Query\Query;
515    ///
516    /// var_dump(Query::fingerprint([Query::equal('status', ['active'])]) === Query::fingerprint([Query::equal('status', ['archived'])])); // bool(true)
517    /// ```
518    pub fn fingerprint(queries: &[QueryOrJson<'_>]) -> Result<String> {
519        let mut shapes = Vec::with_capacity(queries.len());
520        for query in queries {
521            shapes.push(match query {
522                QueryOrJson::Query(q) => q.shape(),
523                QueryOrJson::Json(json) => Query::parse(json, false)?.shape(),
524            });
525        }
526        shapes.sort_by(|a, b| compare_strings(a, b));
527        let digest = Md5::digest(shapes.join("|").as_bytes());
528        Ok(digest.iter().map(|b| format!("{b:02x}")).collect())
529    }
530
531    /// The shape of this query, without values: `method:attribute`, and for
532    /// `and`, `or`, `elemMatch` and joins with conditions
533    /// `method:attribute(child|child)` with the children's shapes sorted.
534    ///
535    /// PHP: `shape()`.
536    pub fn shape(&self) -> String {
537        let logical = matches!(self.method, Method::And | Method::Or | Method::ElemMatch | Method::Relationship);
538        if !logical && !self.is_nested_join() {
539            return format!("{}:{}", self.method.as_str(), self.attribute);
540        }
541        let mut children: Vec<String> = self.nested().map(Query::shape).collect();
542        children.sort_by(|a, b| compare_strings(a, b));
543        format!("{}:{}({})", self.method.as_str(), self.attribute, children.join("|"))
544    }
545
546    /// The query as an array: `method`, `attribute` (unless empty), `alias`
547    /// (unless empty) and `values`, nested queries as arrays.
548    ///
549    /// PHP: `toArray()`.
550    pub fn to_array(&self) -> Array {
551        let mut array = Array::with_capacity(4);
552        array.set(ArrayKey::from("method"), value::string(self.method.as_str()));
553        if !php_empty_str(&self.attribute) {
554            array.set(ArrayKey::from("attribute"), value::string(&self.attribute));
555        }
556        if !self.alias.is_empty() {
557            array.set(ArrayKey::from("alias"), value::string(&self.alias));
558        }
559        let values = self
560            .values
561            .values()
562            .map(|v| match v {
563                Value::Ext(Object::Query(q)) => Value::Array(q.to_array()),
564                other => other.clone(),
565            })
566            .collect();
567        array.set(ArrayKey::from("values"), Value::Array(list(values)));
568        array
569    }
570
571    /// The query as JSON.
572    ///
573    /// PHP: `toString()`.
574    #[allow(clippy::inherent_to_string_shadow_display, clippy::inherent_to_string)]
575    pub fn to_string(&self) -> Result<String> {
576        value::json_encode(&Value::Array(self.to_array()), Flags::THROW_ON_ERROR)
577            .map_err(|e| Error::query(format!("Invalid Json: {}", e.message())))
578    }
579
580    /// Compiles this query with `compiler`, by kind.
581    ///
582    /// PHP: `compile(Compiler $compiler)`.
583    pub fn compile(&self, compiler: &mut dyn Compiler) -> Result<String> {
584        use Method::*;
585        match self.method {
586            OrderAsc | OrderDesc | OrderRandom => compiler.compile_order(self),
587            Limit => compiler.compile_limit(self),
588            Offset => compiler.compile_offset(self),
589            CursorAfter | CursorBefore => compiler.compile_cursor(self),
590            Select => compiler.compile_select(self),
591            m if m.is_aggregate() => compiler.compile_aggregate(self),
592            GroupBy | GroupByTimeBucket => compiler.compile_group_by(self),
593            m if m.is_join() => compiler.compile_join(self),
594            _ => compiler.compile_filter(self),
595        }
596    }
597
598    /// `equal`: the attribute is one of `values`.
599    ///
600    /// PHP: `Query::equal()`.
601    pub fn equal(attribute: impl Into<String>, values: impl IntoValues) -> Self {
602        Query::new(Method::Equal, attribute, values.into_values(), "")
603    }
604
605    /// `notEqual`: the attribute is not `value`; a list means none of its
606    /// items (an associative array is one value).
607    ///
608    /// PHP: `Query::notEqual()`.
609    pub fn not_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
610        let values = match value.into_value() {
611            Value::Array(a) if a.is_list() => a,
612            other => list(vec![other]),
613        };
614        Query::new(Method::NotEqual, attribute, values, "")
615    }
616
617    /// `lessThan`.
618    ///
619    /// PHP: `Query::lessThan()`.
620    pub fn less_than(attribute: impl Into<String>, value: impl IntoValue) -> Self {
621        Query::of(Method::LessThan, attribute, vec![value.into_value()])
622    }
623
624    /// `lessThanEqual`.
625    ///
626    /// PHP: `Query::lessThanEqual()`.
627    pub fn less_than_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
628        Query::of(Method::LessThanEqual, attribute, vec![value.into_value()])
629    }
630
631    /// `greaterThan`.
632    ///
633    /// PHP: `Query::greaterThan()`.
634    pub fn greater_than(attribute: impl Into<String>, value: impl IntoValue) -> Self {
635        Query::of(Method::GreaterThan, attribute, vec![value.into_value()])
636    }
637
638    /// `greaterThanEqual`.
639    ///
640    /// PHP: `Query::greaterThanEqual()`.
641    pub fn greater_than_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
642        Query::of(Method::GreaterThanEqual, attribute, vec![value.into_value()])
643    }
644
645    /// `contains`: a substring of a string attribute, or an element of an
646    /// array attribute.
647    ///
648    /// PHP: `Query::contains()` (deprecated: prefer [`Query::contains_string`]
649    /// or [`Query::contains_any`]).
650    pub fn contains(attribute: impl Into<String>, values: impl IntoValues) -> Self {
651        Query::new(Method::Contains, attribute, values.into_values(), "")
652    }
653
654    /// `contains` on a string attribute: `LIKE '%value%'` for each value.
655    ///
656    /// PHP: `Query::containsString()`.
657    pub fn contains_string(attribute: impl Into<String>, values: impl IntoValues) -> Self {
658        Query::new(Method::Contains, attribute, values.into_values(), "")
659    }
660
661    /// `containsAny`: an array attribute holds any of the values.
662    ///
663    /// PHP: `Query::containsAny()`.
664    pub fn contains_any(attribute: impl Into<String>, values: impl IntoValues) -> Self {
665        Query::new(Method::ContainsAny, attribute, values.into_values(), "")
666    }
667
668    /// `notContains`.
669    ///
670    /// PHP: `Query::notContains()`.
671    pub fn not_contains(attribute: impl Into<String>, values: impl IntoValues) -> Self {
672        Query::new(Method::NotContains, attribute, values.into_values(), "")
673    }
674
675    /// `between` (inclusive).
676    ///
677    /// PHP: `Query::between()`.
678    pub fn between(attribute: impl Into<String>, start: impl IntoValue, end: impl IntoValue) -> Self {
679        Query::of(Method::Between, attribute, vec![start.into_value(), end.into_value()])
680    }
681
682    /// `notBetween`.
683    ///
684    /// PHP: `Query::notBetween()`.
685    pub fn not_between(attribute: impl Into<String>, start: impl IntoValue, end: impl IntoValue) -> Self {
686        Query::of(Method::NotBetween, attribute, vec![start.into_value(), end.into_value()])
687    }
688
689    /// `search`: full-text search.
690    ///
691    /// PHP: `Query::search()`.
692    pub fn search(attribute: impl Into<String>, value: impl IntoValue) -> Self {
693        Query::of(Method::Search, attribute, vec![value.into_value()])
694    }
695
696    /// `notSearch`.
697    ///
698    /// PHP: `Query::notSearch()`.
699    pub fn not_search(attribute: impl Into<String>, value: impl IntoValue) -> Self {
700        Query::of(Method::NotSearch, attribute, vec![value.into_value()])
701    }
702
703    /// `select`: the attributes to return.
704    ///
705    /// PHP: `Query::select()`.
706    pub fn select<S: Into<String>>(attributes: impl IntoIterator<Item = S>) -> Self {
707        Query::new(Method::Select, "", strings(attributes), "")
708    }
709
710    /// `select` with any values (PHP accepts an array of anything).
711    pub fn select_values(values: Array) -> Self {
712        Query::new(Method::Select, "", values, "")
713    }
714
715    /// `orderDesc`, with where `NULL`s sort.
716    ///
717    /// PHP: `Query::orderDesc()`.
718    pub fn order_desc(attribute: impl Into<String>, nulls: Option<NullsPosition>) -> Self {
719        Query::of(Method::OrderDesc, attribute, nulls.map(Value::from).into_iter().collect())
720    }
721
722    /// `orderAsc`, with where `NULL`s sort.
723    ///
724    /// PHP: `Query::orderAsc()`.
725    pub fn order_asc(attribute: impl Into<String>, nulls: Option<NullsPosition>) -> Self {
726        Query::of(Method::OrderAsc, attribute, nulls.map(Value::from).into_iter().collect())
727    }
728
729    /// `orderRandom`.
730    ///
731    /// PHP: `Query::orderRandom()`.
732    pub fn order_random() -> Self {
733        Query::of(Method::OrderRandom, "", Vec::new())
734    }
735
736    /// `limit`.
737    ///
738    /// PHP: `Query::limit()`.
739    pub fn limit(value: i64) -> Self {
740        Query::of(Method::Limit, "", vec![Value::Int(value)])
741    }
742
743    /// `offset`.
744    ///
745    /// PHP: `Query::offset()`.
746    pub fn offset(value: i64) -> Self {
747        Query::of(Method::Offset, "", vec![Value::Int(value)])
748    }
749
750    /// `cursorAfter`: page after a row (an array of its columns, a
751    /// `stdClass`, or a [`Object::Row`]).
752    ///
753    /// PHP: `Query::cursorAfter()`.
754    pub fn cursor_after(row: Value) -> Self {
755        Query::of(Method::CursorAfter, "", vec![row])
756    }
757
758    /// `cursorBefore`: page before a row.
759    ///
760    /// PHP: `Query::cursorBefore()`.
761    pub fn cursor_before(row: Value) -> Self {
762        Query::of(Method::CursorBefore, "", vec![row])
763    }
764
765    /// `isNull`.
766    ///
767    /// PHP: `Query::isNull()`.
768    pub fn is_null(attribute: impl Into<String>) -> Self {
769        Query::of(Method::IsNull, attribute, Vec::new())
770    }
771
772    /// `isNotNull`.
773    ///
774    /// PHP: `Query::isNotNull()`.
775    pub fn is_not_null(attribute: impl Into<String>) -> Self {
776        Query::of(Method::IsNotNull, attribute, Vec::new())
777    }
778
779    /// `startsWith`.
780    ///
781    /// PHP: `Query::startsWith()`.
782    pub fn starts_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
783        Query::of(Method::StartsWith, attribute, vec![value.into_value()])
784    }
785
786    /// `notStartsWith`.
787    ///
788    /// PHP: `Query::notStartsWith()`.
789    pub fn not_starts_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
790        Query::of(Method::NotStartsWith, attribute, vec![value.into_value()])
791    }
792
793    /// `endsWith`.
794    ///
795    /// PHP: `Query::endsWith()`.
796    pub fn ends_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
797        Query::of(Method::EndsWith, attribute, vec![value.into_value()])
798    }
799
800    /// `notEndsWith`.
801    ///
802    /// PHP: `Query::notEndsWith()`.
803    pub fn not_ends_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
804        Query::of(Method::NotEndsWith, attribute, vec![value.into_value()])
805    }
806
807    /// Documents created before a date: `lessThan('$createdAt', value)`.
808    ///
809    /// PHP: `Query::createdBefore()`.
810    pub fn created_before(value: impl IntoValue) -> Self {
811        Query::less_than("$createdAt", value)
812    }
813
814    /// Documents created after a date.
815    ///
816    /// PHP: `Query::createdAfter()`.
817    pub fn created_after(value: impl IntoValue) -> Self {
818        Query::greater_than("$createdAt", value)
819    }
820
821    /// Documents updated before a date.
822    ///
823    /// PHP: `Query::updatedBefore()`.
824    pub fn updated_before(value: impl IntoValue) -> Self {
825        Query::less_than("$updatedAt", value)
826    }
827
828    /// Documents updated after a date.
829    ///
830    /// PHP: `Query::updatedAfter()`.
831    pub fn updated_after(value: impl IntoValue) -> Self {
832        Query::greater_than("$updatedAt", value)
833    }
834
835    /// Documents created between two dates.
836    ///
837    /// PHP: `Query::createdBetween()`.
838    pub fn created_between(start: impl IntoValue, end: impl IntoValue) -> Self {
839        Query::between("$createdAt", start, end)
840    }
841
842    /// Documents updated between two dates.
843    ///
844    /// PHP: `Query::updatedBetween()`.
845    pub fn updated_between(start: impl IntoValue, end: impl IntoValue) -> Self {
846        Query::between("$updatedAt", start, end)
847    }
848
849    /// `or` of queries.
850    ///
851    /// PHP: `Query::or()`.
852    pub fn or(queries: impl IntoIterator<Item = Query>) -> Self {
853        Query::new(Method::Or, "", self::queries(queries), "")
854    }
855
856    /// `and` of queries.
857    ///
858    /// PHP: `Query::and()`.
859    pub fn and(queries: impl IntoIterator<Item = Query>) -> Self {
860        Query::new(Method::And, "", self::queries(queries), "")
861    }
862
863    /// A logical query of any values (PHP accepts an array of anything).
864    pub fn logical(method: Method, values: Array) -> Self {
865        Query::new(method, "", values, "")
866    }
867
868    /// `containsAll`: an array attribute holds every value.
869    ///
870    /// PHP: `Query::containsAll()`.
871    pub fn contains_all(attribute: impl Into<String>, values: impl IntoValues) -> Self {
872        Query::new(Method::ContainsAll, attribute, values.into_values(), "")
873    }
874
875    /// The queries of the given methods.
876    ///
877    /// PHP: `Query::getByType()` (the clone flag is moot: these are references).
878    pub fn by_type<'a>(queries: &'a [Query], methods: &[Method]) -> Vec<&'a Query> {
879        queries.iter().filter(|q| methods.contains(&q.method)).collect()
880    }
881
882    /// The cursor queries.
883    ///
884    /// PHP: `Query::getCursorQueries()`.
885    pub fn cursor_queries(queries: &[Query]) -> Vec<&Query> {
886        Query::by_type(queries, &[Method::CursorAfter, Method::CursorBefore])
887    }
888
889    /// Groups queries by what they do (see [`ParsedQuery`]).
890    ///
891    /// PHP: `Query::groupByType()`.
892    pub fn group_by_type(queries: &[Query]) -> ParsedQuery {
893        let mut parsed = ParsedQuery::default();
894        for query in queries {
895            let method = query.method;
896            let first = query.values.get(&ArrayKey::Int(0));
897            match method {
898                Method::OrderAsc | Method::OrderDesc | Method::OrderRandom => {}
899                Method::Limit => {
900                    if parsed.limit.is_none() {
901                        parsed.limit = first.and_then(to_integer);
902                    }
903                }
904                Method::Offset => {
905                    if parsed.offset.is_none() {
906                        parsed.offset = first.and_then(to_integer);
907                    }
908                }
909                Method::CursorAfter | Method::CursorBefore => {
910                    if parsed.cursor.is_none() {
911                        parsed.cursor = first.filter(|v| !matches!(v, Value::Null)).cloned();
912                        parsed.cursor_direction = Some(if method == Method::CursorAfter {
913                            CursorDirection::After
914                        } else {
915                            CursorDirection::Before
916                        });
917                    }
918                }
919                Method::Select => parsed.selections.push(query.clone()),
920                m if m.is_aggregate() => parsed.aggregations.push(query.clone()),
921                Method::GroupBy => parsed.group_by.extend(query.values.values().cloned()),
922                Method::GroupByTimeBucket => parsed.time_buckets.push(TimeBucket {
923                    attribute: query.attribute.clone(),
924                    interval: first.filter(|v| !matches!(v, Value::Null)).cloned().unwrap_or_else(|| value::string("")),
925                }),
926                Method::Having => parsed.having.push(query.clone()),
927                Method::Distinct => parsed.distinct = true,
928                m if m.is_join() => parsed.joins.push(query.clone()),
929                Method::Union | Method::UnionAll => parsed.unions.push(query.clone()),
930                _ => parsed.filters.push(query.clone()),
931            }
932        }
933        parsed
934    }
935
936    /// `distanceEqual`: the distance from `values` (a point or a geometry)
937    /// equals `distance` (in meters when `meters`).
938    ///
939    /// PHP: `Query::distanceEqual()`.
940    pub fn distance_equal(attribute: impl Into<String>, values: Array, distance: impl IntoValue, meters: bool) -> Self {
941        Query::distance(Method::DistanceEqual, attribute, values, distance.into_value(), meters)
942    }
943
944    /// `distanceNotEqual`.
945    ///
946    /// PHP: `Query::distanceNotEqual()`.
947    pub fn distance_not_equal(
948        attribute: impl Into<String>,
949        values: Array,
950        distance: impl IntoValue,
951        meters: bool,
952    ) -> Self {
953        Query::distance(Method::DistanceNotEqual, attribute, values, distance.into_value(), meters)
954    }
955
956    /// `distanceGreaterThan`.
957    ///
958    /// PHP: `Query::distanceGreaterThan()`.
959    pub fn distance_greater_than(
960        attribute: impl Into<String>,
961        values: Array,
962        distance: impl IntoValue,
963        meters: bool,
964    ) -> Self {
965        Query::distance(Method::DistanceGreaterThan, attribute, values, distance.into_value(), meters)
966    }
967
968    /// `distanceLessThan`.
969    ///
970    /// PHP: `Query::distanceLessThan()`.
971    pub fn distance_less_than(
972        attribute: impl Into<String>,
973        values: Array,
974        distance: impl IntoValue,
975        meters: bool,
976    ) -> Self {
977        Query::distance(Method::DistanceLessThan, attribute, values, distance.into_value(), meters)
978    }
979
980    fn distance(method: Method, attribute: impl Into<String>, values: Array, distance: Value, meters: bool) -> Self {
981        let tuple = list(vec![Value::Array(values), distance, Value::Bool(meters)]);
982        Query::of(method, attribute, vec![Value::Array(tuple)])
983    }
984
985    fn geometry(method: Method, attribute: impl Into<String>, values: Array) -> Self {
986        Query::of(method, attribute, vec![Value::Array(values)])
987    }
988
989    /// `intersects` (spatial).
990    ///
991    /// PHP: `Query::intersects()`.
992    pub fn intersects(attribute: impl Into<String>, values: Array) -> Self {
993        Query::geometry(Method::Intersects, attribute, values)
994    }
995
996    /// `notIntersects` (spatial).
997    ///
998    /// PHP: `Query::notIntersects()`.
999    pub fn not_intersects(attribute: impl Into<String>, values: Array) -> Self {
1000        Query::geometry(Method::NotIntersects, attribute, values)
1001    }
1002
1003    /// `crosses` (spatial).
1004    ///
1005    /// PHP: `Query::crosses()`.
1006    pub fn crosses(attribute: impl Into<String>, values: Array) -> Self {
1007        Query::geometry(Method::Crosses, attribute, values)
1008    }
1009
1010    /// `notCrosses` (spatial).
1011    ///
1012    /// PHP: `Query::notCrosses()`.
1013    pub fn not_crosses(attribute: impl Into<String>, values: Array) -> Self {
1014        Query::geometry(Method::NotCrosses, attribute, values)
1015    }
1016
1017    /// `overlaps` (spatial).
1018    ///
1019    /// PHP: `Query::overlaps()`.
1020    pub fn overlaps(attribute: impl Into<String>, values: Array) -> Self {
1021        Query::geometry(Method::Overlaps, attribute, values)
1022    }
1023
1024    /// `notOverlaps` (spatial).
1025    ///
1026    /// PHP: `Query::notOverlaps()`.
1027    pub fn not_overlaps(attribute: impl Into<String>, values: Array) -> Self {
1028        Query::geometry(Method::NotOverlaps, attribute, values)
1029    }
1030
1031    /// `touches` (spatial).
1032    ///
1033    /// PHP: `Query::touches()`.
1034    pub fn touches(attribute: impl Into<String>, values: Array) -> Self {
1035        Query::geometry(Method::Touches, attribute, values)
1036    }
1037
1038    /// `notTouches` (spatial).
1039    ///
1040    /// PHP: `Query::notTouches()`.
1041    pub fn not_touches(attribute: impl Into<String>, values: Array) -> Self {
1042        Query::geometry(Method::NotTouches, attribute, values)
1043    }
1044
1045    /// `vectorDot`: similarity to `vector` by dot product.
1046    ///
1047    /// PHP: `Query::vectorDot()`.
1048    pub fn vector_dot(attribute: impl Into<String>, vector: Array) -> Self {
1049        Query::geometry(Method::VectorDot, attribute, vector)
1050    }
1051
1052    /// `vectorCosine`.
1053    ///
1054    /// PHP: `Query::vectorCosine()`.
1055    pub fn vector_cosine(attribute: impl Into<String>, vector: Array) -> Self {
1056        Query::geometry(Method::VectorCosine, attribute, vector)
1057    }
1058
1059    /// `vectorEuclidean`.
1060    ///
1061    /// PHP: `Query::vectorEuclidean()`.
1062    pub fn vector_euclidean(attribute: impl Into<String>, vector: Array) -> Self {
1063        Query::geometry(Method::VectorEuclidean, attribute, vector)
1064    }
1065
1066    /// `regex`.
1067    ///
1068    /// PHP: `Query::regex()`.
1069    pub fn regex(attribute: impl Into<String>, pattern: impl IntoValue) -> Self {
1070        Query::of(Method::Regex, attribute, vec![pattern.into_value()])
1071    }
1072
1073    /// `exists`: the attributes are present.
1074    ///
1075    /// PHP: `Query::exists()`.
1076    pub fn exists(attributes: Array) -> Self {
1077        Query::new(Method::Exists, "", attributes, "")
1078    }
1079
1080    /// `notExists`: the attribute (or each of a list) is absent.
1081    ///
1082    /// PHP: `Query::notExists()`.
1083    pub fn not_exists(attribute: impl IntoValue) -> Self {
1084        let values = match attribute.into_value() {
1085            Value::Array(a) => a,
1086            other => list(vec![other]),
1087        };
1088        Query::new(Method::NotExists, "", values, "")
1089    }
1090
1091    /// `elemMatch`: an element of the array attribute matches every query.
1092    ///
1093    /// PHP: `Query::elemMatch()`.
1094    pub fn elem_match(attribute: impl Into<String>, queries: impl IntoIterator<Item = Query>) -> Self {
1095        Query::new(Method::ElemMatch, attribute, self::queries(queries), "")
1096    }
1097
1098    /// `relationship`: queries, written against the related collection,
1099    /// that shape the documents populated for the relationship attribute.
1100    /// It is nested, and `validate()` skips it: its queries name another
1101    /// collection's attributes.
1102    ///
1103    /// ```
1104    /// use utopia_query::{Method, Query};
1105    ///
1106    /// let query = Query::relationship("books", [Query::limit(2)]);
1107    /// assert_eq!(query.method(), Method::Relationship);
1108    /// assert!(Method::Relationship.is_nested());
1109    /// assert_eq!(query.shape(), "relationship:books(limit:)");
1110    /// assert!(Query::validate(&[query], &["title"]).unwrap().is_empty());
1111    /// ```
1112    ///
1113    /// PHP: `Query::relationship()`.
1114    pub fn relationship(attribute: impl Into<String>, queries: impl IntoIterator<Item = Query>) -> Self {
1115        Query::new(Method::Relationship, attribute, self::queries(queries), "")
1116    }
1117
1118    fn aggregate(method: Method, attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1119        Query::new(method, attribute, Array::default(), alias)
1120    }
1121
1122    /// `count` (`*` counts rows).
1123    ///
1124    /// PHP: `Query::count()`.
1125    pub fn count(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1126        Query::aggregate(Method::Count, attribute, alias)
1127    }
1128
1129    /// `countDistinct`.
1130    ///
1131    /// PHP: `Query::countDistinct()`.
1132    pub fn count_distinct(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1133        Query::aggregate(Method::CountDistinct, attribute, alias)
1134    }
1135
1136    /// `sum`.
1137    ///
1138    /// PHP: `Query::sum()`.
1139    pub fn sum(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1140        Query::aggregate(Method::Sum, attribute, alias)
1141    }
1142
1143    /// `avg`.
1144    ///
1145    /// PHP: `Query::avg()`.
1146    pub fn avg(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1147        Query::aggregate(Method::Avg, attribute, alias)
1148    }
1149
1150    /// `min`.
1151    ///
1152    /// PHP: `Query::min()`.
1153    pub fn min(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1154        Query::aggregate(Method::Min, attribute, alias)
1155    }
1156
1157    /// `max`.
1158    ///
1159    /// PHP: `Query::max()`.
1160    pub fn max(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1161        Query::aggregate(Method::Max, attribute, alias)
1162    }
1163
1164    /// `stddev`.
1165    ///
1166    /// PHP: `Query::stddev()`.
1167    pub fn stddev(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1168        Query::aggregate(Method::Stddev, attribute, alias)
1169    }
1170
1171    /// `stddevPop`.
1172    ///
1173    /// PHP: `Query::stddevPop()`.
1174    pub fn stddev_pop(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1175        Query::aggregate(Method::StddevPop, attribute, alias)
1176    }
1177
1178    /// `stddevSamp`.
1179    ///
1180    /// PHP: `Query::stddevSamp()`.
1181    pub fn stddev_samp(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1182        Query::aggregate(Method::StddevSamp, attribute, alias)
1183    }
1184
1185    /// `variance`.
1186    ///
1187    /// PHP: `Query::variance()`.
1188    pub fn variance(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1189        Query::aggregate(Method::Variance, attribute, alias)
1190    }
1191
1192    /// `varPop`.
1193    ///
1194    /// PHP: `Query::varPop()`.
1195    pub fn var_pop(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1196        Query::aggregate(Method::VarPop, attribute, alias)
1197    }
1198
1199    /// `varSamp`.
1200    ///
1201    /// PHP: `Query::varSamp()`.
1202    pub fn var_samp(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1203        Query::aggregate(Method::VarSamp, attribute, alias)
1204    }
1205
1206    /// `bitAnd`.
1207    ///
1208    /// PHP: `Query::bitAnd()`.
1209    pub fn bit_and(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1210        Query::aggregate(Method::BitAnd, attribute, alias)
1211    }
1212
1213    /// `bitOr`.
1214    ///
1215    /// PHP: `Query::bitOr()`.
1216    pub fn bit_or(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1217        Query::aggregate(Method::BitOr, attribute, alias)
1218    }
1219
1220    /// `bitXor`.
1221    ///
1222    /// PHP: `Query::bitXor()`.
1223    pub fn bit_xor(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1224        Query::aggregate(Method::BitXor, attribute, alias)
1225    }
1226
1227    /// `groupBy`.
1228    ///
1229    /// PHP: `Query::groupBy()`.
1230    pub fn group_by<S: Into<String>>(attributes: impl IntoIterator<Item = S>) -> Self {
1231        Query::new(Method::GroupBy, "", strings(attributes), "")
1232    }
1233
1234    /// `groupByTimeBucket`: groups by `attribute` cut into windows of
1235    /// `interval` (one of [`GROUP_BY_TIME_BUCKET_INTERVALS`]).
1236    ///
1237    /// PHP: `Query::groupByTimeBucket()`.
1238    pub fn group_by_time_bucket(attribute: impl Into<String>, interval: &str) -> Result<Self> {
1239        if !GROUP_BY_TIME_BUCKET_INTERVALS.contains(&interval) {
1240            return Err(Error::Validation(format!(
1241                "Invalid groupByTimeBucket interval: {interval}. Allowed: {}",
1242                GROUP_BY_TIME_BUCKET_INTERVALS.join(", ")
1243            )));
1244        }
1245        Ok(Query::of(Method::GroupByTimeBucket, attribute, vec![value::string(interval)]))
1246    }
1247
1248    /// `having`: conditions on aggregates.
1249    ///
1250    /// PHP: `Query::having()`.
1251    pub fn having(queries: impl IntoIterator<Item = Query>) -> Self {
1252        Query::new(Method::Having, "", self::queries(queries), "")
1253    }
1254
1255    /// `distinct`.
1256    ///
1257    /// PHP: `Query::distinct()`.
1258    pub fn distinct() -> Self {
1259        Query::of(Method::Distinct, "", Vec::new())
1260    }
1261
1262    /// `on`: a column-to-column join condition (`operator` defaults to `=` in PHP).
1263    ///
1264    /// PHP: `Query::on()`.
1265    pub fn on(left: impl Into<String>, right: impl Into<String>, operator: impl Into<String>) -> Self {
1266        Query::new(
1267            Method::On,
1268            "",
1269            list(vec![value::string(left.into()), value::string(operator.into()), value::string(right.into())]),
1270            "",
1271        )
1272    }
1273
1274    /// An inner join of `collection` as `alias` on conditions (`on` queries and filters).
1275    ///
1276    /// PHP: `Query::join()`.
1277    pub fn join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
1278        Query::create_join(Method::Join, collection.into(), alias.into(), on)
1279    }
1280
1281    /// A left join.
1282    ///
1283    /// PHP: `Query::leftJoin()`.
1284    pub fn left_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
1285        Query::create_join(Method::LeftJoin, collection.into(), alias.into(), on)
1286    }
1287
1288    /// A right join.
1289    ///
1290    /// PHP: `Query::rightJoin()`.
1291    pub fn right_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
1292        Query::create_join(Method::RightJoin, collection.into(), alias.into(), on)
1293    }
1294
1295    /// A full outer join.
1296    ///
1297    /// PHP: `Query::fullOuterJoin()`.
1298    pub fn full_outer_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
1299        Query::create_join(Method::FullOuterJoin, collection.into(), alias.into(), on)
1300    }
1301
1302    /// A cross join (no conditions).
1303    ///
1304    /// PHP: `Query::crossJoin()`.
1305    pub fn cross_join(collection: impl Into<String>, alias: impl Into<String>) -> Result<Self> {
1306        Query::create_join(Method::CrossJoin, collection.into(), alias.into(), Vec::new())
1307    }
1308
1309    /// A natural join (no conditions).
1310    ///
1311    /// PHP: `Query::naturalJoin()`.
1312    pub fn natural_join(collection: impl Into<String>, alias: impl Into<String>) -> Result<Self> {
1313        Query::create_join(Method::NaturalJoin, collection.into(), alias.into(), Vec::new())
1314    }
1315
1316    /// A join of any conditions (values that must all be queries, as PHP checks).
1317    pub fn join_values(
1318        method: Method,
1319        collection: impl Into<String>,
1320        alias: impl Into<String>,
1321        on: Array,
1322    ) -> Result<Self> {
1323        let mut conditions = Vec::with_capacity(on.len());
1324        let collection = collection.into();
1325        let alias = alias.into();
1326        let alias = if alias.is_empty() { collection.clone() } else { alias };
1327        Query::check_join_alias(method, &collection, &alias, on.is_empty())?;
1328        for value in on.values() {
1329            match value {
1330                Value::Ext(Object::Query(q)) => conditions.push((**q).clone()),
1331                _ => return Err(Error::Validation("Join ON conditions must be Query objects".into())),
1332            }
1333        }
1334        Query::create_join(method, collection, alias, conditions)
1335    }
1336
1337    fn check_join_alias(method: Method, collection: &str, alias: &str, empty: bool) -> Result<()> {
1338        if alias.is_empty() {
1339            // Only when the collection is empty too: an empty alias reads as the collection.
1340            return Err(Error::Validation(format!("Join alias is required: {} {}", method.as_str(), collection)));
1341        }
1342        let unconditioned = method == Method::CrossJoin || method == Method::NaturalJoin;
1343        if unconditioned && !empty {
1344            return Err(Error::Validation(format!("Join ON conditions are not allowed in {}", method.as_str())));
1345        }
1346        if !unconditioned && empty {
1347            return Err(Error::Validation("Join ON requires at least one condition".into()));
1348        }
1349        Ok(())
1350    }
1351
1352    /// A join given no alias is read under the collection it joins.
1353    fn create_join(method: Method, collection: String, alias: String, on: Vec<Query>) -> Result<Self> {
1354        let alias = if alias.is_empty() { collection.clone() } else { alias };
1355        Query::check_join_alias(method, &collection, &alias, on.is_empty())?;
1356        for condition in &on {
1357            Query::assert_join_condition(condition)?;
1358        }
1359        Ok(Query::new(method, collection, self::queries(on), alias))
1360    }
1361
1362    fn assert_join_condition(condition: &Query) -> Result<()> {
1363        let method = condition.method;
1364        if !method.is_join_condition() {
1365            return Err(Error::Validation(format!("Unsupported join ON condition: {}", method.as_str())));
1366        }
1367        if method != Method::And && method != Method::Or {
1368            return Ok(());
1369        }
1370        for child in condition.values.values() {
1371            match child {
1372                Value::Ext(Object::Query(q)) => Query::assert_join_condition(q)?,
1373                _ => return Err(Error::Validation("Join ON conditions must be Query objects".into())),
1374            }
1375        }
1376        Ok(())
1377    }
1378
1379    /// `union` of queries.
1380    ///
1381    /// PHP: `Query::union()`.
1382    pub fn union(queries: impl IntoIterator<Item = Query>) -> Self {
1383        Query::new(Method::Union, "", self::queries(queries), "")
1384    }
1385
1386    /// `unionAll` of queries.
1387    ///
1388    /// PHP: `Query::unionAll()`.
1389    pub fn union_all(queries: impl IntoIterator<Item = Query>) -> Self {
1390        Query::new(Method::UnionAll, "", self::queries(queries), "")
1391    }
1392
1393    /// `jsonContains`: a JSON attribute contains `value`.
1394    ///
1395    /// PHP: `Query::jsonContains()`.
1396    pub fn json_contains(attribute: impl Into<String>, value: impl IntoValue) -> Self {
1397        Query::of(Method::JsonContains, attribute, vec![value.into_value()])
1398    }
1399
1400    /// `jsonNotContains`.
1401    ///
1402    /// PHP: `Query::jsonNotContains()`.
1403    pub fn json_not_contains(attribute: impl Into<String>, value: impl IntoValue) -> Self {
1404        Query::of(Method::JsonNotContains, attribute, vec![value.into_value()])
1405    }
1406
1407    /// `jsonOverlaps`: a JSON array attribute shares an element with `values`.
1408    ///
1409    /// PHP: `Query::jsonOverlaps()`.
1410    pub fn json_overlaps(attribute: impl Into<String>, values: Array) -> Self {
1411        Query::of(Method::JsonOverlaps, attribute, vec![Value::Array(values)])
1412    }
1413
1414    /// `jsonPath`: the value at `path` compares to `value` with `operator`.
1415    ///
1416    /// PHP: `Query::jsonPath()`.
1417    pub fn json_path(
1418        attribute: impl Into<String>,
1419        path: impl Into<String>,
1420        operator: impl Into<String>,
1421        value: impl IntoValue,
1422    ) -> Self {
1423        Query::of(
1424            Method::JsonPath,
1425            attribute,
1426            vec![value::string(path.into()), value::string(operator.into()), value.into_value()],
1427        )
1428    }
1429
1430    /// `covers` (spatial).
1431    ///
1432    /// PHP: `Query::covers()`.
1433    pub fn covers(attribute: impl Into<String>, values: Array) -> Self {
1434        Query::geometry(Method::Covers, attribute, values)
1435    }
1436
1437    /// `notCovers` (spatial).
1438    ///
1439    /// PHP: `Query::notCovers()`.
1440    pub fn not_covers(attribute: impl Into<String>, values: Array) -> Self {
1441        Query::geometry(Method::NotCovers, attribute, values)
1442    }
1443
1444    /// `spatialEquals` (spatial).
1445    ///
1446    /// PHP: `Query::spatialEquals()`.
1447    pub fn spatial_equals(attribute: impl Into<String>, values: Array) -> Self {
1448        Query::geometry(Method::SpatialEquals, attribute, values)
1449    }
1450
1451    /// `notSpatialEquals` (spatial).
1452    ///
1453    /// PHP: `Query::notSpatialEquals()`.
1454    pub fn not_spatial_equals(attribute: impl Into<String>, values: Array) -> Self {
1455        Query::geometry(Method::NotSpatialEquals, attribute, values)
1456    }
1457
1458    /// `raw`: SQL used as given, with its bindings.
1459    ///
1460    /// PHP: `Query::raw()`.
1461    pub fn raw(sql: impl Into<String>, bindings: Array) -> Self {
1462        Query::new(Method::Raw, sql, bindings, "")
1463    }
1464
1465    /// The `limit` and `offset` of page `page` (from 1) of `per_page` rows.
1466    ///
1467    /// PHP: `Query::page()`.
1468    pub fn page(page: i64, per_page: i64) -> Result<[Query; 2]> {
1469        if page < 1 {
1470            return Err(Error::Validation(format!("Page must be >= 1, got {page}")));
1471        }
1472        if per_page < 1 {
1473            return Err(Error::Validation(format!("Per page must be >= 1, got {per_page}")));
1474        }
1475        Ok([Query::limit(per_page), Query::offset((page - 1).wrapping_mul(per_page))])
1476    }
1477
1478    /// `a` followed by `b`, where a `limit`, `offset` or cursor in `b`
1479    /// replaces any of the same method in `a`.
1480    ///
1481    /// PHP: `Query::merge()`.
1482    pub fn merge(a: &[Query], b: &[Query]) -> Vec<Query> {
1483        let singular = [Method::Limit, Method::Offset, Method::CursorAfter, Method::CursorBefore];
1484        let mut result = a.to_vec();
1485        for query in b {
1486            if singular.contains(&query.method) {
1487                result.retain(|q| q.method != query.method);
1488            }
1489            result.push(query.clone());
1490        }
1491        result
1492    }
1493
1494    /// The queries of `a` not in `b` (compared by their array form).
1495    ///
1496    /// PHP: `Query::diff()`.
1497    pub fn diff(a: &[Query], b: &[Query]) -> Vec<Query> {
1498        let b: Vec<Value> = b.iter().map(|q| Value::Array(q.to_array())).collect();
1499        a.iter()
1500            .filter(|q| {
1501                let array = Value::Array(q.to_array());
1502                !b.iter().any(|other| value::identical(&array, other))
1503            })
1504            .cloned()
1505            .collect()
1506    }
1507
1508    /// Error messages for attributes outside `allowed` (nested queries
1509    /// included; pagination, selections and existence checks skipped). Fails
1510    /// as PHP does when a `groupBy` column is an object it cannot print.
1511    ///
1512    /// PHP: `Query::validate()`.
1513    pub fn validate<S: AsRef<str>>(queries: &[Query], allowed: &[S]) -> Result<Vec<String>> {
1514        let allowed: Vec<&str> = allowed.iter().map(AsRef::as_ref).collect();
1515        let mut errors = Vec::new();
1516        Query::validate_into(queries.iter(), &allowed, &mut errors)?;
1517        Ok(errors)
1518    }
1519
1520    fn validate_into<'a>(
1521        queries: impl Iterator<Item = &'a Query>,
1522        allowed: &[&str],
1523        errors: &mut Vec<String>,
1524    ) -> Result<()> {
1525        use Method::*;
1526        for query in queries {
1527            let method = query.method;
1528            // A relationship's queries name the related collection's
1529            // attributes: skipped before nested queries are walked.
1530            if matches!(
1531                method,
1532                Limit
1533                    | Offset
1534                    | CursorAfter
1535                    | CursorBefore
1536                    | OrderRandom
1537                    | Distinct
1538                    | Select
1539                    | Exists
1540                    | NotExists
1541                    | Relationship
1542            ) {
1543                continue;
1544            }
1545            if method.is_nested() {
1546                Query::validate_into(query.nested(), allowed, errors)?;
1547                continue;
1548            }
1549            if method == GroupBy {
1550                for column in query.values.values() {
1551                    let is_allowed =
1552                        matches!(column, Value::Str(s) if s.as_str().is_some_and(|s| allowed.contains(&s)));
1553                    if !is_allowed {
1554                        errors.push(format!(
1555                            "Invalid attribute \"{}\" used in {}",
1556                            value::concat(column)?,
1557                            method.as_str()
1558                        ));
1559                    }
1560                }
1561                continue;
1562            }
1563            let attribute = query.attribute.as_str();
1564            if attribute.is_empty() || attribute == "*" {
1565                continue;
1566            }
1567            if !allowed.contains(&attribute) {
1568                errors.push(format!("Invalid attribute \"{attribute}\" used in {}", method.as_str()));
1569            }
1570        }
1571        Ok(())
1572    }
1573}
1574
1575impl From<NullsPosition> for Object {
1576    /// The enum case as an object value.
1577    fn from(nulls: NullsPosition) -> Self {
1578        Object::Nulls(nulls)
1579    }
1580}
1581
1582/// PHP `empty($string)`: `""` and `"0"`.
1583fn php_empty_str(s: &str) -> bool {
1584    s.is_empty() || s == "0"
1585}
1586
1587/// `is_numeric($value)`.
1588pub(crate) fn is_numeric(value: &Value) -> bool {
1589    match value {
1590        Value::Int(_) | Value::Float(_) => true,
1591        Value::Str(s) => php_std::value::numeric_bytes_ex(s.as_bytes()).is_some(),
1592        _ => false,
1593    }
1594}
1595
1596/// PHP's `Query::toInteger()`: an integer, an integral numeric string, or
1597/// a finite number in range, truncated; `None` for anything else.
1598fn to_integer(value: &Value) -> Option<i64> {
1599    use php_std::filter as f;
1600    let text = match value {
1601        Value::Int(i) => return Some(*i),
1602        _ if !is_numeric(value) => return None,
1603        Value::Float(x) => f::Value::Float(*x),
1604        Value::Str(s) => f::Value::Str(s.as_bytes().to_vec()),
1605        _ => return None,
1606    };
1607    if let Ok(f::Filtered { value: f::Value::Int(i), .. }) =
1608        f::filter_var(&text, f::FILTER_VALIDATE_INT, &f::Options::Flags(0))
1609    {
1610        return Some(i);
1611    }
1612    let number = value.to_double();
1613    if !number.is_finite() || number < i64::MIN as f64 || number >= i64::MAX as f64 {
1614        return None;
1615    }
1616    Some(number as i64)
1617}
1618
1619/// PHP's `sort()` order for strings (`zend_compare` on two strings: numeric
1620/// strings compare as numbers).
1621pub(crate) fn compare_strings(a: &str, b: &str) -> Ordering {
1622    value::string(a).cmp_php(&value::string(b))
1623}
1624
1625fn lossy(bytes: &[u8]) -> String {
1626    String::from_utf8_lossy(bytes).into_owned()
1627}