utopia-query 0.1.1

Queries as data, compiled to SQL (MySQL, MariaDB, PostgreSQL, SQLite, ClickHouse) and MongoDB commands; schema builders; a SQL tokenizer, parser, serializer and statement classifier.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
//! The public API every builder has: selects, aggregates, joins, unions,
//! CTEs, inserts, updates, deletes, hooks and window functions.

use std::sync::Arc;

use crate::builder::AnyBuilder;
use crate::builder::case::CaseExpression;
use crate::builder::core::{
    AfterBuild, Builder, Dialect, ExistsSubquery, ExplainOptions, LateralJoin, SubSelect, WhereInSubquery,
};
use crate::builder::join::JoinBuilder;
use crate::builder::steps::{Arg, Step};
use crate::builder::types::{
    CteClause, Executor, JoinType, Statement, UnionClause, UnionType, WindowDefinition, WindowFrame, WindowSelect,
};
use crate::enums::NullsPosition;
use crate::error::{Error, Result};
use crate::hook::Hook;
use crate::method::Method;
use crate::query::{Compiler, Query};
use crate::value::{Array, IntoValues, Value};

fn strings<S: Into<String>>(items: impl IntoIterator<Item = S>) -> Vec<String> {
    items.into_iter().map(Into::into).collect()
}

/// `/^[A-Za-z_][A-Za-z0-9_]*\s*\(\s*[A-Za-z0-9_,.\s*"`]*\s*\)$/` on the
/// trimmed function, with `/D` (`$` only at the very end).
fn is_window_function(function: &str) -> bool {
    let text = function.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
    let text = text.as_bytes();
    let is_space = |b: u8| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0B' | b'\x0C');
    let mut i = 0;
    match text.first() {
        Some(b) if b.is_ascii_alphabetic() || *b == b'_' => i += 1,
        _ => return false,
    }
    while i < text.len() && (text[i].is_ascii_alphanumeric() || text[i] == b'_') {
        i += 1;
    }
    while i < text.len() && is_space(text[i]) {
        i += 1;
    }
    if text.get(i) != Some(&b'(') || text.last() != Some(&b')') || i == text.len() - 1 {
        return false;
    }
    text[i + 1..text.len() - 1]
        .iter()
        .all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b',' | b'.' | b'*' | b'"' | b'`') || is_space(b))
}

impl<D: Dialect> Builder<D> {
    /// The table (and its alias) to select from, update or delete from; an
    /// empty table makes a select without `FROM`.
    ///
    /// PHP: `from($table, $alias)`.
    ///
    /// On a builder with a [`Scope`](crate::builder::Scope), a non-empty
    /// table is a collection id read through the scope (see
    /// [`Builder::scope`]).
    pub fn from(&mut self, table: impl Into<String>, alias: impl Into<String>) -> &mut Self {
        self.scoped_from(table.into(), alias.into())
    }

    /// The refusal a call returning the builder kept for the next
    /// statement, taken: PHP throws it from that call (`from()` of another
    /// collection or alias on a bound builder, `into()` and the dialects'
    /// multi-table writes once a collection is bound).
    ///
    /// PHP: `ScopesCollections::from()`, `requireUnbound()`.
    pub fn take_refusal(&mut self) -> Option<crate::Error> {
        self.core.deferred.take()
    }

    /// A select without `FROM`.
    ///
    /// PHP: `fromNone()`.
    pub fn from_none(&mut self) -> &mut Self {
        self.from("", "")
    }

    /// `FROM (subquery) AS alias`.
    ///
    /// PHP: `fromSub()`.
    pub fn from_sub(&mut self, subquery: impl AnyBuilder + 'static, alias: impl Into<String>) -> &mut Self {
        self.from_sub_boxed(Box::new(subquery), alias)
    }

    /// [`Builder::from_sub`] with a boxed builder.
    pub fn from_sub_boxed(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
        self.core.from_subquery = Some(SubSelect { subquery, alias: alias.into() });
        self.core.table.clear();
        self
    }

    /// `(subquery) AS alias` in the select list.
    ///
    /// PHP: `selectSub()`.
    pub fn select_sub(&mut self, subquery: Box<dyn AnyBuilder>, alias: impl Into<String>) -> &mut Self {
        self.core.sub_selects.push(SubSelect { subquery, alias: alias.into() });
        self
    }

    /// `column IN (subquery)`.
    ///
    /// PHP: `filterWhereIn()`.
    pub fn filter_where_in(&mut self, column: impl Into<String>, subquery: Box<dyn AnyBuilder>) -> &mut Self {
        self.core.where_in_subqueries.push(WhereInSubquery { column: column.into(), subquery, not: false });
        self
    }

    /// `column NOT IN (subquery)`.
    ///
    /// PHP: `filterWhereNotIn()`.
    pub fn filter_where_not_in(&mut self, column: impl Into<String>, subquery: Box<dyn AnyBuilder>) -> &mut Self {
        self.core.where_in_subqueries.push(WhereInSubquery { column: column.into(), subquery, not: true });
        self
    }

    /// `EXISTS (subquery)`.
    ///
    /// PHP: `filterExists()`.
    pub fn filter_exists(&mut self, subquery: Box<dyn AnyBuilder>) -> &mut Self {
        self.core.exists_subqueries.push(ExistsSubquery { subquery, not: false });
        self
    }

    /// `NOT EXISTS (subquery)`.
    ///
    /// PHP: `filterNotExists()`.
    pub fn filter_not_exists(&mut self, subquery: Box<dyn AnyBuilder>) -> &mut Self {
        self.core.exists_subqueries.push(ExistsSubquery { subquery, not: true });
        self
    }

    /// The columns to select.
    ///
    /// PHP: `select(array $columns)`.
    pub fn select<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
        self.core.pending.push(Query::select(columns));
        self
    }

    /// A raw select expression with its bindings.
    ///
    /// PHP: `select(string $expression, $bindings)`, `selectRaw()`.
    pub fn select_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
        self.core
            .raw_selects
            .push(crate::builder::Condition::new(expression, bindings.into_values().values().cloned().collect()));
        self
    }

    /// `SELECT DISTINCT`.
    ///
    /// PHP: `distinct()`.
    pub fn distinct(&mut self) -> &mut Self {
        self.core.pending.push(Query::distinct());
        self
    }

    /// Adds queries (filters, or any query).
    ///
    /// PHP: `filter()`.
    pub fn filter(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
        self.core.pending.extend(queries);
        self
    }

    /// Adds queries of any kind.
    ///
    /// PHP: `queries()`.
    pub fn queries(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
        self.core.pending.extend(queries);
        self
    }

    /// `ORDER BY attribute ASC` (with `NULLS FIRST`/`LAST`).
    ///
    /// PHP: `sortAsc()`.
    pub fn sort_asc(&mut self, attribute: impl Into<String>, nulls: Option<NullsPosition>) -> &mut Self {
        self.core.pending.push(Query::order_asc(attribute, nulls));
        self
    }

    /// `ORDER BY attribute DESC` (with `NULLS FIRST`/`LAST`).
    ///
    /// PHP: `sortDesc()`.
    pub fn sort_desc(&mut self, attribute: impl Into<String>, nulls: Option<NullsPosition>) -> &mut Self {
        self.core.pending.push(Query::order_desc(attribute, nulls));
        self
    }

    /// Random order.
    ///
    /// PHP: `sortRandom()`.
    pub fn sort_random(&mut self) -> &mut Self {
        self.core.pending.push(Query::order_random());
        self
    }

    /// `LIMIT`.
    ///
    /// PHP: `limit()`.
    pub fn limit(&mut self, value: i64) -> &mut Self {
        self.core.pending.push(Query::limit(value));
        self
    }

    /// `OFFSET`.
    ///
    /// PHP: `offset()`.
    pub fn offset(&mut self, value: i64) -> &mut Self {
        self.core.pending.push(Query::offset(value));
        self
    }

    /// `FETCH FIRST count ROWS ONLY` (or `WITH TIES`).
    ///
    /// PHP: `fetch()`.
    pub fn fetch(&mut self, count: i64, with_ties: bool) -> &mut Self {
        self.core.fetch_count = Some(count);
        self.core.fetch_with_ties = with_ties;
        self
    }

    /// The limit and offset of page `page` (from 1) of `per_page` rows.
    ///
    /// PHP: `page()`.
    pub fn page(&mut self, page: i64, per_page: i64) -> Result<&mut Self> {
        let [limit, offset] = Query::page(page, per_page)?;
        self.core.pending.push(limit);
        self.core.pending.push(offset);
        Ok(self)
    }

    /// Rows after a cursor row (an array with `_cursor`, or a row object).
    ///
    /// PHP: `cursorAfter()`.
    pub fn cursor_after(&mut self, row: Value) -> &mut Self {
        self.core.pending.push(Query::cursor_after(row));
        self
    }

    /// Rows before a cursor row.
    ///
    /// PHP: `cursorBefore()`.
    pub fn cursor_before(&mut self, row: Value) -> &mut Self {
        self.core.pending.push(Query::cursor_before(row));
        self
    }

    /// Runs `callback` with the builder when `condition` holds.
    ///
    /// PHP: `when()`.
    pub fn when(&mut self, condition: bool, callback: impl FnOnce(&mut Self) -> Result<()>) -> Result<&mut Self> {
        if condition {
            callback(self)?;
        }
        Ok(self)
    }

    /// A callback run with the builder at the start of every build.
    ///
    /// PHP: `beforeBuild()`.
    pub fn before_build(&mut self, callback: impl Fn(&mut Self) -> Result<()> + Send + Sync + 'static) -> &mut Self {
        self.before_build.push(Arc::new(callback));
        self
    }

    /// A callback run on every built statement, returning the statement to use.
    ///
    /// PHP: `afterBuild()`.
    pub fn after_build(
        &mut self,
        callback: impl Fn(Statement) -> Result<Statement> + Send + Sync + 'static,
    ) -> &mut Self {
        self.after_build_owned(move |_, statement| callback(statement))
    }

    /// As [`Self::after_build`], with the [owner](Self::set_owner) of the builder that built.
    pub fn after_build_owned(
        &mut self,
        callback: impl Fn(usize, Statement) -> Result<Statement> + Send + Sync + 'static,
    ) -> &mut Self {
        let callback: AfterBuild = Arc::new(callback);
        self.core.after_build.push(callback);
        self
    }

    /// What runs the statements this builder builds ([`Builder::execute`]).
    ///
    /// PHP: `setExecutor()`.
    pub fn set_executor(&mut self, executor: Executor) -> &mut Self {
        self.core.executor = Some(executor);
        self
    }

    /// `EXPLAIN` (or `EXPLAIN ANALYZE`) of the select.
    ///
    /// PHP: `explain($analyze)`.
    pub fn explain(&mut self, analyze: bool) -> Result<Statement> {
        D::explain(self, analyze, &ExplainOptions::default())
    }

    /// `EXPLAIN` with the dialect's options (format; PostgreSQL's verbose and buffers).
    ///
    /// PHP: `explain($analyze, ...)` of MySQL and PostgreSQL.
    pub fn explain_with(&mut self, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
        D::explain(self, analyze, options)
    }

    /// Builds the select and runs it with the executor.
    ///
    /// PHP: `execute()`.
    pub fn execute(&mut self) -> Result<Value> {
        self.build()?.execute()
    }

    /// The select with its bindings inlined: strings quoted by the dialect
    /// (`'` doubled, and `\` doubled outside PostgreSQL and SQLite),
    /// numbers as PHP prints them, booleans as `1`/`0`, anything else `NULL`.
    /// For logs only: never execute it.
    ///
    /// PHP: `toRawSql()`.
    pub fn to_raw_sql(&mut self) -> Result<String> {
        self.raw_sql(false)
    }

    /// As [`Builder::to_raw_sql`], for a builder whose text holds a character for each
    /// byte, as the PHP extension passes a string that is not UTF-8: the bytes of a
    /// string binding are written the same way.
    pub fn to_raw_sql_widened(&mut self) -> Result<String> {
        self.raw_sql(true)
    }

    fn raw_sql(&mut self, widened: bool) -> Result<String> {
        let result = self.built()?;
        let mut sql = result.query;
        let mut offset = 0;
        for binding in &result.bindings {
            let literal = match binding {
                Value::Str(s) if widened => {
                    D::LITERAL.quote(&s.as_bytes().iter().map(|&b| char::from(b)).collect::<String>())?
                }
                Value::Str(s) => D::LITERAL.quote(&String::from_utf8_lossy(s.as_bytes()))?,
                Value::Int(_) | Value::Float(_) => crate::value::to_php_string(binding),
                Value::Bool(b) => if *b { "1" } else { "0" }.to_owned(),
                _ => "NULL".to_owned(),
            };
            if let Some(pos) = sql.get(offset..).and_then(|rest| rest.find('?')).map(|p| p + offset) {
                sql.replace_range(pos..=pos, &literal);
                offset = pos + literal.len();
            }
        }
        Ok(sql)
    }

    /// The bindings so far, each with the column it was bound against.
    ///
    /// PHP: the protected `$bindings`.
    pub fn binding_list(&self) -> &[crate::builder::Binding] {
        &self.core.bindings
    }

    /// Replaces the bindings.
    pub fn set_binding_list(&mut self, bindings: Vec<crate::builder::Binding>) -> &mut Self {
        self.core.bindings = bindings;
        self
    }

    /// Replaces the queries to compile.
    ///
    /// PHP: the protected `$pendingQueries`.
    pub fn set_pending(&mut self, queries: Vec<Query>) -> &mut Self {
        self.core.pending = queries;
        self
    }

    /// The attributes resolved so far, and what each resolved to.
    ///
    /// PHP: the protected `$resolvedAttributeCache`.
    pub fn resolved_attributes(&self) -> impl Iterator<Item = (&str, &str)> {
        self.core.resolved.iter().map(|(attribute, resolved)| (attribute.as_str(), resolved.as_str()))
    }

    /// Replaces the resolved attributes.
    pub fn set_resolved_attributes(&mut self, resolved: impl IntoIterator<Item = (String, String)>) -> &mut Self {
        self.core.resolved = resolved.into_iter().collect();
        self
    }

    /// The bindings of the last statement built.
    ///
    /// PHP: `getBindings()`.
    pub fn bindings(&mut self) -> Vec<Value> {
        self.binding_values()
    }

    /// Clears everything but hooks and the executor.
    ///
    /// PHP: `reset()`.
    pub fn reset(&mut self) -> &mut Self {
        let core = &mut self.core;
        core.pending.clear();
        core.bindings.clear();
        core.resolved.clear();
        core.table.clear();
        core.alias.clear();
        core.unions.clear();
        core.rows.clear();
        core.raw_sets.clear();
        core.raw_set_bindings.clear();
        core.conflict_keys.clear();
        core.conflict_update_columns.clear();
        core.conflict_raw_sets.clear();
        core.conflict_raw_set_bindings.clear();
        core.insert_column_expressions.clear();
        core.insert_column_expression_bindings.clear();
        core.insert_alias.clear();
        core.lock_mode = None;
        core.lock_of_table = None;
        core.insert_select_source = None;
        core.insert_select_columns.clear();
        core.ctes.clear();
        core.raw_selects.clear();
        core.window_selects.clear();
        core.window_definitions.clear();
        core.sample = None;
        core.cases.clear();
        core.case_sets.clear();
        core.where_in_subqueries.clear();
        core.sub_selects.clear();
        core.from_subquery = None;
        core.tableless = false;
        core.raw_orders.clear();
        core.raw_groups.clear();
        core.raw_havings.clear();
        core.raw_wheres.clear();
        core.column_predicates.clear();
        core.joins.clear();
        core.exists_subqueries.clear();
        core.lateral_joins.clear();
        core.after_build.clear();
        core.fetch_count = None;
        core.fetch_with_ties = false;
        core.qualify = false;
        core.aggregation_aliases.clear();
        self.before_build.clear();
        D::reset(self);
        self
    }

    /// Compiles the select.
    ///
    /// PHP: `build()`.
    pub fn build(&mut self) -> Result<Statement> {
        self.scoped_build()
    }

    /// `count(attribute)` (`*` counts rows) as `alias`.
    ///
    /// PHP: `count()`.
    pub fn count(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
        self.core.pending.push(Query::count(attribute, alias));
        self
    }

    /// `COUNT(DISTINCT attribute)`.
    ///
    /// PHP: `countDistinct()`.
    pub fn count_distinct(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
        self.core.pending.push(Query::count_distinct(attribute, alias));
        self
    }

    /// `SUM`.
    ///
    /// PHP: `sum()`.
    pub fn sum(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
        self.core.pending.push(Query::sum(attribute, alias));
        self
    }

    /// `AVG`.
    ///
    /// PHP: `avg()`.
    pub fn avg(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
        self.core.pending.push(Query::avg(attribute, alias));
        self
    }

    /// `MIN`.
    ///
    /// PHP: `min()`.
    pub fn min(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
        self.core.pending.push(Query::min(attribute, alias));
        self
    }

    /// `MAX`.
    ///
    /// PHP: `max()`.
    pub fn max(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
        self.core.pending.push(Query::max(attribute, alias));
        self
    }

    /// `GROUP BY`.
    ///
    /// PHP: `groupBy()`.
    pub fn group_by<S: Into<String>>(&mut self, columns: impl IntoIterator<Item = S>) -> &mut Self {
        self.core.pending.push(Query::group_by(columns));
        self
    }

    /// Groups by `attribute` cut into windows of `interval`.
    ///
    /// PHP: `groupByTimeBucket()`.
    pub fn group_by_time_bucket(&mut self, attribute: impl Into<String>, interval: &str) -> Result<&mut Self> {
        self.core.pending.push(Query::group_by_time_bucket(attribute, interval)?);
        Ok(self)
    }

    /// `HAVING` conditions (aggregate aliases resolve to their expressions).
    ///
    /// PHP: `having()`.
    pub fn having(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
        self.core.pending.push(Query::having(queries));
        self
    }

    fn join_on(
        &mut self,
        method: Method,
        table: String,
        left: &str,
        right: &str,
        operator: &str,
        alias: String,
    ) -> &mut Self {
        let on = Query::on(left, right, operator);
        self.core.pending.push(Query::new(method, table, crate::value::list([on]), alias));
        self
    }

    /// `JOIN table [AS alias] ON left operator right`.
    ///
    /// PHP: `join()`.
    pub fn join(
        &mut self,
        table: impl Into<String>,
        left: &str,
        right: &str,
        operator: &str,
        alias: impl Into<String>,
    ) -> &mut Self {
        self.join_on(Method::Join, table.into(), left, right, operator, alias.into())
    }

    /// `LEFT JOIN`.
    ///
    /// PHP: `leftJoin()`.
    pub fn left_join(
        &mut self,
        table: impl Into<String>,
        left: &str,
        right: &str,
        operator: &str,
        alias: impl Into<String>,
    ) -> &mut Self {
        self.join_on(Method::LeftJoin, table.into(), left, right, operator, alias.into())
    }

    /// `RIGHT JOIN`.
    ///
    /// PHP: `rightJoin()`.
    pub fn right_join(
        &mut self,
        table: impl Into<String>,
        left: &str,
        right: &str,
        operator: &str,
        alias: impl Into<String>,
    ) -> &mut Self {
        self.join_on(Method::RightJoin, table.into(), left, right, operator, alias.into())
    }

    /// A join whose conditions `callback` builds on a [`JoinBuilder`].
    ///
    /// PHP: `joinWhere()`.
    pub fn join_where(
        &mut self,
        table: impl Into<String>,
        callback: impl FnOnce(&mut JoinBuilder) -> Result<()>,
        join_type: JoinType,
        alias: impl Into<String>,
    ) -> Result<&mut Self> {
        let mut join = JoinBuilder::new();
        callback(&mut join)?;
        let method = match join_type {
            JoinType::Left => Method::LeftJoin,
            JoinType::Right => Method::RightJoin,
            JoinType::Cross => Method::CrossJoin,
            JoinType::FullOuter => Method::FullOuterJoin,
            JoinType::Natural => Method::NaturalJoin,
            JoinType::Inner => Method::Join,
        };
        self.core.pending.push(Query::new(method, table, Array::default(), alias));
        let index = self.core.pending.len() - 1;
        self.core.joins.insert(index, join);
        Ok(self)
    }

    fn union_with(&mut self, union_type: UnionType, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
        let result = other.build()?;
        self.core.unions.push(UnionClause::new(union_type, result.query, result.bindings));
        Ok(self)
    }

    /// `UNION` with another builder's select (built now).
    ///
    /// PHP: `union()`.
    pub fn union(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
        self.union_with(UnionType::Union, other)
    }

    /// `UNION ALL`.
    ///
    /// PHP: `unionAll()`.
    pub fn union_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
        self.union_with(UnionType::UnionAll, other)
    }

    /// `INTERSECT`.
    ///
    /// PHP: `intersect()`.
    pub fn intersect(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
        self.union_with(UnionType::Intersect, other)
    }

    /// `INTERSECT ALL`.
    ///
    /// PHP: `intersectAll()`.
    pub fn intersect_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
        self.union_with(UnionType::IntersectAll, other)
    }

    /// `EXCEPT`.
    ///
    /// PHP: `except()`.
    pub fn except(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
        self.union_with(UnionType::Except, other)
    }

    /// `EXCEPT ALL`.
    ///
    /// PHP: `exceptAll()`.
    pub fn except_all(&mut self, other: &mut dyn AnyBuilder) -> Result<&mut Self> {
        self.union_with(UnionType::ExceptAll, other)
    }

    /// `WITH name [(columns)] AS (query)` (built now).
    ///
    /// PHP: `with()`.
    pub fn with<S: Into<String>>(
        &mut self,
        name: impl Into<String>,
        query: &mut dyn AnyBuilder,
        columns: impl IntoIterator<Item = S>,
    ) -> Result<&mut Self> {
        let result = query.build()?;
        self.core.ctes.push(CteClause::new(name, result.query, result.bindings, false, strings(columns)));
        Ok(self)
    }

    /// `WITH RECURSIVE name AS (query)`.
    ///
    /// PHP: `withRecursive()`.
    pub fn with_recursive<S: Into<String>>(
        &mut self,
        name: impl Into<String>,
        query: &mut dyn AnyBuilder,
        columns: impl IntoIterator<Item = S>,
    ) -> Result<&mut Self> {
        let result = query.build()?;
        self.core.ctes.push(CteClause::new(name, result.query, result.bindings, true, strings(columns)));
        Ok(self)
    }

    /// `WITH RECURSIVE name AS (seed UNION ALL step)`.
    ///
    /// PHP: `withRecursiveSeedStep()`.
    pub fn with_recursive_seed_step<S: Into<String>>(
        &mut self,
        name: impl Into<String>,
        seed: &mut dyn AnyBuilder,
        step: &mut dyn AnyBuilder,
        columns: impl IntoIterator<Item = S>,
    ) -> Result<&mut Self> {
        let seed = seed.build()?;
        let step = step.build()?;
        let mut bindings = seed.bindings;
        bindings.extend(step.bindings);
        self.core.ctes.push(CteClause::new(
            name,
            format!("{} UNION ALL {}", seed.query, step.query),
            bindings,
            true,
            strings(columns),
        ));
        Ok(self)
    }

    /// The table to insert into.
    ///
    /// PHP: `into()`.
    pub fn into(&mut self, table: impl Into<String>) -> &mut Self {
        let table = table.into();
        self.defer_unbound(&format!("insert into table '{table}'"));
        self.core.table = table;
        self
    }

    /// `INSERT INTO table AS alias`.
    ///
    /// PHP: `insertAs()`.
    pub fn insert_as(&mut self, alias: impl Into<String>) -> &mut Self {
        self.core.insert_alias = alias.into();
        self
    }

    /// A row to insert (column => value), or the values of an update.
    ///
    /// PHP: `set()`.
    pub fn set(&mut self, row: Array) -> Result<&mut Self> {
        D::set(self, row)?;
        Ok(self)
    }

    /// The conflict target and the columns an upsert updates.
    ///
    /// PHP: `onConflict()`.
    pub fn on_conflict<K: Into<String>, U: Into<String>>(
        &mut self,
        keys: impl IntoIterator<Item = K>,
        update_columns: impl IntoIterator<Item = U>,
    ) -> &mut Self {
        self.core.conflict_keys = strings(keys);
        self.core.conflict_update_columns = strings(update_columns);
        self
    }

    /// `INSERT INTO table (columns) SELECT ...` from `source` (built at insert time).
    ///
    /// PHP: `fromSelect()`.
    pub fn from_select<S: Into<String>>(
        &mut self,
        columns: impl IntoIterator<Item = S>,
        source: Box<dyn AnyBuilder>,
    ) -> &mut Self {
        self.core.insert_select_columns = strings(columns);
        self.core.insert_select_source = Some(source);
        self
    }

    /// Compiles the insert.
    ///
    /// PHP: `insert()`.
    pub fn insert(&mut self) -> Result<Statement> {
        self.check_deferred()?;
        D::insert(self)
    }

    /// `INSERT INTO table DEFAULT VALUES` (MySQL: `() VALUES ()`).
    ///
    /// PHP: `insertDefaultValues()`.
    pub fn insert_default_values(&mut self) -> Result<Statement> {
        self.check_deferred()?;
        D::insert_default_values(self)
    }

    /// `INSERT INTO table (columns) SELECT ...`.
    ///
    /// PHP: `insertSelect()`.
    pub fn insert_select(&mut self) -> Result<Statement> {
        self.check_deferred()?;
        self.base_insert_select()
    }

    /// Compiles the update.
    ///
    /// PHP: `update()`.
    pub fn update(&mut self) -> Result<Statement> {
        self.check_deferred()?;
        D::update(self)
    }

    /// Compiles the delete.
    ///
    /// PHP: `delete()`.
    pub fn delete(&mut self) -> Result<Statement> {
        self.check_deferred()?;
        D::delete(self)
    }

    /// Adds a hook: a filter, an attribute resolver, a join filter, or several at once.
    ///
    /// PHP: `addHook()`.
    pub fn add_hook(&mut self, hook: impl Into<Hook>) -> Result<&mut Self> {
        D::add_hook(self, hook.into())?;
        Ok(self)
    }

    /// A window function in the select list: `function OVER (...) AS alias`,
    /// or `OVER window_name`. The function must look like `NAME(args)`.
    ///
    /// PHP: `selectWindow()`.
    pub fn select_window(
        &mut self,
        function: impl Into<String>,
        alias: impl Into<String>,
        partition_by: Option<Vec<String>>,
        order_by: Option<Vec<String>>,
        window_name: Option<String>,
        frame: Option<WindowFrame>,
    ) -> Result<&mut Self> {
        let function = function.into();
        if !is_window_function(&function) {
            return Err(Error::Validation(format!("Invalid window function: {function}")));
        }
        self.core.window_selects.push(WindowSelect::new(function, alias, partition_by, order_by, window_name, frame));
        Ok(self)
    }

    /// A named window: `WINDOW name AS (...)`.
    ///
    /// PHP: `window()`.
    pub fn window(
        &mut self,
        name: impl Into<String>,
        partition_by: Option<Vec<String>>,
        order_by: Option<Vec<String>>,
        frame: Option<WindowFrame>,
    ) -> &mut Self {
        self.core.window_definitions.push(WindowDefinition::new(name, partition_by, order_by, frame));
        self
    }

    /// The queries added so far.
    pub fn pending(&self) -> &[Query] {
        &self.core.pending
    }

    pub(crate) fn push_case(&mut self, case: CaseExpression) {
        self.core.cases.push(case);
    }

    pub(crate) fn add_lateral(&mut self, subquery: Box<dyn AnyBuilder>, alias: String, join_type: JoinType) {
        self.core.lateral_joins.push(LateralJoin { subquery, alias, join_type });
    }
}

impl<D: Dialect> Compiler for Builder<D> {
    fn compile_filter(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileFilter, &[Arg::Query(query)])
    }

    fn compile_order(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileOrder, &[Arg::Query(query)])
    }

    fn compile_limit(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileLimit, &[Arg::Query(query)])
    }

    fn compile_offset(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileOffset, &[Arg::Query(query)])
    }

    fn compile_select(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileSelect, &[Arg::Query(query)])
    }

    fn compile_cursor(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileCursor, &[Arg::Query(query)])
    }

    fn compile_aggregate(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileAggregate, &[Arg::Query(query)])
    }

    fn compile_group_by(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileGroupBy, &[Arg::Query(query)])
    }

    fn compile_join(&mut self, query: &Query) -> Result<String> {
        self.step_string(Step::CompileJoin, &[Arg::Query(query)])
    }
}

impl<D: Dialect> AnyBuilder for Builder<D> {
    fn build(&mut self) -> Result<Statement> {
        D::build(self)
    }

    fn clone_box(&self) -> Box<dyn AnyBuilder> {
        Box::new(self.clone())
    }

    fn php_class(&self) -> &'static str {
        D::CLASS
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}