Skip to main content

utopia_query/builder/
api.rs

1//! The public API every builder has: selects, aggregates, joins, unions,
2//! CTEs, inserts, updates, deletes, hooks and window functions.
3
4use std::sync::Arc;
5
6use crate::builder::AnyBuilder;
7use crate::builder::case::CaseExpression;
8use crate::builder::core::{
9    AfterBuild, Builder, Dialect, ExistsSubquery, ExplainOptions, LateralJoin, SubSelect, WhereInSubquery,
10};
11use crate::builder::join::JoinBuilder;
12use crate::builder::steps::{Arg, Step};
13use crate::builder::types::{
14    CteClause, Executor, JoinType, Statement, UnionClause, UnionType, WindowDefinition, WindowFrame, WindowSelect,
15};
16use crate::enums::NullsPosition;
17use crate::error::{Error, Result};
18use crate::hook::Hook;
19use crate::method::Method;
20use crate::query::{Compiler, Query};
21use crate::value::{Array, IntoValues, Value};
22
23fn strings<S: Into<String>>(items: impl IntoIterator<Item = S>) -> Vec<String> {
24    items.into_iter().map(Into::into).collect()
25}
26
27/// `/^[A-Za-z_][A-Za-z0-9_]*\s*\(\s*[A-Za-z0-9_,.\s*"`]*\s*\)$/` on the
28/// trimmed function, with `/D` (`$` only at the very end).
29fn is_window_function(function: &str) -> bool {
30    let text = function.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
31    let text = text.as_bytes();
32    let is_space = |b: u8| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0B' | b'\x0C');
33    let mut i = 0;
34    match text.first() {
35        Some(b) if b.is_ascii_alphabetic() || *b == b'_' => i += 1,
36        _ => return false,
37    }
38    while i < text.len() && (text[i].is_ascii_alphanumeric() || text[i] == b'_') {
39        i += 1;
40    }
41    while i < text.len() && is_space(text[i]) {
42        i += 1;
43    }
44    if text.get(i) != Some(&b'(') || text.last() != Some(&b')') || i == text.len() - 1 {
45        return false;
46    }
47    text[i + 1..text.len() - 1]
48        .iter()
49        .all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b',' | b'.' | b'*' | b'"' | b'`') || is_space(b))
50}
51
52impl<D: Dialect> Builder<D> {
53    /// The table (and its alias) to select from, update or delete from; an
54    /// empty table makes a select without `FROM`.
55    ///
56    /// PHP: `from($table, $alias)`.
57    ///
58    /// On a builder with a [`Scope`](crate::builder::Scope), a non-empty
59    /// table is a collection id read through the scope (see
60    /// [`Builder::scope`]).
61    pub fn from(&mut self, table: impl Into<String>, alias: impl Into<String>) -> &mut Self {
62        self.scoped_from(table.into(), alias.into())
63    }
64
65    /// The refusal a call returning the builder kept for the next
66    /// statement, taken: PHP throws it from that call (`from()` of another
67    /// collection or alias on a bound builder, `into()` and the dialects'
68    /// multi-table writes once a collection is bound).
69    ///
70    /// PHP: `ScopesCollections::from()`, `requireUnbound()`.
71    pub fn take_refusal(&mut self) -> Option<crate::Error> {
72        self.core.deferred.take()
73    }
74
75    /// A select without `FROM`.
76    ///
77    /// PHP: `fromNone()`.
78    pub fn from_none(&mut self) -> &mut Self {
79        self.from("", "")
80    }
81
82    /// `FROM (subquery) AS alias`.
83    ///
84    /// PHP: `fromSub()`.
85    pub fn from_sub(&mut self, subquery: impl AnyBuilder + 'static, alias: impl Into<String>) -> &mut Self {
86        self.from_sub_boxed(Box::new(subquery), alias)
87    }
88
89    /// [`Builder::from_sub`] with a boxed builder.
90    pub fn from_sub_boxed(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
91        self.core.from_subquery = Some(SubSelect { subquery, alias: alias.into() });
92        self.core.table.clear();
93        self
94    }
95
96    /// `(subquery) AS alias` in the select list.
97    ///
98    /// PHP: `selectSub()`.
99    pub fn select_sub(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
100        self.core.sub_selects.push(SubSelect { subquery, alias: alias.into() });
101        self
102    }
103
104    /// `column IN (subquery)`.
105    ///
106    /// PHP: `filterWhereIn()`.
107    pub fn filter_where_in(&mut self, column: impl Into<String>, subquery: Box<dyn AnyBuilder>) -> &mut Self {
108        self.core.where_in_subqueries.push(WhereInSubquery { column: column.into(), subquery, not: false });
109        self
110    }
111
112    /// `column NOT IN (subquery)`.
113    ///
114    /// PHP: `filterWhereNotIn()`.
115    pub fn filter_where_not_in(&mut self, column: impl Into<String>, subquery: Box<dyn AnyBuilder>) -> &mut Self {
116        self.core.where_in_subqueries.push(WhereInSubquery { column: column.into(), subquery, not: true });
117        self
118    }
119
120    /// `EXISTS (subquery)`.
121    ///
122    /// PHP: `filterExists()`.
123    pub fn filter_exists(&mut self, subquery: Box<dyn AnyBuilder>) -> &mut Self {
124        self.core.exists_subqueries.push(ExistsSubquery { subquery, not: false });
125        self
126    }
127
128    /// `NOT EXISTS (subquery)`.
129    ///
130    /// PHP: `filterNotExists()`.
131    pub fn filter_not_exists(&mut self, subquery: Box<dyn AnyBuilder>) -> &mut Self {
132        self.core.exists_subqueries.push(ExistsSubquery { subquery, not: true });
133        self
134    }
135
136    /// The columns to select.
137    ///
138    /// PHP: `select(array $columns)`.
139    pub fn select<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
140        self.core.pending.push(Query::select(columns));
141        self
142    }
143
144    /// A raw select expression with its bindings.
145    ///
146    /// PHP: `select(string $expression, $bindings)`, `selectRaw()`.
147    pub fn select_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
148        self.core
149            .raw_selects
150            .push(crate::builder::Condition::new(expression, bindings.into_values().values().cloned().collect()));
151        self
152    }
153
154    /// `SELECT DISTINCT`.
155    ///
156    /// PHP: `distinct()`.
157    pub fn distinct(&mut self) -> &mut Self {
158        self.core.pending.push(Query::distinct());
159        self
160    }
161
162    /// Adds queries (filters, or any query).
163    ///
164    /// PHP: `filter()`.
165    pub fn filter(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
166        self.core.pending.extend(queries);
167        self
168    }
169
170    /// Adds queries of any kind.
171    ///
172    /// PHP: `queries()`.
173    pub fn queries(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
174        self.core.pending.extend(queries);
175        self
176    }
177
178    /// `ORDER BY attribute ASC` (with `NULLS FIRST`/`LAST`).
179    ///
180    /// PHP: `sortAsc()`.
181    pub fn sort_asc(&mut self, attribute: impl Into<String>, nulls: Option<NullsPosition>) -> &mut Self {
182        self.core.pending.push(Query::order_asc(attribute, nulls));
183        self
184    }
185
186    /// `ORDER BY attribute DESC` (with `NULLS FIRST`/`LAST`).
187    ///
188    /// PHP: `sortDesc()`.
189    pub fn sort_desc(&mut self, attribute: impl Into<String>, nulls: Option<NullsPosition>) -> &mut Self {
190        self.core.pending.push(Query::order_desc(attribute, nulls));
191        self
192    }
193
194    /// Random order.
195    ///
196    /// PHP: `sortRandom()`.
197    pub fn sort_random(&mut self) -> &mut Self {
198        self.core.pending.push(Query::order_random());
199        self
200    }
201
202    /// `LIMIT`.
203    ///
204    /// PHP: `limit()`.
205    pub fn limit(&mut self, value: i64) -> &mut Self {
206        self.core.pending.push(Query::limit(value));
207        self
208    }
209
210    /// `OFFSET`.
211    ///
212    /// PHP: `offset()`.
213    pub fn offset(&mut self, value: i64) -> &mut Self {
214        self.core.pending.push(Query::offset(value));
215        self
216    }
217
218    /// `FETCH FIRST count ROWS ONLY` (or `WITH TIES`).
219    ///
220    /// PHP: `fetch()`.
221    pub fn fetch(&mut self, count: i64, with_ties: bool) -> &mut Self {
222        self.core.fetch_count = Some(count);
223        self.core.fetch_with_ties = with_ties;
224        self
225    }
226
227    /// The limit and offset of page `page` (from 1) of `per_page` rows.
228    ///
229    /// PHP: `page()`.
230    pub fn page(&mut self, page: i64, per_page: i64) -> Result<&mut Self> {
231        let [limit, offset] = Query::page(page, per_page)?;
232        self.core.pending.push(limit);
233        self.core.pending.push(offset);
234        Ok(self)
235    }
236
237    /// Rows after a cursor row (an array with `_cursor`, or a row object).
238    ///
239    /// PHP: `cursorAfter()`.
240    pub fn cursor_after(&mut self, row: Value) -> &mut Self {
241        self.core.pending.push(Query::cursor_after(row));
242        self
243    }
244
245    /// Rows before a cursor row.
246    ///
247    /// PHP: `cursorBefore()`.
248    pub fn cursor_before(&mut self, row: Value) -> &mut Self {
249        self.core.pending.push(Query::cursor_before(row));
250        self
251    }
252
253    /// Runs `callback` with the builder when `condition` holds.
254    ///
255    /// PHP: `when()`.
256    pub fn when(&mut self, condition: bool, callback: impl FnOnce(&mut Self) -> Result<()>) -> Result<&mut Self> {
257        if condition {
258            callback(self)?;
259        }
260        Ok(self)
261    }
262
263    /// A callback run with the builder at the start of every build.
264    ///
265    /// PHP: `beforeBuild()`.
266    pub fn before_build(&mut self, callback: impl Fn(&mut Self) -> Result<()> + Send + Sync + 'static) -> &mut Self {
267        self.before_build.push(Arc::new(callback));
268        self
269    }
270
271    /// A callback run on every built statement, returning the statement to use.
272    ///
273    /// PHP: `afterBuild()`.
274    pub fn after_build(
275        &mut self,
276        callback: impl Fn(Statement) -> Result<Statement> + Send + Sync + 'static,
277    ) -> &mut Self {
278        self.after_build_owned(move |_, statement| callback(statement))
279    }
280
281    /// As [`Self::after_build`], with the [owner](Self::set_owner) of the builder that built.
282    pub fn after_build_owned(
283        &mut self,
284        callback: impl Fn(usize, Statement) -> Result<Statement> + Send + Sync + 'static,
285    ) -> &mut Self {
286        let callback: AfterBuild = Arc::new(callback);
287        self.core.after_build.push(callback);
288        self
289    }
290
291    /// What runs the statements this builder builds ([`Builder::execute`]).
292    ///
293    /// PHP: `setExecutor()`.
294    pub fn set_executor(&mut self, executor: Executor) -> &mut Self {
295        self.core.executor = Some(executor);
296        self
297    }
298
299    /// `EXPLAIN` (or `EXPLAIN ANALYZE`) of the select.
300    ///
301    /// PHP: `explain($analyze)`.
302    pub fn explain(&mut self, analyze: bool) -> Result<Statement> {
303        D::explain(self, analyze, &ExplainOptions::default())
304    }
305
306    /// `EXPLAIN` with the dialect's options (format; PostgreSQL's verbose and buffers).
307    ///
308    /// PHP: `explain($analyze, ...)` of MySQL and PostgreSQL.
309    pub fn explain_with(&mut self, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
310        D::explain(self, analyze, options)
311    }
312
313    /// Builds the select and runs it with the executor.
314    ///
315    /// PHP: `execute()`.
316    pub fn execute(&mut self) -> Result<Value> {
317        self.build()?.execute()
318    }
319
320    /// The select with its bindings inlined: strings quoted by the dialect
321    /// (`'` doubled, and `\` doubled outside PostgreSQL and SQLite),
322    /// numbers as PHP prints them, booleans as `1`/`0`, anything else `NULL`.
323    /// For logs only: never execute it.
324    ///
325    /// PHP: `toRawSql()`.
326    pub fn to_raw_sql(&mut self) -> Result<String> {
327        self.raw_sql(false)
328    }
329
330    /// As [`Builder::to_raw_sql`], for a builder whose text holds a character for each
331    /// byte, as the PHP extension passes a string that is not UTF-8: the bytes of a
332    /// string binding are written the same way.
333    pub fn to_raw_sql_widened(&mut self) -> Result<String> {
334        self.raw_sql(true)
335    }
336
337    fn raw_sql(&mut self, widened: bool) -> Result<String> {
338        let result = self.built()?;
339        let mut sql = result.query;
340        let mut offset = 0;
341        for binding in &result.bindings {
342            let literal = match binding {
343                Value::Str(s) if widened => {
344                    D::LITERAL.quote(&s.as_bytes().iter().map(|&b| char::from(b)).collect::<String>())?
345                }
346                Value::Str(s) => D::LITERAL.quote(&String::from_utf8_lossy(s.as_bytes()))?,
347                Value::Int(_) | Value::Float(_) => crate::value::to_php_string(binding),
348                Value::Bool(b) => if *b { "1" } else { "0" }.to_owned(),
349                _ => "NULL".to_owned(),
350            };
351            if let Some(pos) = sql.get(offset..).and_then(|rest| rest.find('?')).map(|p| p + offset) {
352                sql.replace_range(pos..=pos, &literal);
353                offset = pos + literal.len();
354            }
355        }
356        Ok(sql)
357    }
358
359    /// The bindings so far, each with the column it was bound against.
360    ///
361    /// PHP: the protected `$bindings`.
362    pub fn binding_list(&self) -> &[crate::builder::Binding] {
363        &self.core.bindings
364    }
365
366    /// Replaces the bindings.
367    pub fn set_binding_list(&mut self, bindings: Vec<crate::builder::Binding>) -> &mut Self {
368        self.core.bindings = bindings;
369        self
370    }
371
372    /// Replaces the queries to compile.
373    ///
374    /// PHP: the protected `$pendingQueries`.
375    pub fn set_pending(&mut self, queries: Vec<Query>) -> &mut Self {
376        self.core.pending = queries;
377        self
378    }
379
380    /// The attributes resolved so far, and what each resolved to.
381    ///
382    /// PHP: the protected `$resolvedAttributeCache`.
383    pub fn resolved_attributes(&self) -> impl Iterator<Item = (&str, &str)> {
384        self.core.resolved.iter().map(|(attribute, resolved)| (attribute.as_str(), resolved.as_str()))
385    }
386
387    /// Replaces the resolved attributes.
388    pub fn set_resolved_attributes(&mut self, resolved: impl IntoIterator<Item = (String, String)>) -> &mut Self {
389        self.core.resolved = resolved.into_iter().collect();
390        self
391    }
392
393    /// The bindings of the last statement built.
394    ///
395    /// PHP: `getBindings()`.
396    pub fn bindings(&mut self) -> Vec<Value> {
397        self.binding_values()
398    }
399
400    /// Clears everything but hooks and the executor.
401    ///
402    /// PHP: `reset()`.
403    pub fn reset(&mut self) -> &mut Self {
404        let core = &mut self.core;
405        core.pending.clear();
406        core.bindings.clear();
407        core.resolved.clear();
408        core.table.clear();
409        core.alias.clear();
410        core.unions.clear();
411        core.rows.clear();
412        core.raw_sets.clear();
413        core.raw_set_bindings.clear();
414        core.conflict_keys.clear();
415        core.conflict_update_columns.clear();
416        core.conflict_raw_sets.clear();
417        core.conflict_raw_set_bindings.clear();
418        core.insert_column_expressions.clear();
419        core.insert_column_expression_bindings.clear();
420        core.insert_alias.clear();
421        core.lock_mode = None;
422        core.lock_of_table = None;
423        core.insert_select_source = None;
424        core.insert_select_columns.clear();
425        core.ctes.clear();
426        core.raw_selects.clear();
427        core.window_selects.clear();
428        core.window_definitions.clear();
429        core.sample = None;
430        core.cases.clear();
431        core.case_sets.clear();
432        core.where_in_subqueries.clear();
433        core.sub_selects.clear();
434        core.from_subquery = None;
435        core.tableless = false;
436        core.raw_orders.clear();
437        core.raw_groups.clear();
438        core.raw_havings.clear();
439        core.raw_wheres.clear();
440        core.column_predicates.clear();
441        core.joins.clear();
442        core.exists_subqueries.clear();
443        core.lateral_joins.clear();
444        core.after_build.clear();
445        core.fetch_count = None;
446        core.fetch_with_ties = false;
447        core.qualify = false;
448        core.aggregation_aliases.clear();
449        self.before_build.clear();
450        D::reset(self);
451        self
452    }
453
454    /// Compiles the select.
455    ///
456    /// PHP: `build()`.
457    pub fn build(&mut self) -> Result<Statement> {
458        self.scoped_build()
459    }
460
461    /// `count(attribute)` (`*` counts rows) as `alias`.
462    ///
463    /// PHP: `count()`.
464    pub fn count(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
465        self.core.pending.push(Query::count(attribute, alias));
466        self
467    }
468
469    /// `COUNT(DISTINCT attribute)`.
470    ///
471    /// PHP: `countDistinct()`.
472    pub fn count_distinct(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
473        self.core.pending.push(Query::count_distinct(attribute, alias));
474        self
475    }
476
477    /// `SUM`.
478    ///
479    /// PHP: `sum()`.
480    pub fn sum(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
481        self.core.pending.push(Query::sum(attribute, alias));
482        self
483    }
484
485    /// `AVG`.
486    ///
487    /// PHP: `avg()`.
488    pub fn avg(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
489        self.core.pending.push(Query::avg(attribute, alias));
490        self
491    }
492
493    /// `MIN`.
494    ///
495    /// PHP: `min()`.
496    pub fn min(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
497        self.core.pending.push(Query::min(attribute, alias));
498        self
499    }
500
501    /// `MAX`.
502    ///
503    /// PHP: `max()`.
504    pub fn max(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
505        self.core.pending.push(Query::max(attribute, alias));
506        self
507    }
508
509    /// `GROUP BY`.
510    ///
511    /// PHP: `groupBy()`.
512    pub fn group_by<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
513        self.core.pending.push(Query::group_by(columns));
514        self
515    }
516
517    /// Groups by `attribute` cut into windows of `interval`.
518    ///
519    /// PHP: `groupByTimeBucket()`.
520    pub fn group_by_time_bucket(&mut self, attribute: impl Into<String>, interval: &str) -> Result<&mut Self> {
521        self.core.pending.push(Query::group_by_time_bucket(attribute, interval)?);
522        Ok(self)
523    }
524
525    /// `HAVING` conditions (aggregate aliases resolve to their expressions).
526    ///
527    /// PHP: `having()`.
528    pub fn having(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
529        self.core.pending.push(Query::having(queries));
530        self
531    }
532
533    fn join_on(
534        &mut self,
535        method: Method,
536        table: String,
537        left: &str,
538        right: &str,
539        operator: &str,
540        alias: String,
541    ) -> &mut Self {
542        let on = Query::on(left, right, operator);
543        self.core.pending.push(Query::new(method, table, crate::value::list([on]), alias));
544        self
545    }
546
547    /// `JOIN table [AS alias] ON left operator right`.
548    ///
549    /// PHP: `join()`.
550    pub fn join(
551        &mut self,
552        table: impl Into<String>,
553        left: &str,
554        right: &str,
555        operator: &str,
556        alias: impl Into<String>,
557    ) -> &mut Self {
558        self.join_on(Method::Join, table.into(), left, right, operator, alias.into())
559    }
560
561    /// `LEFT JOIN`.
562    ///
563    /// PHP: `leftJoin()`.
564    pub fn left_join(
565        &mut self,
566        table: impl Into<String>,
567        left: &str,
568        right: &str,
569        operator: &str,
570        alias: impl Into<String>,
571    ) -> &mut Self {
572        self.join_on(Method::LeftJoin, table.into(), left, right, operator, alias.into())
573    }
574
575    /// `RIGHT JOIN`.
576    ///
577    /// PHP: `rightJoin()`.
578    pub fn right_join(
579        &mut self,
580        table: impl Into<String>,
581        left: &str,
582        right: &str,
583        operator: &str,
584        alias: impl Into<String>,
585    ) -> &mut Self {
586        self.join_on(Method::RightJoin, table.into(), left, right, operator, alias.into())
587    }
588
589    /// A join whose conditions `callback` builds on a [`JoinBuilder`].
590    ///
591    /// PHP: `joinWhere()`.
592    pub fn join_where(
593        &mut self,
594        table: impl Into<String>,
595        callback: impl FnOnce(&mut JoinBuilder) -> Result<()>,
596        join_type: JoinType,
597        alias: impl Into<String>,
598    ) -> Result<&mut Self> {
599        let mut join = JoinBuilder::new();
600        callback(&mut join)?;
601        let method = match join_type {
602            JoinType::Left => Method::LeftJoin,
603            JoinType::Right => Method::RightJoin,
604            JoinType::Cross => Method::CrossJoin,
605            JoinType::FullOuter => Method::FullOuterJoin,
606            JoinType::Natural => Method::NaturalJoin,
607            JoinType::Inner => Method::Join,
608        };
609        self.core.pending.push(Query::new(method, table, Array::default(), alias));
610        let index = self.core.pending.len() - 1;
611        self.core.joins.insert(index, join);
612        Ok(self)
613    }
614
615    fn union_with(&mut self, union_type: UnionType, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
616        let result = other.build()?;
617        self.core.unions.push(UnionClause::new(union_type, result.query, result.bindings));
618        Ok(self)
619    }
620
621    /// `UNION` with another builder's select (built now).
622    ///
623    /// PHP: `union()`.
624    pub fn union(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
625        self.union_with(UnionType::Union, other)
626    }
627
628    /// `UNION ALL`.
629    ///
630    /// PHP: `unionAll()`.
631    pub fn union_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
632        self.union_with(UnionType::UnionAll, other)
633    }
634
635    /// `INTERSECT`.
636    ///
637    /// PHP: `intersect()`.
638    pub fn intersect(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
639        self.union_with(UnionType::Intersect, other)
640    }
641
642    /// `INTERSECT ALL`.
643    ///
644    /// PHP: `intersectAll()`.
645    pub fn intersect_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
646        self.union_with(UnionType::IntersectAll, other)
647    }
648
649    /// `EXCEPT`.
650    ///
651    /// PHP: `except()`.
652    pub fn except(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
653        self.union_with(UnionType::Except, other)
654    }
655
656    /// `EXCEPT ALL`.
657    ///
658    /// PHP: `exceptAll()`.
659    pub fn except_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
660        self.union_with(UnionType::ExceptAll, other)
661    }
662
663    /// `WITH name [(columns)] AS (query)` (built now).
664    ///
665    /// PHP: `with()`.
666    pub fn with<S: Into<String>>(
667        &mut self,
668        name: impl Into<String>,
669        query: &mut dyn AnyBuilder,
670        columns: impl IntoIterator<Item = S>,
671    ) -> Result<&mut Self> {
672        let result = query.build()?;
673        self.core.ctes.push(CteClause::new(name, result.query, result.bindings, false, strings(columns)));
674        Ok(self)
675    }
676
677    /// `WITH RECURSIVE name AS (query)`.
678    ///
679    /// PHP: `withRecursive()`.
680    pub fn with_recursive<S: Into<String>>(
681        &mut self,
682        name: impl Into<String>,
683        query: &mut dyn AnyBuilder,
684        columns: impl IntoIterator<Item = S>,
685    ) -> Result<&mut Self> {
686        let result = query.build()?;
687        self.core.ctes.push(CteClause::new(name, result.query, result.bindings, true, strings(columns)));
688        Ok(self)
689    }
690
691    /// `WITH RECURSIVE name AS (seed UNION ALL step)`.
692    ///
693    /// PHP: `withRecursiveSeedStep()`.
694    pub fn with_recursive_seed_step<S: Into<String>>(
695        &mut self,
696        name: impl Into<String>,
697        seed: &mut dyn AnyBuilder,
698        step: &mut dyn AnyBuilder,
699        columns: impl IntoIterator<Item = S>,
700    ) -> Result<&mut Self> {
701        let seed = seed.build()?;
702        let step = step.build()?;
703        let mut bindings = seed.bindings;
704        bindings.extend(step.bindings);
705        self.core.ctes.push(CteClause::new(
706            name,
707            format!("{} UNION ALL {}", seed.query, step.query),
708            bindings,
709            true,
710            strings(columns),
711        ));
712        Ok(self)
713    }
714
715    /// The table to insert into.
716    ///
717    /// PHP: `into()`.
718    pub fn into(&mut self, table: impl Into<String>) -> &mut Self {
719        let table = table.into();
720        self.defer_unbound(&format!("insert into table '{table}'"));
721        self.core.table = table;
722        self
723    }
724
725    /// `INSERT INTO table AS alias`.
726    ///
727    /// PHP: `insertAs()`.
728    pub fn insert_as(&mut self, alias: impl Into<String>) -> &mut Self {
729        self.core.insert_alias = alias.into();
730        self
731    }
732
733    /// A row to insert (column => value), or the values of an update.
734    ///
735    /// PHP: `set()`.
736    pub fn set(&mut self, row: Array) -> Result<&mut Self> {
737        D::set(self, row)?;
738        Ok(self)
739    }
740
741    /// The conflict target and the columns an upsert updates.
742    ///
743    /// PHP: `onConflict()`.
744    pub fn on_conflict<K: Into<String>, U: Into<String>>(
745        &mut self,
746        keys: impl IntoIterator<Item = K>,
747        update_columns: impl IntoIterator<Item = U>,
748    ) -> &mut Self {
749        self.core.conflict_keys = strings(keys);
750        self.core.conflict_update_columns = strings(update_columns);
751        self
752    }
753
754    /// `INSERT INTO table (columns) SELECT ...` from `source` (built at insert time).
755    ///
756    /// PHP: `fromSelect()`.
757    pub fn from_select<S: Into<String>>(
758        &mut self,
759        columns: impl IntoIterator<Item = S>,
760        source: Box<dyn AnyBuilder>,
761    ) -> &mut Self {
762        self.core.insert_select_columns = strings(columns);
763        self.core.insert_select_source = Some(source);
764        self
765    }
766
767    /// Compiles the insert.
768    ///
769    /// PHP: `insert()`.
770    pub fn insert(&mut self) -> Result<Statement> {
771        self.check_deferred()?;
772        D::insert(self)
773    }
774
775    /// `INSERT INTO table DEFAULT VALUES` (MySQL: `() VALUES ()`).
776    ///
777    /// PHP: `insertDefaultValues()`.
778    pub fn insert_default_values(&mut self) -> Result<Statement> {
779        self.check_deferred()?;
780        D::insert_default_values(self)
781    }
782
783    /// `INSERT INTO table (columns) SELECT ...`.
784    ///
785    /// PHP: `insertSelect()`.
786    pub fn insert_select(&mut self) -> Result<Statement> {
787        self.check_deferred()?;
788        self.base_insert_select()
789    }
790
791    /// Compiles the update.
792    ///
793    /// PHP: `update()`.
794    pub fn update(&mut self) -> Result<Statement> {
795        self.check_deferred()?;
796        D::update(self)
797    }
798
799    /// Compiles the delete.
800    ///
801    /// PHP: `delete()`.
802    pub fn delete(&mut self) -> Result<Statement> {
803        self.check_deferred()?;
804        D::delete(self)
805    }
806
807    /// Adds a hook: a filter, an attribute resolver, a join filter, or several at once.
808    ///
809    /// PHP: `addHook()`.
810    pub fn add_hook(&mut self, hook: impl Into<Hook>) -> Result<&mut Self> {
811        D::add_hook(self, hook.into())?;
812        Ok(self)
813    }
814
815    /// A window function in the select list: `function OVER (...) AS alias`,
816    /// or `OVER window_name`. The function must look like `NAME(args)`.
817    ///
818    /// PHP: `selectWindow()`.
819    pub fn select_window(
820        &mut self,
821        function: impl Into<String>,
822        alias: impl Into<String>,
823        partition_by: Option<Vec<String>>,
824        order_by: Option<Vec<String>>,
825        window_name: Option<String>,
826        frame: Option<WindowFrame>,
827    ) -> Result<&mut Self> {
828        let function = function.into();
829        if !is_window_function(&function) {
830            return Err(Error::Validation(format!("Invalid window function: {function}")));
831        }
832        self.core.window_selects.push(WindowSelect::new(function, alias, partition_by, order_by, window_name, frame));
833        Ok(self)
834    }
835
836    /// A named window: `WINDOW name AS (...)`.
837    ///
838    /// PHP: `window()`.
839    pub fn window(
840        &mut self,
841        name: impl Into<String>,
842        partition_by: Option<Vec<String>>,
843        order_by: Option<Vec<String>>,
844        frame: Option<WindowFrame>,
845    ) -> &mut Self {
846        self.core.window_definitions.push(WindowDefinition::new(name, partition_by, order_by, frame));
847        self
848    }
849
850    /// The queries added so far.
851    pub fn pending(&self) -> &[Query] {
852        &self.core.pending
853    }
854
855    pub(crate) fn push_case(&mut self, case: CaseExpression) {
856        self.core.cases.push(case);
857    }
858
859    pub(crate) fn add_lateral(&mut self, subquery: Box<dyn AnyBuilder>, alias: String, join_type: JoinType) {
860        self.core.lateral_joins.push(LateralJoin { subquery, alias, join_type });
861    }
862}
863
864impl<D: Dialect> Compiler for Builder<D> {
865    fn compile_filter(&mut self, query: &Query) -> Result<String> {
866        self.step_string(Step::CompileFilter, &[Arg::Query(query)])
867    }
868
869    fn compile_order(&mut self, query: &Query) -> Result<String> {
870        self.step_string(Step::CompileOrder, &[Arg::Query(query)])
871    }
872
873    fn compile_limit(&mut self, query: &Query) -> Result<String> {
874        self.step_string(Step::CompileLimit, &[Arg::Query(query)])
875    }
876
877    fn compile_offset(&mut self, query: &Query) -> Result<String> {
878        self.step_string(Step::CompileOffset, &[Arg::Query(query)])
879    }
880
881    fn compile_select(&mut self, query: &Query) -> Result<String> {
882        self.step_string(Step::CompileSelect, &[Arg::Query(query)])
883    }
884
885    fn compile_cursor(&mut self, query: &Query) -> Result<String> {
886        self.step_string(Step::CompileCursor, &[Arg::Query(query)])
887    }
888
889    fn compile_aggregate(&mut self, query: &Query) -> Result<String> {
890        self.step_string(Step::CompileAggregate, &[Arg::Query(query)])
891    }
892
893    fn compile_group_by(&mut self, query: &Query) -> Result<String> {
894        self.step_string(Step::CompileGroupBy, &[Arg::Query(query)])
895    }
896
897    fn compile_join(&mut self, query: &Query) -> Result<String> {
898        self.step_string(Step::CompileJoin, &[Arg::Query(query)])
899    }
900}
901
902impl<D: Dialect> AnyBuilder for Builder<D> {
903    fn build(&mut self) -> Result<Statement> {
904        D::build(self)
905    }
906
907    fn clone_box(&self) -> Box<dyn AnyBuilder> {
908        Box::new(self.clone())
909    }
910
911    fn php_class(&self) -> &'static str {
912        D::CLASS
913    }
914
915    fn as_any(&self) -> &dyn std::any::Any {
916        self
917    }
918}