Skip to main content

utopia_query/builder/
feature.rs

1//! What only some dialects can do: each feature is a trait a dialect
2//! implements, and [`Builder`] has the feature's methods for the dialects
3//! that implement it (so `MySql::new().hint(...)` compiles and a ClickHouse
4//! builder has `prewhere`, while a MongoDB builder has neither).
5//!
6//! PHP: the interfaces of `Utopia\Query\Builder\Feature` (and their traits),
7//! which the builder classes implement.
8//!
9//! | PHP interface | Rust trait |
10//! |---|---|
11//! | `Feature\Locking` | [`Locking`] |
12//! | `Feature\Transactions` | [`Transactions`] |
13//! | `Feature\StatisticalAggregates` | [`StatisticalAggregates`] |
14//! | `Feature\BitwiseAggregates` | [`BitwiseAggregates`] |
15//! | `Feature\RawSql` | [`RawSql`] |
16//! | `Feature\CrossJoins` | [`CrossJoins`] |
17//! | `Feature\FullOuterJoins` | [`FullOuterJoins`] |
18//! | `Feature\LateralJoins` | [`LateralJoins`] |
19//! | `Feature\Json` | [`Json`] |
20//! | `Feature\Hints` | [`Hints`] |
21//! | `Feature\ConditionalAggregates` | [`ConditionalAggregates`] |
22//! | `Feature\StringAggregates` | [`StringAggregates`] |
23//! | `Feature\Rollup`, `Feature\Cube`, `Feature\Totals` | [`Rollup`], [`Cube`], [`Totals`] |
24//! | `Feature\Spatial` | [`Spatial`] |
25//! | `Feature\FullTextSearch`, `Feature\NegatedFullTextSearch` | [`FullTextSearch`], [`NegatedFullTextSearch`] |
26//! | `Feature\Upsert`, `Feature\UpsertSelect`, `Feature\InsertOrIgnore` | [`Upsert`], [`UpsertSelect`], [`InsertOrIgnore`] |
27//! | `Feature\TableSampling` | [`TableSampling`] |
28//! | `Feature\Sequences` | [`Sequences`] |
29//! | `Feature\MariaDB\Returning`, `Feature\PostgreSQL\Returning` | [`Returning`] |
30
31use crate::builder::core::{Builder, Dialect};
32use crate::builder::steps::{Arg, Ret, Step};
33use crate::builder::types::{ColumnPredicate, Condition, LockMode, Statement};
34use crate::builder::{AnyBuilder, CaseExpression, JoinType};
35use crate::error::{Error, Result};
36use crate::query::Query;
37use crate::value::{Array, IntoValue, IntoValues, Value};
38
39fn values(values: impl IntoValues) -> Vec<Value> {
40    values.into_values().values().cloned().collect()
41}
42
43/// `FOR UPDATE`, `FOR SHARE` and their `SKIP LOCKED` / `NOWAIT` forms.
44pub trait Locking: Dialect {}
45
46/// `BEGIN`, `COMMIT`, `ROLLBACK` and savepoints.
47pub trait Transactions: Dialect {}
48
49/// `STDDEV`, `VARIANCE` and their population/sample forms.
50pub trait StatisticalAggregates: Dialect {}
51
52/// `BIT_AND`, `BIT_OR`, `BIT_XOR`.
53pub trait BitwiseAggregates: Dialect {}
54
55/// Raw SQL in select, where, group, having and order clauses, casts, `CASE`
56/// expressions and raw assignments.
57pub trait RawSql: Dialect {}
58
59/// `CROSS JOIN` and `NATURAL JOIN`.
60pub trait CrossJoins: Dialect {}
61
62/// `FULL OUTER JOIN`.
63pub trait FullOuterJoins: Dialect {}
64
65/// `JOIN LATERAL (subquery)`.
66pub trait LateralJoins: Dialect {}
67
68/// `GROUP BY ... WITH ROLLUP` / `ROLLUP(...)`.
69pub trait Rollup: Dialect {
70    /// Sets the dialect's rollup modifier.
71    fn with_rollup(b: &mut Builder<Self>);
72}
73
74/// `GROUP BY CUBE(...)` / `WITH CUBE`.
75pub trait Cube: Dialect {
76    /// Sets the dialect's cube modifier.
77    fn with_cube(b: &mut Builder<Self>);
78}
79
80/// `WITH TOTALS` (ClickHouse).
81pub trait Totals: Dialect {
82    /// Sets the totals modifier.
83    fn with_totals(b: &mut Builder<Self>);
84}
85
86/// Optimizer hints.
87pub trait Hints: Dialect {
88    /// Adds a hint, validated by the dialect.
89    fn hint(b: &mut Builder<Self>, hint: &str) -> Result<()>;
90}
91
92/// `COUNT(CASE WHEN ... THEN 1 END)` and the other conditional aggregates.
93pub trait ConditionalAggregates: Dialect {
94    /// The select expression of `aggregate` over `column` (or `1` for counts)
95    /// where `condition` holds, with its alias.
96    fn aggregate_filter(
97        b: &mut Builder<Self>,
98        aggregate: &str,
99        column: Option<&str>,
100        condition: &str,
101        alias: &str,
102    ) -> Result<String> {
103        let then = match column {
104            None => "1".to_owned(),
105            Some(c) => b.resolve_and_wrap(c)?,
106        };
107        let mut expression = format!("{aggregate}(CASE WHEN {condition} THEN {then} END)");
108        if !alias.is_empty() {
109            expression.push_str(" AS ");
110            expression.push_str(&b.quote(alias)?);
111        }
112        Ok(expression)
113    }
114}
115
116/// The builder's own `groupConcatExpr()`, `jsonArrayAggExpr()` and `jsonObjectAggExpr()`.
117pub(crate) fn aggregates_base_step<D: StringAggregates>(step: Step, arguments: &[Arg<'_>]) -> Option<Result<Ret>> {
118    Some(Ok(Ret::Str(match (step, arguments) {
119        (Step::GroupConcatExpr, [Arg::Str(column), Arg::Str(order_by)]) => D::group_concat_expr(column, order_by),
120        (Step::JsonArrayAggExpr, [Arg::Str(column)]) => D::json_array_agg_expr(column),
121        (Step::JsonObjectAggExpr, [Arg::Str(key), Arg::Str(value)]) => D::json_object_agg_expr(key, value),
122        _ => return None,
123    })))
124}
125
126/// `GROUP_CONCAT` / `STRING_AGG`, `JSON_ARRAYAGG`, `JSON_OBJECTAGG`.
127pub trait StringAggregates: Dialect {
128    /// The concatenation of `column` (wrapped) with an `ORDER BY` fragment.
129    fn group_concat_expr(column: &str, order_by: &str) -> String;
130    /// The JSON array aggregate of `column`.
131    fn json_array_agg_expr(column: &str) -> String;
132    /// The JSON object aggregate of key and value columns.
133    fn json_object_agg_expr(key: &str, value: &str) -> String;
134}
135
136/// JSON filters and JSON column updates.
137pub trait Json: Dialect {
138    /// Appends `values` to a JSON array column.
139    fn set_json_append(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()>;
140    /// Prepends `values` to a JSON array column.
141    fn set_json_prepend(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()>;
142    /// Inserts `value` at `index` of a JSON array column.
143    fn set_json_insert(b: &mut Builder<Self>, column: &str, index: i64, value: Value) -> Result<()>;
144    /// Removes `value` from a JSON array column.
145    fn set_json_remove(b: &mut Builder<Self>, column: &str, value: Value) -> Result<()>;
146    /// Keeps the elements also in `values`.
147    fn set_json_intersect(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()>;
148    /// Removes the elements in `values`.
149    fn set_json_diff(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()>;
150    /// Removes duplicate elements.
151    fn set_json_unique(b: &mut Builder<Self>, column: &str) -> Result<()>;
152    /// Sets the value at a JSON path.
153    fn set_json_path(b: &mut Builder<Self>, column: &str, path: &str, value: Value) -> Result<()>;
154}
155
156/// Spatial filters.
157pub trait Spatial: Dialect {}
158
159/// `filterSearch()`: full-text search.
160pub trait FullTextSearch: Dialect {
161    /// Adds the search (MongoDB keeps it apart from filters).
162    fn filter_search(b: &mut Builder<Self>, attribute: &str, value: &str) -> Result<()> {
163        b.core.pending.push(Query::search(attribute, value));
164        Ok(())
165    }
166}
167
168/// `filterNotSearch()`.
169pub trait NegatedFullTextSearch: Dialect {}
170
171/// `upsert()`.
172pub trait Upsert: Dialect {
173    /// Compiles the upsert.
174    fn upsert(b: &mut Builder<Self>) -> Result<Statement>;
175}
176
177/// `upsertSelect()`.
178pub trait UpsertSelect: Dialect {
179    /// Compiles the upsert from a select.
180    fn upsert_select(b: &mut Builder<Self>) -> Result<Statement>;
181}
182
183/// `insertOrIgnore()`.
184pub trait InsertOrIgnore: Dialect {
185    /// Compiles the insert that skips conflicting rows.
186    fn insert_or_ignore(b: &mut Builder<Self>) -> Result<Statement>;
187}
188
189/// `TABLESAMPLE` / `SAMPLE`.
190pub trait TableSampling: Dialect {
191    /// Samples `percent` of the table with `method` (PHP's default `BERNOULLI`).
192    fn tablesample(b: &mut Builder<Self>, percent: f64, method: &str) -> Result<()>;
193}
194
195/// `nextVal()` and `currVal()` of sequences.
196pub trait Sequences: Dialect {
197    /// The select expression of `function` (`next` or `current`) on `sequence` (validated).
198    fn sequence_expression(b: &mut Builder<Self>, next: bool, sequence: &str) -> Result<String>;
199}
200
201/// `RETURNING` after inserts, updates and deletes.
202pub trait Returning: Dialect {}
203
204/// `/^[a-zA-Z_][a-zA-Z0-9_]*$/D`.
205pub(crate) fn is_plain_identifier(name: &str) -> bool {
206    let bytes = name.as_bytes();
207    match bytes.split_first() {
208        Some((first, rest)) => {
209            (first.is_ascii_alphabetic() || *first == b'_')
210                && rest.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'_')
211        }
212        None => false,
213    }
214}
215
216/// `/^[A-Za-z_][A-Za-z0-9_]*(\s+[A-Za-z_][A-Za-z0-9_]*)*(\s*\(\s*[A-Za-z0-9_,\s]+\s*\))?$/D`:
217/// a type name of words, with an optional parenthesised argument list.
218pub(crate) fn is_cast_type(text: &str) -> bool {
219    let text = text.as_bytes();
220    let is_space = |b: u8| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0B' | b'\x0C');
221    let word_start = |b: u8| b.is_ascii_alphabetic() || b == b'_';
222    let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
223    let mut i = 0;
224    if !text.first().is_some_and(|&b| word_start(b)) {
225        return false;
226    }
227    while i < text.len() && word(text[i]) {
228        i += 1;
229    }
230    loop {
231        // (\s+word)* — a run of spaces followed by a word; otherwise stop.
232        let mut j = i;
233        while j < text.len() && is_space(text[j]) {
234            j += 1;
235        }
236        if j > i && j < text.len() && word_start(text[j]) {
237            i = j;
238            while i < text.len() && word(text[i]) {
239                i += 1;
240            }
241        } else {
242            break;
243        }
244    }
245    if i == text.len() {
246        return true;
247    }
248    // (\s*\(\s*[A-Za-z0-9_,\s]+\s*\))?$
249    while i < text.len() && is_space(text[i]) {
250        i += 1;
251    }
252    if text.get(i) != Some(&b'(') || text.last() != Some(&b')') || i + 1 >= text.len() - 1 {
253        return false;
254    }
255    let inner = &text[i + 1..text.len() - 1];
256    inner.iter().all(|&b| word(b) || b == b',' || is_space(b))
257}
258
259impl<D: Locking> Builder<D> {
260    /// `FOR UPDATE`.
261    ///
262    /// PHP: `forUpdate()`.
263    pub fn for_update(&mut self) -> &mut Self {
264        self.core.lock_mode = Some(LockMode::ForUpdate);
265        self
266    }
267
268    /// `FOR SHARE`.
269    ///
270    /// PHP: `forShare()`.
271    pub fn for_share(&mut self) -> &mut Self {
272        self.core.lock_mode = Some(LockMode::ForShare);
273        self
274    }
275
276    /// `FOR UPDATE SKIP LOCKED`.
277    ///
278    /// PHP: `forUpdateSkipLocked()`.
279    pub fn for_update_skip_locked(&mut self) -> &mut Self {
280        self.core.lock_mode = Some(LockMode::ForUpdateSkipLocked);
281        self
282    }
283
284    /// `FOR UPDATE NOWAIT`.
285    ///
286    /// PHP: `forUpdateNoWait()`.
287    pub fn for_update_no_wait(&mut self) -> &mut Self {
288        self.core.lock_mode = Some(LockMode::ForUpdateNoWait);
289        self
290    }
291
292    /// `FOR SHARE SKIP LOCKED`.
293    ///
294    /// PHP: `forShareSkipLocked()`.
295    pub fn for_share_skip_locked(&mut self) -> &mut Self {
296        self.core.lock_mode = Some(LockMode::ForShareSkipLocked);
297        self
298    }
299
300    /// `FOR SHARE NOWAIT`.
301    ///
302    /// PHP: `forShareNoWait()`.
303    pub fn for_share_no_wait(&mut self) -> &mut Self {
304        self.core.lock_mode = Some(LockMode::ForShareNoWait);
305        self
306    }
307}
308
309impl<D: Transactions> Builder<D> {
310    /// `BEGIN`.
311    ///
312    /// PHP: `begin()`.
313    pub fn begin(&self) -> Statement {
314        Statement::with_parts("BEGIN", Vec::new(), false, self.core.executor.clone(), None)
315    }
316
317    /// `COMMIT`.
318    ///
319    /// PHP: `commit()`.
320    pub fn commit(&self) -> Statement {
321        Statement::with_parts("COMMIT", Vec::new(), false, self.core.executor.clone(), None)
322    }
323
324    /// `ROLLBACK`.
325    ///
326    /// PHP: `rollback()`.
327    pub fn rollback(&self) -> Statement {
328        Statement::with_parts("ROLLBACK", Vec::new(), false, self.core.executor.clone(), None)
329    }
330
331    /// `SAVEPOINT name`.
332    ///
333    /// PHP: `savepoint()`.
334    pub fn savepoint(&mut self, name: &str) -> Result<Statement> {
335        Ok(Statement::with_parts(
336            format!("SAVEPOINT {}", self.quote(name)?),
337            Vec::new(),
338            false,
339            self.core.executor.clone(),
340            None,
341        ))
342    }
343
344    /// `RELEASE SAVEPOINT name`.
345    ///
346    /// PHP: `releaseSavepoint()`.
347    pub fn release_savepoint(&mut self, name: &str) -> Result<Statement> {
348        Ok(Statement::with_parts(
349            format!("RELEASE SAVEPOINT {}", self.quote(name)?),
350            Vec::new(),
351            false,
352            self.core.executor.clone(),
353            None,
354        ))
355    }
356
357    /// `ROLLBACK TO SAVEPOINT name`.
358    ///
359    /// PHP: `rollbackToSavepoint()`.
360    pub fn rollback_to_savepoint(&mut self, name: &str) -> Result<Statement> {
361        Ok(Statement::with_parts(
362            format!("ROLLBACK TO SAVEPOINT {}", self.quote(name)?),
363            Vec::new(),
364            false,
365            self.core.executor.clone(),
366            None,
367        ))
368    }
369}
370
371impl<D: StatisticalAggregates> Builder<D> {
372    /// `STDDEV`.
373    ///
374    /// PHP: `stddev()`.
375    pub fn stddev(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
376        self.core.pending.push(Query::stddev(attribute, alias));
377        self
378    }
379
380    /// `STDDEV_POP`.
381    ///
382    /// PHP: `stddevPop()`.
383    pub fn stddev_pop(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
384        self.core.pending.push(Query::stddev_pop(attribute, alias));
385        self
386    }
387
388    /// `STDDEV_SAMP`.
389    ///
390    /// PHP: `stddevSamp()`.
391    pub fn stddev_samp(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
392        self.core.pending.push(Query::stddev_samp(attribute, alias));
393        self
394    }
395
396    /// `VARIANCE`.
397    ///
398    /// PHP: `variance()`.
399    pub fn variance(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
400        self.core.pending.push(Query::variance(attribute, alias));
401        self
402    }
403
404    /// `VAR_POP`.
405    ///
406    /// PHP: `varPop()`.
407    pub fn var_pop(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
408        self.core.pending.push(Query::var_pop(attribute, alias));
409        self
410    }
411
412    /// `VAR_SAMP`.
413    ///
414    /// PHP: `varSamp()`.
415    pub fn var_samp(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
416        self.core.pending.push(Query::var_samp(attribute, alias));
417        self
418    }
419}
420
421impl<D: BitwiseAggregates> Builder<D> {
422    /// `BIT_AND`.
423    ///
424    /// PHP: `bitAnd()`.
425    pub fn bit_and(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
426        self.core.pending.push(Query::bit_and(attribute, alias));
427        self
428    }
429
430    /// `BIT_OR`.
431    ///
432    /// PHP: `bitOr()`.
433    pub fn bit_or(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
434        self.core.pending.push(Query::bit_or(attribute, alias));
435        self
436    }
437
438    /// `BIT_XOR`.
439    ///
440    /// PHP: `bitXor()`.
441    pub fn bit_xor(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
442        self.core.pending.push(Query::bit_xor(attribute, alias));
443        self
444    }
445}
446
447impl<D: RawSql> Builder<D> {
448    /// `CAST(column AS type) [AS alias]`; the type must be a type name
449    /// (words, with an optional argument list).
450    ///
451    /// PHP: `selectCast()`.
452    pub fn select_cast(&mut self, column: &str, cast_type: &str, alias: &str) -> Result<&mut Self> {
453        if !is_cast_type(cast_type) {
454            return Err(Error::Validation(format!("Invalid cast type: {cast_type}")));
455        }
456        let mut expression = format!("CAST({} AS {cast_type})", self.resolve_and_wrap(column)?);
457        if !alias.is_empty() {
458            expression.push_str(" AS ");
459            expression.push_str(&self.quote(alias)?);
460        }
461        self.core.raw_selects.push(Condition::new(expression, Vec::new()));
462        Ok(self)
463    }
464
465    /// A raw `ORDER BY` expression.
466    ///
467    /// PHP: `orderByRaw()`.
468    pub fn order_by_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
469        self.core.raw_orders.push(Condition::new(expression, values(bindings)));
470        self
471    }
472
473    /// A raw `GROUP BY` expression.
474    ///
475    /// PHP: `groupByRaw()`.
476    pub fn group_by_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
477        self.core.raw_groups.push(Condition::new(expression, values(bindings)));
478        self
479    }
480
481    /// A raw `HAVING` condition.
482    ///
483    /// PHP: `havingRaw()`.
484    pub fn having_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
485        self.core.raw_havings.push(Condition::new(expression, values(bindings)));
486        self
487    }
488
489    /// A raw `WHERE` condition.
490    ///
491    /// PHP: `whereRaw()`.
492    pub fn where_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
493        self.core.raw_wheres.push(Condition::new(expression, values(bindings)));
494        self
495    }
496
497    /// `left operator right`, both columns.
498    ///
499    /// PHP: `whereColumn()`.
500    pub fn where_column(&mut self, left: &str, operator: &str, right: &str) -> Result<&mut Self> {
501        if !["=", "!=", "<>", "<", ">", "<=", ">="].contains(&operator) {
502            return Err(Error::Validation(format!("Invalid whereColumn operator: {operator}")));
503        }
504        self.core.column_predicates.push(ColumnPredicate::new(left, operator, right));
505        Ok(self)
506    }
507
508    /// A `CASE` expression in the select list.
509    ///
510    /// PHP: `selectCase()`.
511    pub fn select_case(&mut self, case: CaseExpression) -> &mut Self {
512        self.push_case(case);
513        self
514    }
515
516    /// `column = CASE ...` in an update.
517    ///
518    /// PHP: `setCase()`.
519    pub fn set_case(&mut self, column: impl Into<String>, case: CaseExpression) -> &mut Self {
520        self.core.case_sets.set(column, case);
521        self
522    }
523
524    /// `column = expression` in an update.
525    ///
526    /// PHP: `setRaw()`.
527    pub fn set_raw(
528        &mut self,
529        column: impl Into<String>,
530        expression: impl Into<String>,
531        bindings: impl IntoValues,
532    ) -> &mut Self {
533        let column = column.into();
534        self.core.raw_sets.set(column.clone(), expression.into());
535        self.core.raw_set_bindings.set(column, values(bindings));
536        self
537    }
538
539    /// `column = expression` in an upsert's conflict update.
540    ///
541    /// PHP: `conflictSetRaw()`.
542    pub fn conflict_set_raw(
543        &mut self,
544        column: impl Into<String>,
545        expression: impl Into<String>,
546        bindings: impl IntoValues,
547    ) -> &mut Self {
548        let column = column.into();
549        self.core.conflict_raw_sets.set(column.clone(), expression.into());
550        self.core.conflict_raw_set_bindings.set(column, values(bindings));
551        self
552    }
553
554    /// The SQL inserted for `column` instead of `?` (`ST_GeomFromText(?)`),
555    /// with extra bindings after the value.
556    ///
557    /// PHP: `insertColumnExpression()`.
558    pub fn insert_column_expression(
559        &mut self,
560        column: impl Into<String>,
561        expression: impl Into<String>,
562        extra_bindings: impl IntoValues,
563    ) -> &mut Self {
564        let column = column.into();
565        let extra = values(extra_bindings);
566        self.core.insert_column_expressions.set(column.clone(), expression.into());
567        if !extra.is_empty() {
568            self.core.insert_column_expression_bindings.set(column, extra);
569        }
570        self
571    }
572}
573
574impl<D: CrossJoins> Builder<D> {
575    /// `CROSS JOIN table [AS alias]`.
576    ///
577    /// PHP: `crossJoin()`.
578    pub fn cross_join(&mut self, table: impl Into<String>, alias: impl Into<String>) -> &mut Self {
579        self.core.pending.push(Query::new(crate::Method::CrossJoin, table, Array::default(), alias));
580        self
581    }
582
583    /// `NATURAL JOIN table [AS alias]`.
584    ///
585    /// PHP: `naturalJoin()`.
586    pub fn natural_join(&mut self, table: impl Into<String>, alias: impl Into<String>) -> &mut Self {
587        self.core.pending.push(Query::new(crate::Method::NaturalJoin, table, Array::default(), alias));
588        self
589    }
590}
591
592impl<D: FullOuterJoins> Builder<D> {
593    /// `FULL OUTER JOIN table ON left operator right`.
594    ///
595    /// PHP: `fullOuterJoin()`.
596    pub fn full_outer_join(
597        &mut self,
598        table: impl Into<String>,
599        left: &str,
600        right: &str,
601        operator: &str,
602        alias: impl Into<String>,
603    ) -> &mut Self {
604        let on = Query::on(left, right, operator);
605        self.core.pending.push(Query::new(crate::Method::FullOuterJoin, table, crate::value::list([on]), alias));
606        self
607    }
608}
609
610impl<D: LateralJoins> Builder<D> {
611    /// `[LEFT] JOIN LATERAL (subquery) AS alias ON true`.
612    ///
613    /// PHP: `joinLateral()`.
614    pub fn join_lateral(
615        &mut self,
616        subquery: Box<dyn AnyBuilder>,
617        alias: impl Into<String>,
618        join_type: JoinType,
619    ) -> &mut Self {
620        self.add_lateral(subquery, alias.into(), join_type);
621        self
622    }
623
624    /// `LEFT JOIN LATERAL`.
625    ///
626    /// PHP: `leftJoinLateral()`.
627    pub fn left_join_lateral(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
628        self.join_lateral(subquery, alias, JoinType::Left)
629    }
630}
631
632impl<D: Rollup> Builder<D> {
633    /// `WITH ROLLUP` / `ROLLUP(...)`.
634    ///
635    /// PHP: `withRollup()`.
636    pub fn with_rollup(&mut self) -> &mut Self {
637        D::with_rollup(self);
638        self
639    }
640}
641
642impl<D: Cube> Builder<D> {
643    /// `CUBE(...)` / `WITH CUBE`.
644    ///
645    /// PHP: `withCube()`.
646    pub fn with_cube(&mut self) -> &mut Self {
647        D::with_cube(self);
648        self
649    }
650}
651
652impl<D: Totals> Builder<D> {
653    /// `WITH TOTALS`.
654    ///
655    /// PHP: `withTotals()`.
656    pub fn with_totals(&mut self) -> &mut Self {
657        D::with_totals(self);
658        self
659    }
660}
661
662impl<D: Hints> Builder<D> {
663    /// An optimizer hint.
664    ///
665    /// PHP: `hint()`.
666    pub fn hint(&mut self, hint: &str) -> Result<&mut Self> {
667        D::hint(self, hint)?;
668        Ok(self)
669    }
670}
671
672impl<D: ConditionalAggregates> Builder<D> {
673    fn conditional(
674        &mut self,
675        aggregate: &str,
676        column: Option<&str>,
677        condition: &str,
678        alias: &str,
679        bindings: impl IntoValues,
680    ) -> Result<&mut Self> {
681        let expression = D::aggregate_filter(self, aggregate, column, condition, alias)?;
682        Ok(self.select_raw(expression, bindings))
683    }
684
685    /// `COUNT(CASE WHEN condition THEN 1 END) [AS alias]`.
686    ///
687    /// PHP: `countWhen()`.
688    pub fn count_when(&mut self, condition: &str, alias: &str, bindings: impl IntoValues) -> Result<&mut Self> {
689        self.conditional("COUNT", None, condition, alias, bindings)
690    }
691
692    /// `SUM(CASE WHEN condition THEN column END)`.
693    ///
694    /// PHP: `sumWhen()`.
695    pub fn sum_when(
696        &mut self,
697        column: &str,
698        condition: &str,
699        alias: &str,
700        bindings: impl IntoValues,
701    ) -> Result<&mut Self> {
702        self.conditional("SUM", Some(column), condition, alias, bindings)
703    }
704
705    /// `AVG(CASE WHEN ...)`.
706    ///
707    /// PHP: `avgWhen()`.
708    pub fn avg_when(
709        &mut self,
710        column: &str,
711        condition: &str,
712        alias: &str,
713        bindings: impl IntoValues,
714    ) -> Result<&mut Self> {
715        self.conditional("AVG", Some(column), condition, alias, bindings)
716    }
717
718    /// `MIN(CASE WHEN ...)`.
719    ///
720    /// PHP: `minWhen()`.
721    pub fn min_when(
722        &mut self,
723        column: &str,
724        condition: &str,
725        alias: &str,
726        bindings: impl IntoValues,
727    ) -> Result<&mut Self> {
728        self.conditional("MIN", Some(column), condition, alias, bindings)
729    }
730
731    /// `MAX(CASE WHEN ...)`.
732    ///
733    /// PHP: `maxWhen()`.
734    pub fn max_when(
735        &mut self,
736        column: &str,
737        condition: &str,
738        alias: &str,
739        bindings: impl IntoValues,
740    ) -> Result<&mut Self> {
741        self.conditional("MAX", Some(column), condition, alias, bindings)
742    }
743}
744
745impl<D: StringAggregates> Builder<D> {
746    /// The values of `column` concatenated with `separator`, optionally
747    /// ordered (`-column` descending).
748    ///
749    /// PHP: `groupConcat()`.
750    pub fn group_concat(
751        &mut self,
752        column: &str,
753        separator: &str,
754        alias: &str,
755        order_by: Option<&[String]>,
756    ) -> Result<&mut Self> {
757        let order = match order_by {
758            Some(columns) if !columns.is_empty() => format!("ORDER BY {}", self.compile_order_by_list(columns)?),
759            _ => String::new(),
760        };
761        let wrapped = self.resolve_and_wrap(column)?;
762        let mut expression = self.step_string(Step::GroupConcatExpr, &[Arg::Str(&wrapped), Arg::Str(&order)])?;
763        if !alias.is_empty() {
764            expression.push_str(" AS ");
765            expression.push_str(&self.quote(alias)?);
766        }
767        Ok(self.select_raw(expression, [separator]))
768    }
769
770    /// A JSON array of `column`'s values.
771    ///
772    /// PHP: `jsonArrayAgg()`.
773    pub fn json_array_agg(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
774        let wrapped = self.resolve_and_wrap(column)?;
775        let mut expression = self.step_string(Step::JsonArrayAggExpr, &[Arg::Str(&wrapped)])?;
776        if !alias.is_empty() {
777            expression.push_str(" AS ");
778            expression.push_str(&self.quote(alias)?);
779        }
780        Ok(self.select_raw(expression, Array::default()))
781    }
782
783    /// A JSON object of key and value columns.
784    ///
785    /// PHP: `jsonObjectAgg()`.
786    pub fn json_object_agg(&mut self, key_column: &str, value_column: &str, alias: &str) -> Result<&mut Self> {
787        let key = self.resolve_and_wrap(key_column)?;
788        let value = self.resolve_and_wrap(value_column)?;
789        let mut expression = self.step_string(Step::JsonObjectAggExpr, &[Arg::Str(&key), Arg::Str(&value)])?;
790        if !alias.is_empty() {
791            expression.push_str(" AS ");
792            expression.push_str(&self.quote(alias)?);
793        }
794        Ok(self.select_raw(expression, Array::default()))
795    }
796}
797
798impl<D: Json> Builder<D> {
799    /// The JSON column contains `value`.
800    ///
801    /// PHP: `filterJsonContains()`.
802    pub fn filter_json_contains(&mut self, attribute: impl Into<String>, value: impl IntoValue) -> &mut Self {
803        self.core.pending.push(Query::json_contains(attribute, value));
804        self
805    }
806
807    /// The JSON column does not contain `value`.
808    ///
809    /// PHP: `filterJsonNotContains()`.
810    pub fn filter_json_not_contains(&mut self, attribute: impl Into<String>, value: impl IntoValue) -> &mut Self {
811        self.core.pending.push(Query::json_not_contains(attribute, value));
812        self
813    }
814
815    /// The JSON array column shares an element with `values`.
816    ///
817    /// PHP: `filterJsonOverlaps()`.
818    pub fn filter_json_overlaps(&mut self, attribute: impl Into<String>, values: impl IntoValues) -> &mut Self {
819        self.core.pending.push(Query::json_overlaps(attribute, values.into_values()));
820        self
821    }
822
823    /// The value at `path` compares to `value`.
824    ///
825    /// PHP: `filterJsonPath()`.
826    pub fn filter_json_path(
827        &mut self,
828        attribute: impl Into<String>,
829        path: &str,
830        operator: &str,
831        value: impl IntoValue,
832    ) -> &mut Self {
833        self.core.pending.push(Query::json_path(attribute, path, operator, value));
834        self
835    }
836
837    /// Appends `values` to the JSON array column (in an update).
838    ///
839    /// PHP: `setJsonAppend()`.
840    pub fn set_json_append(&mut self, column: &str, values: impl IntoValues) -> Result<&mut Self> {
841        D::set_json_append(self, column, &values.into_values())?;
842        Ok(self)
843    }
844
845    /// Prepends `values`.
846    ///
847    /// PHP: `setJsonPrepend()`.
848    pub fn set_json_prepend(&mut self, column: &str, values: impl IntoValues) -> Result<&mut Self> {
849        D::set_json_prepend(self, column, &values.into_values())?;
850        Ok(self)
851    }
852
853    /// Inserts `value` at `index`.
854    ///
855    /// PHP: `setJsonInsert()`.
856    pub fn set_json_insert(&mut self, column: &str, index: i64, value: impl IntoValue) -> Result<&mut Self> {
857        D::set_json_insert(self, column, index, value.into_value())?;
858        Ok(self)
859    }
860
861    /// Removes `value`.
862    ///
863    /// PHP: `setJsonRemove()`.
864    pub fn set_json_remove(&mut self, column: &str, value: impl IntoValue) -> Result<&mut Self> {
865        D::set_json_remove(self, column, value.into_value())?;
866        Ok(self)
867    }
868
869    /// Keeps the elements also in `values`.
870    ///
871    /// PHP: `setJsonIntersect()`.
872    pub fn set_json_intersect(&mut self, column: &str, values: impl IntoValues) -> Result<&mut Self> {
873        D::set_json_intersect(self, column, &values.into_values())?;
874        Ok(self)
875    }
876
877    /// Removes the elements in `values`.
878    ///
879    /// PHP: `setJsonDiff()`.
880    pub fn set_json_diff(&mut self, column: &str, values: impl IntoValues) -> Result<&mut Self> {
881        D::set_json_diff(self, column, &values.into_values())?;
882        Ok(self)
883    }
884
885    /// Removes duplicates.
886    ///
887    /// PHP: `setJsonUnique()`.
888    pub fn set_json_unique(&mut self, column: &str) -> Result<&mut Self> {
889        D::set_json_unique(self, column)?;
890        Ok(self)
891    }
892
893    /// Sets the value at `path`.
894    ///
895    /// PHP: `setJsonPath()`.
896    pub fn set_json_path(&mut self, column: &str, path: &str, value: impl IntoValue) -> Result<&mut Self> {
897        D::set_json_path(self, column, path, value.into_value())?;
898        Ok(self)
899    }
900}
901
902impl<D: FullTextSearch> Builder<D> {
903    /// Full-text search on `attribute`.
904    ///
905    /// PHP: `filterSearch()`.
906    pub fn filter_search(&mut self, attribute: &str, value: &str) -> Result<&mut Self> {
907        D::filter_search(self, attribute, value)?;
908        Ok(self)
909    }
910}
911
912impl<D: NegatedFullTextSearch> Builder<D> {
913    /// Rows not matching a full-text search.
914    ///
915    /// PHP: `filterNotSearch()`.
916    pub fn filter_not_search(&mut self, attribute: &str, value: &str) -> &mut Self {
917        self.core.pending.push(Query::not_search(attribute, value));
918        self
919    }
920}
921
922impl<D: Upsert> Builder<D> {
923    /// Compiles the upsert (insert, updating the conflict columns on conflict).
924    ///
925    /// PHP: `upsert()`.
926    pub fn upsert(&mut self) -> Result<Statement> {
927        self.check_deferred()?;
928        D::upsert(self)
929    }
930}
931
932impl<D: UpsertSelect> Builder<D> {
933    /// Compiles the upsert from the select source.
934    ///
935    /// PHP: `upsertSelect()`.
936    pub fn upsert_select(&mut self) -> Result<Statement> {
937        self.check_deferred()?;
938        D::upsert_select(self)
939    }
940}
941
942impl<D: InsertOrIgnore> Builder<D> {
943    /// Compiles an insert that skips rows that conflict.
944    ///
945    /// PHP: `insertOrIgnore()`.
946    pub fn insert_or_ignore(&mut self) -> Result<Statement> {
947        self.check_deferred()?;
948        D::insert_or_ignore(self)
949    }
950}
951
952impl<D: TableSampling> Builder<D> {
953    /// Samples the table.
954    ///
955    /// PHP: `tablesample()`.
956    pub fn tablesample(&mut self, percent: f64, method: &str) -> Result<&mut Self> {
957        D::tablesample(self, percent, method)?;
958        Ok(self)
959    }
960}
961
962impl<D: Sequences> Builder<D> {
963    fn sequence(&mut self, next: bool, sequence: &str, alias: &str) -> Result<&mut Self> {
964        if !is_plain_identifier(sequence) {
965            return Err(Error::Validation(format!("Invalid sequence name: {sequence}")));
966        }
967        let mut expression = D::sequence_expression(self, next, sequence)?;
968        if !alias.is_empty() {
969            if !is_plain_identifier(alias) {
970                return Err(Error::Validation(format!("Invalid sequence alias: {alias}")));
971            }
972            expression.push_str(" AS ");
973            expression.push_str(&self.quote(alias)?);
974        }
975        Ok(self.select_raw(expression, Array::default()))
976    }
977
978    /// The next value of `sequence`.
979    ///
980    /// PHP: `nextVal()`.
981    pub fn next_val(&mut self, sequence: &str, alias: &str) -> Result<&mut Self> {
982        self.sequence(true, sequence, alias)
983    }
984
985    /// The current value of `sequence`.
986    ///
987    /// PHP: `currVal()`.
988    pub fn curr_val(&mut self, sequence: &str, alias: &str) -> Result<&mut Self> {
989        self.sequence(false, sequence, alias)
990    }
991}
992
993impl<D: Returning> Builder<D> {
994    /// The columns returned after inserts, updates and deletes (`["*"]` for all;
995    /// empty to stop returning).
996    ///
997    /// PHP: `returning()`.
998    pub fn returning<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
999        self.core.returning = columns.into_iter().map(Into::into).collect();
1000        self
1001    }
1002}
1003
1004impl<D: Spatial> Builder<D> {
1005    /// The distance from `point` (`[x, y]`) compares to `distance` with
1006    /// `operator` (`<`, `>`, `=`, `!=`; anything else is `<`), in meters when
1007    /// `meters`. Fails with [`Error::Validation`](crate::Error::Validation)
1008    /// unless `point` is an `[x, y]` pair of finite numbers.
1009    ///
1010    /// PHP: `filterDistance()`.
1011    pub fn filter_distance(
1012        &mut self,
1013        attribute: impl Into<String>,
1014        point: &Array,
1015        operator: &str,
1016        distance: f64,
1017        meters: bool,
1018    ) -> crate::Result<&mut Self> {
1019        let point = Value::Array(point.clone());
1020        let wkt = format!("POINT({})", crate::builder::sql::point_wkt(Some(&point))?);
1021        let method = match operator {
1022            ">" => crate::Method::DistanceGreaterThan,
1023            "=" => crate::Method::DistanceEqual,
1024            "!=" => crate::Method::DistanceNotEqual,
1025            _ => crate::Method::DistanceLessThan,
1026        };
1027        let tuple = crate::value::list([crate::value::string(wkt), Value::Float(distance), Value::Bool(meters)]);
1028        self.core.pending.push(Query::new(method, attribute, crate::value::list([Value::Array(tuple)]), ""));
1029        Ok(self)
1030    }
1031
1032    /// The geometry column intersects `geometry`.
1033    ///
1034    /// PHP: `filterIntersects()`.
1035    pub fn filter_intersects(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1036        self.core.pending.push(Query::intersects(attribute, geometry));
1037        self
1038    }
1039
1040    /// Does not intersect.
1041    ///
1042    /// PHP: `filterNotIntersects()`.
1043    pub fn filter_not_intersects(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1044        self.core.pending.push(Query::not_intersects(attribute, geometry));
1045        self
1046    }
1047
1048    /// Crosses.
1049    ///
1050    /// PHP: `filterCrosses()`.
1051    pub fn filter_crosses(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1052        self.core.pending.push(Query::crosses(attribute, geometry));
1053        self
1054    }
1055
1056    /// Does not cross.
1057    ///
1058    /// PHP: `filterNotCrosses()`.
1059    pub fn filter_not_crosses(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1060        self.core.pending.push(Query::not_crosses(attribute, geometry));
1061        self
1062    }
1063
1064    /// Overlaps.
1065    ///
1066    /// PHP: `filterOverlaps()`.
1067    pub fn filter_overlaps(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1068        self.core.pending.push(Query::overlaps(attribute, geometry));
1069        self
1070    }
1071
1072    /// Does not overlap.
1073    ///
1074    /// PHP: `filterNotOverlaps()`.
1075    pub fn filter_not_overlaps(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1076        self.core.pending.push(Query::not_overlaps(attribute, geometry));
1077        self
1078    }
1079
1080    /// Touches.
1081    ///
1082    /// PHP: `filterTouches()`.
1083    pub fn filter_touches(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1084        self.core.pending.push(Query::touches(attribute, geometry));
1085        self
1086    }
1087
1088    /// Does not touch.
1089    ///
1090    /// PHP: `filterNotTouches()`.
1091    pub fn filter_not_touches(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1092        self.core.pending.push(Query::not_touches(attribute, geometry));
1093        self
1094    }
1095
1096    /// Covers.
1097    ///
1098    /// PHP: `filterCovers()`.
1099    pub fn filter_covers(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1100        self.core.pending.push(Query::covers(attribute, geometry));
1101        self
1102    }
1103
1104    /// Does not cover.
1105    ///
1106    /// PHP: `filterNotCovers()`.
1107    pub fn filter_not_covers(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1108        self.core.pending.push(Query::not_covers(attribute, geometry));
1109        self
1110    }
1111
1112    /// Spatially equal.
1113    ///
1114    /// PHP: `filterSpatialEquals()`.
1115    pub fn filter_spatial_equals(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1116        self.core.pending.push(Query::spatial_equals(attribute, geometry));
1117        self
1118    }
1119
1120    /// Not spatially equal.
1121    ///
1122    /// PHP: `filterNotSpatialEquals()`.
1123    pub fn filter_not_spatial_equals(&mut self, attribute: impl Into<String>, geometry: Array) -> &mut Self {
1124        self.core.pending.push(Query::not_spatial_equals(attribute, geometry));
1125        self
1126    }
1127}