Skip to main content

utopia_query/
method.rs

1//! [`Method`]: what a [`Query`](crate::Query) does.
2
3/// Defines a string-backed enumeration the way PHP's backed enums behave:
4/// `as_str()` is `->value`, `name()` is `->name`, `from()` / `try_from()`
5/// parse a value, `CASES` lists them in declaration order.
6macro_rules! backed_enum {
7    (
8        $(#[$meta:meta])*
9        $vis:vis enum $name:ident: $php:literal {
10            $( $(#[$vmeta:meta])* $variant:ident = $value:literal, )*
11        }
12    ) => {
13        $(#[$meta])*
14        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15        $vis enum $name {
16            $( $(#[$vmeta])* $variant, )*
17        }
18
19        impl $name {
20            /// Every case, in declaration order.
21            ///
22            /// PHP: `cases()`.
23            pub const CASES: &'static [$name] = &[$($name::$variant),*];
24
25            /// The PHP class of this enumeration.
26            pub const PHP_CLASS: &'static str = $php;
27
28            /// The backing value.
29            ///
30            /// PHP: `->value`.
31            pub const fn as_str(self) -> &'static str {
32                match self {
33                    $($name::$variant => $value,)*
34                }
35            }
36
37            /// The case name.
38            ///
39            /// PHP: `->name`.
40            pub const fn name(self) -> &'static str {
41                match self {
42                    $($name::$variant => stringify!($variant),)*
43                }
44            }
45
46            /// The case with backing value `value`, if any.
47            ///
48            /// PHP: `tryFrom()`.
49            pub fn try_from_value(value: &str) -> Option<Self> {
50                match value {
51                    $($value => Some($name::$variant),)*
52                    _ => None,
53                }
54            }
55
56            /// The case with backing value `value`.
57            ///
58            /// PHP: `from()`, which throws `ValueError` ([`Error::InvalidValue`](crate::Error::InvalidValue)) with the same message.
59            pub fn from_value(value: &str) -> Result<Self, $crate::Error> {
60                Self::try_from_value(value).ok_or_else(|| {
61                    $crate::Error::InvalidValue(format!(
62                        "\"{}\" is not a valid backing value for enum {}",
63                        value,
64                        $php
65                    ))
66                })
67            }
68
69            /// The case named `name`, if any.
70            pub fn from_name(name: &str) -> Option<Self> {
71                match name {
72                    $(stringify!($variant) => Some($name::$variant),)*
73                    _ => None,
74                }
75            }
76        }
77
78        impl std::fmt::Display for $name {
79            /// The backing value.
80            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81                f.write_str(self.as_str())
82            }
83        }
84    };
85}
86
87pub(crate) use backed_enum;
88
89backed_enum! {
90    /// What a [`Query`](crate::Query) does: filter, order, paginate, select,
91    /// aggregate, join, combine, or carry raw SQL.
92    ///
93    /// PHP: `Utopia\Query\Method`.
94    pub enum Method: "Utopia\\Query\\Method" {
95        /// `equal`: the attribute is one of the values.
96        Equal = "equal",
97        /// `notEqual`: the attribute is none of the values.
98        NotEqual = "notEqual",
99        /// `lessThan`.
100        LessThan = "lessThan",
101        /// `lessThanEqual`.
102        LessThanEqual = "lessThanEqual",
103        /// `greaterThan`.
104        GreaterThan = "greaterThan",
105        /// `greaterThanEqual`.
106        GreaterThanEqual = "greaterThanEqual",
107        /// `contains`: substring (or array element) match.
108        Contains = "contains",
109        /// `containsAny`: any of the values.
110        ContainsAny = "containsAny",
111        /// `notContains`.
112        NotContains = "notContains",
113        /// `search`: full-text search.
114        Search = "search",
115        /// `notSearch`.
116        NotSearch = "notSearch",
117        /// `isNull`.
118        IsNull = "isNull",
119        /// `isNotNull`.
120        IsNotNull = "isNotNull",
121        /// `between`.
122        Between = "between",
123        /// `notBetween`.
124        NotBetween = "notBetween",
125        /// `startsWith`.
126        StartsWith = "startsWith",
127        /// `notStartsWith`.
128        NotStartsWith = "notStartsWith",
129        /// `endsWith`.
130        EndsWith = "endsWith",
131        /// `notEndsWith`.
132        NotEndsWith = "notEndsWith",
133        /// `regex`.
134        Regex = "regex",
135        /// `exists`: the attributes are present.
136        Exists = "exists",
137        /// `notExists`.
138        NotExists = "notExists",
139        /// `crosses` (spatial).
140        Crosses = "crosses",
141        /// `notCrosses` (spatial).
142        NotCrosses = "notCrosses",
143        /// `distanceEqual` (spatial).
144        DistanceEqual = "distanceEqual",
145        /// `distanceNotEqual` (spatial).
146        DistanceNotEqual = "distanceNotEqual",
147        /// `distanceGreaterThan` (spatial).
148        DistanceGreaterThan = "distanceGreaterThan",
149        /// `distanceLessThan` (spatial).
150        DistanceLessThan = "distanceLessThan",
151        /// `intersects` (spatial).
152        Intersects = "intersects",
153        /// `notIntersects` (spatial).
154        NotIntersects = "notIntersects",
155        /// `overlaps` (spatial).
156        Overlaps = "overlaps",
157        /// `notOverlaps` (spatial).
158        NotOverlaps = "notOverlaps",
159        /// `touches` (spatial).
160        Touches = "touches",
161        /// `notTouches` (spatial).
162        NotTouches = "notTouches",
163        /// `vectorDot` (vector similarity).
164        VectorDot = "vectorDot",
165        /// `vectorCosine` (vector similarity).
166        VectorCosine = "vectorCosine",
167        /// `vectorEuclidean` (vector similarity).
168        VectorEuclidean = "vectorEuclidean",
169        /// `select`: the columns to return.
170        Select = "select",
171        /// `orderDesc`.
172        OrderDesc = "orderDesc",
173        /// `orderAsc`.
174        OrderAsc = "orderAsc",
175        /// `orderRandom`.
176        OrderRandom = "orderRandom",
177        /// `limit`.
178        Limit = "limit",
179        /// `offset`.
180        Offset = "offset",
181        /// `cursorAfter`: page after a row.
182        CursorAfter = "cursorAfter",
183        /// `cursorBefore`: page before a row.
184        CursorBefore = "cursorBefore",
185        /// `and`.
186        And = "and",
187        /// `or`.
188        Or = "or",
189        /// `containsAll`.
190        ContainsAll = "containsAll",
191        /// `elemMatch`: an array element matches every nested query.
192        ElemMatch = "elemMatch",
193        /// `relationship`: queries, written against the related collection,
194        /// that shape the documents populated for a relationship attribute.
195        Relationship = "relationship",
196        /// `count`.
197        Count = "count",
198        /// `countDistinct`.
199        CountDistinct = "countDistinct",
200        /// `sum`.
201        Sum = "sum",
202        /// `avg`.
203        Avg = "avg",
204        /// `min`.
205        Min = "min",
206        /// `max`.
207        Max = "max",
208        /// `stddev`.
209        Stddev = "stddev",
210        /// `stddevPop`.
211        StddevPop = "stddevPop",
212        /// `stddevSamp`.
213        StddevSamp = "stddevSamp",
214        /// `variance`.
215        Variance = "variance",
216        /// `varPop`.
217        VarPop = "varPop",
218        /// `varSamp`.
219        VarSamp = "varSamp",
220        /// `bitAnd`.
221        BitAnd = "bitAnd",
222        /// `bitOr`.
223        BitOr = "bitOr",
224        /// `bitXor`.
225        BitXor = "bitXor",
226        /// `groupBy`.
227        GroupBy = "groupBy",
228        /// `groupByTimeBucket`.
229        GroupByTimeBucket = "groupByTimeBucket",
230        /// `having`.
231        Having = "having",
232        /// `distinct`.
233        Distinct = "distinct",
234        /// `join` (inner).
235        Join = "join",
236        /// `leftJoin`.
237        LeftJoin = "leftJoin",
238        /// `rightJoin`.
239        RightJoin = "rightJoin",
240        /// `crossJoin`.
241        CrossJoin = "crossJoin",
242        /// `fullOuterJoin`.
243        FullOuterJoin = "fullOuterJoin",
244        /// `naturalJoin`.
245        NaturalJoin = "naturalJoin",
246        /// `on`: a column-to-column join condition.
247        On = "on",
248        /// `union`.
249        Union = "union",
250        /// `unionAll`.
251        UnionAll = "unionAll",
252        /// `jsonContains`.
253        JsonContains = "jsonContains",
254        /// `jsonNotContains`.
255        JsonNotContains = "jsonNotContains",
256        /// `jsonOverlaps`.
257        JsonOverlaps = "jsonOverlaps",
258        /// `jsonPath`.
259        JsonPath = "jsonPath",
260        /// `orderVectorDistance`.
261        OrderVectorDistance = "orderVectorDistance",
262        /// `covers` (spatial).
263        Covers = "covers",
264        /// `notCovers` (spatial).
265        NotCovers = "notCovers",
266        /// `spatialEquals` (spatial).
267        SpatialEquals = "spatialEquals",
268        /// `notSpatialEquals` (spatial).
269        NotSpatialEquals = "notSpatialEquals",
270        /// `raw`: SQL used as given.
271        Raw = "raw",
272    }
273}
274
275impl Method {
276    /// Whether this is a comparison filter (`equal` through `notExists`).
277    ///
278    /// PHP: `isFilter()`.
279    pub fn is_filter(self) -> bool {
280        use Method::*;
281        matches!(
282            self,
283            Equal
284                | NotEqual
285                | LessThan
286                | LessThanEqual
287                | GreaterThan
288                | GreaterThanEqual
289                | Contains
290                | ContainsAny
291                | NotContains
292                | Search
293                | NotSearch
294                | IsNull
295                | IsNotNull
296                | Between
297                | NotBetween
298                | StartsWith
299                | NotStartsWith
300                | EndsWith
301                | NotEndsWith
302                | Regex
303                | Exists
304                | NotExists
305        )
306    }
307
308    /// Whether this is a spatial predicate.
309    ///
310    /// PHP: `isSpatial()`.
311    pub fn is_spatial(self) -> bool {
312        use Method::*;
313        matches!(
314            self,
315            Crosses
316                | NotCrosses
317                | DistanceEqual
318                | DistanceNotEqual
319                | DistanceGreaterThan
320                | DistanceLessThan
321                | Intersects
322                | NotIntersects
323                | Overlaps
324                | NotOverlaps
325                | Touches
326                | NotTouches
327                | Covers
328                | NotCovers
329                | SpatialEquals
330                | NotSpatialEquals
331        )
332    }
333
334    /// Whether this is a vector similarity filter.
335    ///
336    /// PHP: `isVector()`.
337    pub fn is_vector(self) -> bool {
338        matches!(self, Method::VectorDot | Method::VectorCosine | Method::VectorEuclidean)
339    }
340
341    /// Whether this is a JSON filter.
342    ///
343    /// PHP: `isJson()`.
344    pub fn is_json(self) -> bool {
345        matches!(self, Method::JsonContains | Method::JsonNotContains | Method::JsonOverlaps | Method::JsonPath)
346    }
347
348    /// Whether queries of this method hold other queries.
349    ///
350    /// PHP: `isNested()`.
351    pub fn is_nested(self) -> bool {
352        matches!(
353            self,
354            Method::And
355                | Method::Or
356                | Method::ElemMatch
357                | Method::Relationship
358                | Method::Having
359                | Method::Union
360                | Method::UnionAll
361        )
362    }
363
364    /// Whether this is an aggregate.
365    ///
366    /// PHP: `isAggregate()`.
367    pub fn is_aggregate(self) -> bool {
368        use Method::*;
369        matches!(
370            self,
371            Count
372                | CountDistinct
373                | Sum
374                | Avg
375                | Min
376                | Max
377                | Stddev
378                | StddevPop
379                | StddevSamp
380                | Variance
381                | VarPop
382                | VarSamp
383                | BitAnd
384                | BitOr
385                | BitXor
386        )
387    }
388
389    /// Whether a join's ON list may hold this method: `on` column
390    /// comparisons, the filters every builder compiles inside ON, and
391    /// `and`/`or` of those.
392    ///
393    /// PHP: `isJoinCondition()`.
394    pub fn is_join_condition(self) -> bool {
395        use Method::*;
396        matches!(
397            self,
398            On | Equal
399                | NotEqual
400                | GreaterThan
401                | GreaterThanEqual
402                | LessThan
403                | LessThanEqual
404                | Between
405                | NotBetween
406                | IsNull
407                | IsNotNull
408                | Contains
409                | ContainsAny
410                | NotContains
411                | StartsWith
412                | NotStartsWith
413                | EndsWith
414                | NotEndsWith
415                | And
416                | Or
417        )
418    }
419
420    /// Whether this is a join.
421    ///
422    /// PHP: `isJoin()`.
423    pub fn is_join(self) -> bool {
424        use Method::*;
425        matches!(self, Join | LeftJoin | RightJoin | CrossJoin | FullOuterJoin | NaturalJoin)
426    }
427
428    /// The standard SQL function of an aggregate (`SUM`, `COUNT`, ...), or
429    /// `None` when the method has no direct mapping.
430    ///
431    /// PHP: `sqlFunction()`.
432    ///
433    /// ```
434    /// use utopia_query::Method;
435    ///
436    /// assert_eq!(Method::StddevPop.sql_function(), Some("STDDEV_POP"));
437    /// assert_eq!(Method::Equal.sql_function(), None);
438    /// ```
439    ///
440    /// ```php
441    /// use Utopia\Query\Method;
442    ///
443    /// echo Method::StddevPop->sqlFunction(), "\n"; // STDDEV_POP
444    /// var_dump(Method::Equal->sqlFunction());      // NULL
445    /// ```
446    pub fn sql_function(self) -> Option<&'static str> {
447        use Method::*;
448        Some(match self {
449            Sum => "SUM",
450            Count | CountDistinct => "COUNT",
451            Avg => "AVG",
452            Min => "MIN",
453            Max => "MAX",
454            Stddev => "STDDEV",
455            StddevPop => "STDDEV_POP",
456            StddevSamp => "STDDEV_SAMP",
457            Variance => "VARIANCE",
458            VarPop => "VAR_POP",
459            VarSamp => "VAR_SAMP",
460            BitAnd => "BIT_AND",
461            BitOr => "BIT_OR",
462            BitXor => "BIT_XOR",
463            _ => return None,
464        })
465    }
466}