Skip to main content

utopia_query/builder/
types.rs

1//! The values builders produce and keep: statements, conditions, join and
2//! window definitions.
3
4use std::fmt;
5use std::sync::Arc;
6
7use crate::error::{Error, Result};
8use crate::method::backed_enum;
9use crate::value::{Array, Value};
10
11/// What runs a statement: given it, returns its rows (an array) or an
12/// affected-row count (an integer).
13///
14/// PHP: the `Closure(Statement): (array|int)` of `setExecutor()` / `withExecutor()`.
15pub type Executor = Arc<dyn Fn(&Statement) -> Result<Value> + Send + Sync>;
16
17/// A compiled statement: the SQL (or MongoDB command JSON) with `?`
18/// placeholders and the values bound to them, in order.
19///
20/// PHP: `Utopia\Query\Builder\Statement`.
21#[derive(Clone)]
22pub struct Statement {
23    /// The statement text.
24    pub query: String,
25    /// The values of the placeholders, in order.
26    pub bindings: Vec<Value>,
27    /// Whether the statement only reads.
28    pub read_only: bool,
29    /// Named parameters (ClickHouse's `{name:Type}` placeholders), if any.
30    pub named_bindings: Option<Array>,
31    executor: Option<Executor>,
32}
33
34impl fmt::Debug for Statement {
35    /// The statement without its executor.
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.debug_struct("Statement")
38            .field("query", &self.query)
39            .field("bindings", &self.bindings)
40            .field("read_only", &self.read_only)
41            .field("named_bindings", &self.named_bindings)
42            .field("executor", &self.executor.is_some())
43            .finish()
44    }
45}
46
47impl PartialEq for Statement {
48    /// Same text, bindings and flags (executors are not compared).
49    fn eq(&self, other: &Self) -> bool {
50        self.query == other.query
51            && self.bindings == other.bindings
52            && self.read_only == other.read_only
53            && self.named_bindings == other.named_bindings
54    }
55}
56
57impl Statement {
58    /// A statement that is not read-only and has no executor.
59    ///
60    /// PHP: `new Statement($query, $bindings)`.
61    pub fn new(query: impl Into<String>, bindings: Vec<Value>) -> Self {
62        Statement { query: query.into(), bindings, read_only: false, named_bindings: None, executor: None }
63    }
64
65    /// Every part of a statement.
66    ///
67    /// PHP: `new Statement($query, $bindings, $readOnly, $executor, $namedBindings)`.
68    pub fn with_parts(
69        query: impl Into<String>,
70        bindings: Vec<Value>,
71        read_only: bool,
72        executor: Option<Executor>,
73        named_bindings: Option<Array>,
74    ) -> Self {
75        Statement { query: query.into(), bindings, read_only, named_bindings, executor }
76    }
77
78    /// Runs the statement with its executor.
79    ///
80    /// PHP: `execute()`, which throws `BadMethodCallException` ([`Error::NoExecutor`]) without one.
81    pub fn execute(&self) -> Result<Value> {
82        match &self.executor {
83            Some(executor) => executor(self),
84            None => Err(Error::NoExecutor("No executor configured on this plan".into())),
85        }
86    }
87
88    /// The same statement run by `executor`.
89    ///
90    /// PHP: `withExecutor()`.
91    pub fn with_executor(&self, executor: Executor) -> Statement {
92        Statement { executor: Some(executor), ..self.clone() }
93    }
94
95    /// The executor, if any.
96    pub fn executor(&self) -> Option<&Executor> {
97        self.executor.as_ref()
98    }
99}
100
101/// A binding captured while compiling: the value and the column it was
102/// compared to, when known (ClickHouse types named parameters by column).
103///
104/// PHP: `Utopia\Query\Builder\Binding`.
105#[derive(Debug, Clone, PartialEq)]
106pub struct Binding {
107    /// The value.
108    pub value: Value,
109    /// The raw column name, if the value was bound against one.
110    pub column: Option<String>,
111}
112
113impl Binding {
114    /// A binding of `value` against `column`.
115    pub fn new(value: Value, column: Option<String>) -> Self {
116        Binding { value, column }
117    }
118}
119
120/// A SQL fragment with its bindings.
121///
122/// PHP: `Utopia\Query\Builder\Condition`.
123#[derive(Debug, Clone, PartialEq)]
124pub struct Condition {
125    /// The SQL, with `?` placeholders.
126    pub expression: String,
127    /// The values of the placeholders.
128    pub bindings: Vec<Value>,
129}
130
131impl Condition {
132    /// A fragment with its bindings.
133    pub fn new(expression: impl Into<String>, bindings: Vec<Value>) -> Self {
134        Condition { expression: expression.into(), bindings }
135    }
136}
137
138/// `left operator right`, both columns.
139///
140/// PHP: `Utopia\Query\Builder\ColumnPredicate`.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct ColumnPredicate {
143    /// The left column.
144    pub left: String,
145    /// The operator.
146    pub operator: String,
147    /// The right column.
148    pub right: String,
149}
150
151impl ColumnPredicate {
152    /// A column comparison.
153    pub fn new(left: impl Into<String>, operator: impl Into<String>, right: impl Into<String>) -> Self {
154        ColumnPredicate { left: left.into(), operator: operator.into(), right: right.into() }
155    }
156}
157
158/// A common table expression, compiled.
159///
160/// PHP: `Utopia\Query\Builder\CteClause`.
161#[derive(Debug, Clone, PartialEq)]
162pub struct CteClause {
163    /// The name.
164    pub name: String,
165    /// The SQL.
166    pub query: String,
167    /// The bindings of the SQL.
168    pub bindings: Vec<Value>,
169    /// Whether it is recursive.
170    pub recursive: bool,
171    /// The column names, if given.
172    pub columns: Vec<String>,
173}
174
175impl CteClause {
176    /// A compiled CTE.
177    pub fn new(
178        name: impl Into<String>,
179        query: impl Into<String>,
180        bindings: Vec<Value>,
181        recursive: bool,
182        columns: Vec<String>,
183    ) -> Self {
184        CteClause { name: name.into(), query: query.into(), bindings, recursive, columns }
185    }
186}
187
188/// A column-to-column condition of a join built with a [`JoinBuilder`](super::JoinBuilder).
189///
190/// PHP: `Utopia\Query\Builder\JoinOn`.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct JoinOn {
193    /// The left column.
194    pub left: String,
195    /// The operator.
196    pub operator: String,
197    /// The right column.
198    pub right: String,
199}
200
201impl JoinOn {
202    /// A join condition.
203    pub fn new(left: impl Into<String>, operator: impl Into<String>, right: impl Into<String>) -> Self {
204        JoinOn { left: left.into(), operator: operator.into(), right: right.into() }
205    }
206}
207
208backed_enum! {
209    /// A kind of join, as its SQL keyword.
210    ///
211    /// PHP: `Utopia\Query\Builder\JoinType`.
212    pub enum JoinType: "Utopia\\Query\\Builder\\JoinType" {
213        /// `JOIN`.
214        Inner = "JOIN",
215        /// `LEFT JOIN`.
216        Left = "LEFT JOIN",
217        /// `RIGHT JOIN`.
218        Right = "RIGHT JOIN",
219        /// `CROSS JOIN`.
220        Cross = "CROSS JOIN",
221        /// `FULL OUTER JOIN`.
222        FullOuter = "FULL OUTER JOIN",
223        /// `NATURAL JOIN`.
224        Natural = "NATURAL JOIN",
225    }
226}
227
228backed_enum! {
229    /// A row lock, as its SQL.
230    ///
231    /// PHP: `Utopia\Query\Builder\LockMode`.
232    pub enum LockMode: "Utopia\\Query\\Builder\\LockMode" {
233        /// `FOR UPDATE`.
234        ForUpdate = "FOR UPDATE",
235        /// `FOR SHARE`.
236        ForShare = "FOR SHARE",
237        /// `FOR UPDATE SKIP LOCKED`.
238        ForUpdateSkipLocked = "FOR UPDATE SKIP LOCKED",
239        /// `FOR UPDATE NOWAIT`.
240        ForUpdateNoWait = "FOR UPDATE NOWAIT",
241        /// `FOR SHARE SKIP LOCKED`.
242        ForShareSkipLocked = "FOR SHARE SKIP LOCKED",
243        /// `FOR SHARE NOWAIT`.
244        ForShareNoWait = "FOR SHARE NOWAIT",
245    }
246}
247
248impl LockMode {
249    /// The SQL.
250    ///
251    /// PHP: `toSql()`.
252    pub fn to_sql(self) -> &'static str {
253        self.as_str()
254    }
255}
256
257backed_enum! {
258    /// How a compound select combines its members.
259    ///
260    /// PHP: `Utopia\Query\Builder\UnionType`.
261    pub enum UnionType: "Utopia\\Query\\Builder\\UnionType" {
262        /// `UNION`.
263        Union = "UNION",
264        /// `UNION ALL`.
265        UnionAll = "UNION ALL",
266        /// `INTERSECT`.
267        Intersect = "INTERSECT",
268        /// `INTERSECT ALL`.
269        IntersectAll = "INTERSECT ALL",
270        /// `EXCEPT`.
271        Except = "EXCEPT",
272        /// `EXCEPT ALL`.
273        ExceptAll = "EXCEPT ALL",
274    }
275}
276
277/// A compiled member of a compound select.
278///
279/// PHP: `Utopia\Query\Builder\UnionClause`.
280#[derive(Debug, Clone, PartialEq)]
281pub struct UnionClause {
282    /// How it combines.
283    pub union_type: UnionType,
284    /// The SQL.
285    pub query: String,
286    /// Its bindings.
287    pub bindings: Vec<Value>,
288}
289
290impl UnionClause {
291    /// A compiled member.
292    pub fn new(union_type: UnionType, query: impl Into<String>, bindings: Vec<Value>) -> Self {
293        UnionClause { union_type, query: query.into(), bindings }
294    }
295}
296
297backed_enum! {
298    /// A vector distance metric (pgvector).
299    ///
300    /// PHP: `Utopia\Query\Builder\VectorMetric`.
301    pub enum VectorMetric: "Utopia\\Query\\Builder\\VectorMetric" {
302        /// Cosine distance.
303        Cosine = "cosine",
304        /// Euclidean distance.
305        Euclidean = "euclidean",
306        /// Negative inner product.
307        Dot = "dot",
308    }
309}
310
311impl VectorMetric {
312    /// The pgvector operator: `<=>`, `<->` or `<#>`.
313    ///
314    /// PHP: `toOperator()`.
315    pub fn to_operator(self) -> &'static str {
316        match self {
317            VectorMetric::Cosine => "<=>",
318            VectorMetric::Euclidean => "<->",
319            VectorMetric::Dot => "<#>",
320        }
321    }
322}
323
324/// A window frame: `ROWS UNBOUNDED PRECEDING`, `RANGE BETWEEN ... AND ...`.
325///
326/// PHP: `Utopia\Query\Builder\WindowFrame`.
327#[derive(Debug, Clone, PartialEq, Eq)]
328pub struct WindowFrame {
329    /// `ROWS`, `RANGE` or `GROUPS`.
330    pub frame_type: String,
331    /// The start bound.
332    pub start: String,
333    /// The end bound, if any.
334    pub end: Option<String>,
335}
336
337impl WindowFrame {
338    /// A frame.
339    pub fn new(frame_type: impl Into<String>, start: impl Into<String>, end: Option<String>) -> Self {
340        WindowFrame { frame_type: frame_type.into(), start: start.into(), end }
341    }
342
343    /// The SQL.
344    ///
345    /// PHP: `toSql()`.
346    pub fn to_sql(&self) -> String {
347        match &self.end {
348            None => format!("{} {}", self.frame_type, self.start),
349            Some(end) => format!("{} BETWEEN {} AND {}", self.frame_type, self.start, end),
350        }
351    }
352}
353
354/// A named window: `WINDOW name AS (...)`.
355///
356/// PHP: `Utopia\Query\Builder\WindowDefinition`.
357#[derive(Debug, Clone, PartialEq, Eq)]
358pub struct WindowDefinition {
359    /// The name.
360    pub name: String,
361    /// The partition columns, if any.
362    pub partition_by: Option<Vec<String>>,
363    /// The order columns (`-col` descending), if any.
364    pub order_by: Option<Vec<String>>,
365    /// The frame, if any.
366    pub frame: Option<WindowFrame>,
367}
368
369impl WindowDefinition {
370    /// A named window.
371    pub fn new(
372        name: impl Into<String>,
373        partition_by: Option<Vec<String>>,
374        order_by: Option<Vec<String>>,
375        frame: Option<WindowFrame>,
376    ) -> Self {
377        WindowDefinition { name: name.into(), partition_by, order_by, frame }
378    }
379}
380
381/// A window function in the select list.
382///
383/// PHP: `Utopia\Query\Builder\WindowSelect`.
384#[derive(Debug, Clone, PartialEq, Eq)]
385pub struct WindowSelect {
386    /// The function call (`ROW_NUMBER()`).
387    pub function: String,
388    /// The alias.
389    pub alias: String,
390    /// The partition columns, if any.
391    pub partition_by: Option<Vec<String>>,
392    /// The order columns (`-col` descending), if any.
393    pub order_by: Option<Vec<String>>,
394    /// A named window used instead of an inline one.
395    pub window_name: Option<String>,
396    /// The frame, if any.
397    pub frame: Option<WindowFrame>,
398}
399
400impl WindowSelect {
401    /// A window function.
402    pub fn new(
403        function: impl Into<String>,
404        alias: impl Into<String>,
405        partition_by: Option<Vec<String>>,
406        order_by: Option<Vec<String>>,
407        window_name: Option<String>,
408        frame: Option<WindowFrame>,
409    ) -> Self {
410        WindowSelect { function: function.into(), alias: alias.into(), partition_by, order_by, window_name, frame }
411    }
412}
413
414/// A `MERGE` action and its bindings.
415///
416/// PHP: `Utopia\Query\Builder\MergeClause`.
417#[derive(Debug, Clone, PartialEq)]
418pub struct MergeClause {
419    /// The action SQL.
420    pub action: String,
421    /// Whether it applies to matched rows.
422    pub matched: bool,
423    /// Its bindings.
424    pub bindings: Vec<Value>,
425}
426
427impl MergeClause {
428    /// A merge action.
429    pub fn new(action: impl Into<String>, matched: bool, bindings: Vec<Value>) -> Self {
430        MergeClause { action: action.into(), matched, bindings }
431    }
432}
433
434/// The geometry, distance and unit of a `distance*` query.
435///
436/// PHP: `Utopia\Query\Builder\SpatialDistanceFilter`.
437#[derive(Debug, Clone, PartialEq)]
438pub struct SpatialDistanceFilter {
439    /// WKT, or a coordinate array.
440    pub geometry: Value,
441    /// The distance threshold.
442    pub distance: f64,
443    /// Whether the distance is in meters (sphere / geography).
444    pub meters: bool,
445}
446
447impl SpatialDistanceFilter {
448    /// A distance filter.
449    pub fn new(geometry: Value, distance: f64, meters: bool) -> Self {
450        SpatialDistanceFilter { geometry, distance, meters }
451    }
452
453    /// The filter from the `[geometry, distance, meters]` value of a `distance*` query.
454    ///
455    /// PHP: `SpatialDistanceFilter::fromTuple()`.
456    /// Fails with [`Error::Validation`] unless the geometry is a WKT string
457    /// or a coordinate array, the distance a finite number (a numeric
458    /// string counts), and `meters` a boolean as `FILTER_VALIDATE_BOOL`
459    /// reads one (`true`, `1`, `"on"`, `"no"`, ...; absent is `false`).
460    pub fn from_tuple(tuple: &Array) -> crate::Result<Self> {
461        let at = |i: i64| tuple.get(&php_std::ArrayKey::Int(i)).filter(|v| !matches!(v, Value::Null));
462        let geometry = match at(0) {
463            Some(g @ (Value::Str(_) | Value::Array(_))) => g.clone(),
464            _ => {
465                return Err(Error::Validation(
466                    "Invalid distance query: the geometry must be a WKT string or a coordinate array".into(),
467                ));
468            }
469        };
470        let distance = at(1).filter(|d| crate::query::is_numeric(d)).map(Value::to_double);
471        let Some(distance) = distance.filter(|d| d.is_finite()) else {
472            return Err(Error::Validation("Invalid distance query: the distance must be a finite number".into()));
473        };
474        let Some(meters) = at(2).map_or(Some(false), filter_bool) else {
475            return Err(Error::Validation("Invalid distance query: meters must be a boolean".into()));
476        };
477        Ok(SpatialDistanceFilter { geometry, distance, meters })
478    }
479}
480
481/// `filter_var($value, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE)`:
482/// `None` when the value is not a boolean.
483fn filter_bool(value: &Value) -> Option<bool> {
484    use php_std::filter as f;
485    let value = match value {
486        Value::Null => f::Value::Null,
487        Value::Bool(b) => f::Value::Bool(*b),
488        Value::Int(i) => f::Value::Int(*i),
489        Value::Float(x) => f::Value::Float(*x),
490        Value::Str(s) => f::Value::Str(s.as_bytes().to_vec()),
491        // Neither an array nor an object without `__toString()` is a scalar.
492        _ => return None,
493    };
494    match f::filter_var(&value, f::FILTER_VALIDATE_BOOL, &f::Options::Flags(f::FILTER_NULL_ON_FAILURE)) {
495        Ok(f::Filtered { value: f::Value::Bool(b), .. }) => Some(b),
496        _ => None,
497    }
498}