Skip to main content

utopia_query/builder/
core.rs

1//! [`Builder`]: the state every dialect shares, and the compilation PHP's
2//! abstract `Utopia\Query\Builder` implements; [`Dialect`]: what a dialect
3//! changes.
4
5use std::collections::{HashMap, HashSet};
6use std::sync::Arc;
7
8use php_std::ArrayKey;
9use php_std::json::Flags;
10
11use crate::builder::AnyBuilder;
12use crate::builder::case::{CaseExpression, Kind as CaseKind, WhenClause};
13use crate::builder::join::JoinBuilder;
14use crate::builder::steps::{Arg, Step};
15use crate::builder::types::{
16    Binding, ColumnPredicate, Condition, CteClause, Executor, JoinType, LockMode, Statement, UnionClause,
17    WindowDefinition, WindowSelect,
18};
19use crate::error::{Error, Result};
20use crate::hook::{Attribute, Filter, Hook, JoinFilter, Placement};
21use crate::method::Method;
22use crate::query::{ParsedQuery, Query, is_numeric};
23use crate::value::{self, Array, Object, Param, Value};
24
25/// A builder used as a source: `FROM (subquery) AS alias`, a select-list
26/// subquery.
27///
28/// PHP: `Utopia\Query\Builder\SubSelect`.
29#[derive(Clone)]
30pub struct SubSelect {
31    /// The subquery.
32    pub subquery: Box<dyn AnyBuilder>,
33    /// Its alias.
34    pub alias: String,
35}
36
37/// `column [NOT] IN (subquery)`.
38///
39/// PHP: `Utopia\Query\Builder\WhereInSubquery`.
40#[derive(Clone)]
41pub struct WhereInSubquery {
42    /// The column.
43    pub column: String,
44    /// The subquery.
45    pub subquery: Box<dyn AnyBuilder>,
46    /// Whether it is `NOT IN`.
47    pub not: bool,
48}
49
50/// `[NOT] EXISTS (subquery)`.
51///
52/// PHP: `Utopia\Query\Builder\ExistsSubquery`.
53#[derive(Clone)]
54pub struct ExistsSubquery {
55    /// The subquery.
56    pub subquery: Box<dyn AnyBuilder>,
57    /// Whether it is `NOT EXISTS`.
58    pub not: bool,
59}
60
61/// `[LEFT] JOIN LATERAL (subquery) AS alias ON true`.
62///
63/// PHP: `Utopia\Query\Builder\LateralJoin`.
64#[derive(Clone)]
65pub struct LateralJoin {
66    /// The subquery.
67    pub subquery: Box<dyn AnyBuilder>,
68    /// Its alias.
69    pub alias: String,
70    /// `Inner` or `Left`.
71    pub join_type: JoinType,
72}
73
74/// A map kept in insertion order where setting a key again replaces its
75/// value in place (a PHP array keyed by column).
76#[derive(Debug, Clone, PartialEq)]
77pub(crate) struct Ordered<T>(pub(crate) Vec<(String, T)>);
78
79impl<T> Default for Ordered<T> {
80    fn default() -> Self {
81        Ordered(Vec::new())
82    }
83}
84
85impl<T> Ordered<T> {
86    pub(crate) fn set(&mut self, key: impl Into<String>, value: T) {
87        let key = key.into();
88        match self.0.iter_mut().find(|(k, _)| *k == key) {
89            Some(entry) => entry.1 = value,
90            None => self.0.push((key, value)),
91        }
92    }
93
94    pub(crate) fn get(&self, key: &str) -> Option<&T> {
95        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
96    }
97
98    pub(crate) fn clear(&mut self) {
99        self.0.clear();
100    }
101}
102
103/// A callback run at the start of every build, with the builder.
104pub type BeforeBuild<D> = Arc<dyn Fn(&mut Builder<D>) -> Result<()> + Send + Sync>;
105
106/// A callback run on every built statement, returning the statement to use.
107pub type AfterBuild = Arc<dyn Fn(usize, Statement) -> Result<Statement> + Send + Sync>;
108
109/// The state of a builder that every dialect shares: what PHP's abstract
110/// `Builder` and its traits hold.
111#[derive(Clone, Default)]
112pub struct Core {
113    pub(crate) table: String,
114    pub(crate) alias: String,
115    pub(crate) pending: Vec<Query>,
116    pub(crate) bindings: Vec<Binding>,
117    pub(crate) unions: Vec<UnionClause>,
118    pub(crate) filter_hooks: Vec<Arc<dyn Filter>>,
119    pub(crate) attribute_hooks: Vec<Arc<dyn Attribute>>,
120    pub(crate) join_filter_hooks: Vec<Arc<dyn JoinFilter>>,
121    pub(crate) resolved: HashMap<String, String>,
122    pub(crate) rows: Vec<Array>,
123    pub(crate) raw_sets: Ordered<String>,
124    pub(crate) raw_set_bindings: Ordered<Vec<Value>>,
125    pub(crate) lock_mode: Option<LockMode>,
126    pub(crate) lock_of_table: Option<String>,
127    pub(crate) insert_select_source: Option<Box<dyn AnyBuilder>>,
128    pub(crate) insert_select_columns: Vec<String>,
129    pub(crate) ctes: Vec<CteClause>,
130    pub(crate) raw_selects: Vec<Condition>,
131    pub(crate) window_selects: Vec<WindowSelect>,
132    pub(crate) window_definitions: Vec<WindowDefinition>,
133    pub(crate) sample: Option<(f64, String)>,
134    pub(crate) cases: Vec<CaseExpression>,
135    pub(crate) case_sets: Ordered<CaseExpression>,
136    pub(crate) insert_column_expressions: Ordered<String>,
137    pub(crate) insert_column_expression_bindings: Ordered<Vec<Value>>,
138    pub(crate) insert_alias: String,
139    pub(crate) where_in_subqueries: Vec<WhereInSubquery>,
140    pub(crate) sub_selects: Vec<SubSelect>,
141    pub(crate) from_subquery: Option<SubSelect>,
142    pub(crate) tableless: bool,
143    pub(crate) raw_orders: Vec<Condition>,
144    pub(crate) raw_groups: Vec<Condition>,
145    pub(crate) raw_havings: Vec<Condition>,
146    pub(crate) raw_wheres: Vec<Condition>,
147    pub(crate) column_predicates: Vec<ColumnPredicate>,
148    pub(crate) joins: HashMap<usize, JoinBuilder>,
149    pub(crate) exists_subqueries: Vec<ExistsSubquery>,
150    pub(crate) lateral_joins: Vec<LateralJoin>,
151    pub(crate) after_build: Vec<AfterBuild>,
152    pub(crate) executor: Option<Executor>,
153    pub(crate) qualify: bool,
154    pub(crate) aggregation_aliases: HashSet<String>,
155    pub(crate) fetch_count: Option<i64>,
156    pub(crate) fetch_with_ties: bool,
157    pub(crate) conflict_keys: Vec<String>,
158    pub(crate) conflict_update_columns: Vec<String>,
159    pub(crate) conflict_raw_sets: Ordered<String>,
160    pub(crate) conflict_raw_set_bindings: Ordered<Vec<Value>>,
161    pub(crate) hints: Vec<String>,
162    pub(crate) json_sets: Ordered<Condition>,
163    pub(crate) returning: Vec<String>,
164    pub(crate) group_by_modifier: Option<String>,
165    pub(crate) flavor: crate::builder::flavor::Flavor,
166    pub(crate) scope: Option<crate::builder::flavor::ScopeState>,
167    pub(crate) deferred: Option<Error>,
168    pub(crate) overrides: Option<Arc<dyn crate::builder::Overrides>>,
169    pub(crate) class: Option<String>,
170    pub(crate) steps: u128,
171    /// Whose builder this is, to the overrides and `after_build` callbacks: a clone has no owner.
172    pub(crate) owner: usize,
173}
174
175/// A query builder for one dialect: from a table, with queries (filters,
176/// ordering, pagination, aggregates, joins) and the builder's own clauses
177/// (subqueries, raw SQL, window functions, CTEs, unions), compiled by
178/// [`Builder::build`] into a [`Statement`]; also inserts, updates, deletes and
179/// upserts.
180///
181/// The dialects are type aliases: [`MySql`](crate::builder::MySql) and the
182/// others. Features only some dialects have are traits in
183/// [`feature`](crate::builder::feature).
184///
185/// PHP: the abstract `Utopia\Query\Builder` and its subclasses.
186pub struct Builder<D: Dialect> {
187    pub(crate) core: Core,
188    pub(crate) before_build: Vec<BeforeBuild<D>>,
189    pub(crate) dialect: D,
190}
191
192impl<D: Dialect> Clone for Builder<D> {
193    /// A deep copy (subqueries included); hooks, callbacks and the executor are shared.
194    fn clone(&self) -> Self {
195        let mut core = self.core.clone();
196        core.owner = 0;
197        Builder { core, before_build: self.before_build.clone(), dialect: self.dialect.clone() }
198    }
199}
200
201impl<D: Dialect> Default for Builder<D> {
202    fn default() -> Self {
203        Builder { core: Core::default(), before_build: Vec::new(), dialect: D::default() }
204    }
205}
206
207/// What a dialect changes in the shared compilation: identifier quoting,
208/// random order, regex, and the clauses only some dialects emit. Every hook
209/// has the behaviour of PHP's base `Builder` unless the dialect overrides it.
210pub trait Dialect: Clone + Default + Send + Sync + Sized + 'static {
211    /// The PHP class (`Utopia\Query\Builder\MySQL`), as messages name it.
212    const CLASS: &'static str;
213
214    /// The identifier quote character.
215    const WRAP: char = '`';
216
217    /// The character that escapes `%`, `_` and itself in a `LIKE` pattern.
218    ///
219    /// PHP: `LIKE_ESCAPE`.
220    const LIKE_ESCAPE: u8 = b'\\';
221
222    /// Whether a `LIKE` names its escape character (`LIKE ? ESCAPE '!'`).
223    ///
224    /// PHP: `DECLARES_LIKE_ESCAPE`.
225    const DECLARES_LIKE_ESCAPE: bool = false;
226
227    /// The character `LIKE` escapes with when a pattern declares none; `None` when it escapes
228    /// nothing, as in SQLite.
229    ///
230    /// PHP: `IMPLICIT_LIKE_ESCAPE`.
231    const IMPLICIT_LIKE_ESCAPE: Option<u8> = Some(b'\\');
232
233    /// How the dialect writes and reads a string literal.
234    ///
235    /// PHP: `$literal`.
236    const LITERAL: crate::StringLiteral = crate::StringLiteral::Backslash;
237
238    /// Quotes an identifier (`` `users`.`id` ``).
239    fn quote(_b: &Builder<Self>, identifier: &str) -> Result<String> {
240        crate::quote::quote(identifier, Self::WRAP)
241    }
242
243    /// A string literal for `to_raw_sql()`: `\` doubled and `'` doubled
244    /// (PostgreSQL and SQLite double only `'`, since `\` is not an escape
245    /// in their standard strings).
246    ///
247    /// PHP: `quoteString()`.
248    fn quote_string(value: &[u8]) -> Vec<u8> {
249        quote_bytes(value, true)
250    }
251
252    /// A step only some dialects have, run as the dialect itself does: `None` where the
253    /// dialect has no such step.
254    fn base_step(_b: &mut Builder<Self>, _step: Step, _arguments: &[Arg<'_>]) -> Option<Result<crate::builder::Ret>> {
255        None
256    }
257
258    /// The random-order expression (`RAND()`).
259    fn compile_random(b: &Builder<Self>) -> String;
260
261    /// A regex filter on the wrapped attribute.
262    fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String>;
263
264    /// A filter query (the base compiles comparisons, LIKE, IN, logical and raw filters).
265    fn compile_filter(b: &mut Builder<Self>, query: &Query) -> Result<String> {
266        b.base_compile_filter(query)
267    }
268
269    /// `LIKE` with a prefix and suffix around the escaped value.
270    fn compile_like(
271        b: &mut Builder<Self>,
272        attribute: &str,
273        values: &Array,
274        prefix: &str,
275        suffix: &str,
276        not: bool,
277        column: Option<&str>,
278    ) -> Result<String> {
279        b.base_compile_like(attribute, values, prefix, suffix, not, column)
280    }
281
282    /// `contains` (`LIKE '%v%'`, `OR`ed for several values).
283    fn compile_contains(
284        b: &mut Builder<Self>,
285        attribute: &str,
286        values: &Array,
287        column: Option<&str>,
288    ) -> Result<String> {
289        b.base_compile_contains(attribute, values, column)
290    }
291
292    /// `containsAll` (`LIKE '%v%'`, `AND`ed).
293    fn compile_contains_all(
294        b: &mut Builder<Self>,
295        attribute: &str,
296        values: &Array,
297        column: Option<&str>,
298    ) -> Result<String> {
299        b.base_compile_contains_all(attribute, values, column)
300    }
301
302    /// `notContains` (`NOT LIKE '%v%'`, `AND`ed).
303    fn compile_not_contains(
304        b: &mut Builder<Self>,
305        attribute: &str,
306        values: &Array,
307        column: Option<&str>,
308    ) -> Result<String> {
309        b.base_compile_not_contains(attribute, values, column)
310    }
311
312    /// The `LIKE` keyword (`ILIKE` on PostgreSQL).
313    fn like_keyword(_b: &Builder<Self>) -> &'static str {
314        "LIKE"
315    }
316
317    /// The `FROM` clause.
318    fn build_table_clause(b: &mut Builder<Self>) -> Result<String> {
319        b.base_build_table_clause()
320    }
321
322    /// Clauses after the joins and before `WHERE` (ClickHouse `ARRAY JOIN`, `PREWHERE`).
323    fn build_after_joins_clause(_b: &mut Builder<Self>, _grouped: &ParsedQuery) -> Result<String> {
324        Ok(String::new())
325    }
326
327    /// Clauses after `GROUP BY` (ClickHouse `WITH TOTALS`).
328    fn build_after_group_by_clause(_b: &mut Builder<Self>) -> Result<String> {
329        Ok(String::new())
330    }
331
332    /// Clauses after `ORDER BY` (ClickHouse `LIMIT BY`).
333    fn build_after_order_by_clause(_b: &mut Builder<Self>) -> Result<String> {
334        Ok(String::new())
335    }
336
337    /// Clauses at the very end of a select (ClickHouse `SETTINGS`).
338    fn build_settings_clause(_b: &mut Builder<Self>) -> Result<String> {
339        Ok(String::new())
340    }
341
342    /// One member of a `UNION` chain (parenthesised by default).
343    fn wrap_union_member(_b: &Builder<Self>, sql: &str) -> String {
344        format!("({sql})")
345    }
346
347    /// Whether to emit `OFFSET`; the base refuses an offset without a limit.
348    fn should_emit_offset(_b: &Builder<Self>, offset: Option<i64>, limit: Option<i64>) -> Result<bool> {
349        match (offset, limit) {
350            (None, _) => Ok(false),
351            (Some(_), None) => Err(Error::Validation(
352                "OFFSET requires LIMIT on this engine. Set a limit or use the dialect's native no-limit form.".into(),
353            )),
354            (Some(_), Some(_)) => Ok(true),
355        }
356    }
357
358    /// An `ORDER BY` vector distance expression (PostgreSQL).
359    fn compile_vector_order_expression(_b: &mut Builder<Self>) -> Result<Option<Condition>> {
360        Ok(None)
361    }
362
363    /// A `groupByTimeBucket` expression; unsupported by default.
364    fn compile_group_by_time_bucket(_b: &mut Builder<Self>, _attribute: &str, _interval: &str) -> Result<String> {
365        Err(Error::Unsupported(format!("groupByTimeBucket is not supported by {}", _b.class())))
366    }
367
368    /// Where a join filter's condition goes (cross and natural joins have no `ON`).
369    fn resolve_join_filter_placement(_b: &Builder<Self>, requested: Placement, is_cross_join: bool) -> Placement {
370        if is_cross_join { Placement::Where } else { requested }
371    }
372
373    /// The `ON` of a join built with a [`JoinBuilder`].
374    fn compile_join_with_builder(b: &mut Builder<Self>, query: &Query, join: &JoinBuilder) -> Result<String> {
375        b.base_compile_join_with_builder(query, join)
376    }
377
378    /// Compiles the select statement.
379    fn build(b: &mut Builder<Self>) -> Result<Statement> {
380        b.base_build()
381    }
382
383    /// Compiles the insert statement.
384    fn insert(b: &mut Builder<Self>) -> Result<Statement> {
385        b.base_insert()
386    }
387
388    /// `INSERT ... DEFAULT VALUES`.
389    fn insert_default_values(b: &mut Builder<Self>) -> Result<Statement> {
390        b.base_insert_default_values()
391    }
392
393    /// Compiles the update statement.
394    fn update(b: &mut Builder<Self>) -> Result<Statement> {
395        b.base_update()
396    }
397
398    /// Compiles the delete statement.
399    fn delete(b: &mut Builder<Self>) -> Result<Statement> {
400        b.base_delete()
401    }
402
403    /// `EXPLAIN` of the select statement.
404    fn explain(b: &mut Builder<Self>, analyze: bool, _options: &ExplainOptions) -> Result<Statement> {
405        b.base_explain(analyze)
406    }
407
408    /// Clears the dialect's own state (after the shared state is cleared).
409    fn reset(_b: &mut Builder<Self>) {}
410
411    /// Adds a hook.
412    fn add_hook(b: &mut Builder<Self>, hook: Hook) -> Result<()> {
413        b.base_add_hook(hook);
414        Ok(())
415    }
416
417    /// Adds a row to insert or the values to update.
418    fn set(b: &mut Builder<Self>, row: Array) -> Result<()> {
419        b.core.rows.push(row);
420        Ok(())
421    }
422
423    /// The serializer `fromAst`/`toAst` use for expressions.
424    fn ast_dialect() -> crate::builder::AstDialect {
425        crate::builder::AstDialect::Standard
426    }
427}
428
429/// The options of `EXPLAIN` beyond `ANALYZE`, for the dialects that have them.
430#[derive(Debug, Clone, Default, PartialEq, Eq)]
431pub struct ExplainOptions {
432    /// `VERBOSE` (PostgreSQL).
433    pub verbose: bool,
434    /// `BUFFERS` (PostgreSQL).
435    pub buffers: bool,
436    /// The output format (`JSON`), or empty.
437    pub format: String,
438}
439
440impl<D: Dialect> Builder<D> {
441    /// An empty builder.
442    pub fn new() -> Self {
443        Builder::default()
444    }
445
446    /// The dialect's state.
447    pub fn dialect(&self) -> &D {
448        &self.dialect
449    }
450
451    /// The PHP class messages name: the dialect's, or the subclass of it given to
452    /// [`Builder::set_class`].
453    ///
454    /// PHP: `static::class`.
455    pub fn class(&self) -> &str {
456        self.core.class.as_deref().unwrap_or(D::CLASS)
457    }
458
459    /// Names the PHP class of the builder, when it is a subclass of the dialect's.
460    pub fn set_class(&mut self, class: impl Into<String>) -> &mut Self {
461        self.core.class = Some(class.into());
462        self
463    }
464
465    /// PHP: `$this->quote()`, which a subclass may override.
466    pub(crate) fn quote(&mut self, identifier: &str) -> Result<String> {
467        if !self.overrides(Step::Quote) {
468            return D::quote(self, identifier);
469        }
470        self.step_string(Step::Quote, &[Arg::Str(identifier)])
471    }
472
473    pub(crate) fn add_binding(&mut self, value: Value, column: Option<&str>) {
474        if self.core.overrides.is_none() {
475            return self.base_add_binding(value, column);
476        }
477        // An override that fails has nowhere to say so here: the build it is part of does.
478        if let Err(error) = self.step(Step::AddBinding, &[Arg::Value(&value), Arg::MaybeStr(column)]) {
479            self.core.deferred.get_or_insert(error);
480        }
481    }
482
483    pub(crate) fn base_add_binding(&mut self, value: Value, column: Option<&str>) {
484        self.core.bindings.push(Binding::new(value, column.map(str::to_owned)));
485    }
486
487    /// Binds each of `values`.
488    ///
489    /// PHP: `addBindings()`.
490    pub(crate) fn base_add_bindings(&mut self, values: impl IntoIterator<Item = Value>) {
491        for value in values {
492            self.core.bindings.push(Binding::new(value, None));
493        }
494    }
495
496    /// PHP: `$this->getBindingValues()`, which a subclass may override.
497    pub(crate) fn binding_values(&mut self) -> Vec<Value> {
498        if !self.overrides(Step::GetBindingValues) {
499            return self.base_binding_values();
500        }
501        // An override that fails has nowhere to say so here: the build it is part of does.
502        match self.step(Step::GetBindingValues, &[]) {
503            Ok(crate::builder::steps::Ret::Values(values)) => values,
504            Ok(_) => self.base_binding_values(),
505            Err(error) => {
506                self.core.deferred.get_or_insert(error);
507                self.base_binding_values()
508            }
509        }
510    }
511
512    /// The values bound so far.
513    ///
514    /// PHP: `parent::getBindingValues()`.
515    pub fn base_binding_values(&self) -> Vec<Value> {
516        self.core.bindings.iter().map(|b| b.value.clone()).collect()
517    }
518
519    /// PHP: `$this->getLikeKeyword()`, which a subclass may override.
520    pub(crate) fn like_keyword(&mut self) -> Result<String> {
521        if !self.overrides(Step::GetLikeKeyword) {
522            return Ok(D::like_keyword(self).to_owned());
523        }
524        self.step_string(Step::GetLikeKeyword, &[])
525    }
526
527    /// PHP: `$this->geometryToWkt()`, which a subclass may override.
528    pub(crate) fn geometry_to_wkt(&mut self, geometry: &Array) -> Result<String> {
529        if !self.overrides(Step::GeometryToWkt) {
530            return crate::builder::sql::geometry_to_wkt(geometry);
531        }
532        self.step_string(Step::GeometryToWkt, &[Arg::Values(geometry)])
533    }
534
535    pub(crate) fn statement(&mut self, sql: impl Into<String>) -> Statement {
536        Statement::with_parts(sql, self.binding_values(), false, self.core.executor.clone(), None)
537    }
538
539    pub(crate) fn resolve_attribute(&mut self, attribute: &str) -> Result<String> {
540        self.step_string(Step::ResolveAttribute, &[Arg::Str(attribute)])
541    }
542
543    pub(crate) fn base_resolve_attribute(&mut self, attribute: &str) -> Result<String> {
544        if let Some(resolved) = self.core.resolved.get(attribute) {
545            return Ok(resolved.clone());
546        }
547        let mut resolved = attribute.to_owned();
548        for hook in self.core.attribute_hooks.clone() {
549            resolved = hook.resolve(&resolved)?;
550        }
551        self.core.resolved.insert(attribute.to_owned(), resolved.clone());
552        Ok(resolved)
553    }
554
555    pub(crate) fn resolve_and_wrap(&mut self, attribute: &str) -> Result<String> {
556        self.step_string(Step::ResolveAndWrap, &[Arg::Str(attribute)])
557    }
558
559    pub(crate) fn base_resolve_and_wrap(&mut self, attribute: &str) -> Result<String> {
560        let mut resolved = self.resolve_attribute(attribute)?;
561        if self.core.qualify
562            && resolved != "*"
563            && !resolved.contains('.')
564            && !self.core.aggregation_aliases.contains(&resolved)
565        {
566            resolved = format!("{}.{}", self.core.alias, resolved);
567        }
568        self.quote(&resolved)
569    }
570
571    /// Refuses a builder with no table.
572    ///
573    /// PHP: `validateTable()`.
574    pub(crate) fn base_validate_table(&self) -> Result<()> {
575        if self.core.tableless {
576            return Ok(());
577        }
578        if self.core.table.is_empty() && self.core.from_subquery.is_none() {
579            return Err(Error::Validation("No table specified. Call from() or into() before building a query.".into()));
580        }
581        Ok(())
582    }
583
584    /// Refuses `operation` on a builder with no rows, or with an empty one.
585    ///
586    /// PHP: `validateRows()`.
587    pub(crate) fn base_validate_rows(&self, operation: &str) -> Result<()> {
588        if self.core.rows.is_empty() {
589            return Err(Error::Validation(format!("No rows to {operation}. Call set() before {operation}().")));
590        }
591        if self.core.rows.iter().any(Array::is_empty) {
592            return Err(Error::Validation(format!(
593                "Cannot {operation} an empty row. Each set() call must include at least one column."
594            )));
595        }
596        Ok(())
597    }
598
599    /// The columns of the rows: the first row's keys; every row must have the same set.
600    pub(crate) fn base_validate_and_get_columns(&self) -> Result<Vec<ArrayKey>> {
601        // PHP reads `$this->rows[0]` whatever is there, which every caller has checked. Now that
602        // a subclass can call this on its own, no rows is an error, not a panic.
603        let Some(first) = self.core.rows.first() else {
604            return Err(Error::Validation("No rows to take columns from.".into()));
605        };
606        let columns: Vec<ArrayKey> = first.keys().map(|k| k.to_owned()).collect();
607        if columns.iter().any(|c| matches!(c, ArrayKey::Str(s) if s.is_empty())) {
608            return Err(Error::Validation("Column names must be non-empty strings.".into()));
609        }
610        if self.core.rows.len() > 1 {
611            let sorted = |keys: Vec<ArrayKey>| {
612                let mut values: Vec<Value> = keys.into_iter().map(key_value).collect();
613                values.sort_by(|a, b| a.cmp_php(b));
614                values
615            };
616            let expected = sorted(columns.clone());
617            for (i, row) in self.core.rows.iter().enumerate() {
618                let keys = sorted(row.keys().map(|k| k.to_owned()).collect());
619                if keys.len() != expected.len() || keys.iter().zip(&expected).any(|(a, b)| !a.strict_eq(b)) {
620                    return Err(Error::Validation(format!(
621                        "Row {i} has different columns than row 0. All rows in a batch must have the same columns."
622                    )));
623                }
624            }
625        }
626        Ok(columns)
627    }
628
629    // ----- select ---------------------------------------------------------
630
631    pub(crate) fn base_build(&mut self) -> Result<Statement> {
632        self.core.bindings.clear();
633        self.core.resolved.clear();
634        for callback in self.before_build.clone() {
635            callback(self)?;
636        }
637        self.validate_table()?;
638        let cte_prefix = self.build_cte_prefix()?;
639        let grouped = Query::group_by_type(&self.core.pending);
640        self.prepare_alias_qualification(&grouped);
641
642        let mut join_filter_where = Vec::new();
643        let mut parts = vec![self.build_select_clause(&grouped)?];
644        let push = |parts: &mut Vec<String>, fragment: String| {
645            if !fragment.is_empty() {
646                parts.push(fragment);
647            }
648        };
649        let from = self.step_string(Step::BuildTableClause, &[])?;
650        push(&mut parts, from);
651        let joins = self.build_joins_clause(&grouped, &mut join_filter_where)?;
652        push(&mut parts, joins);
653        let after_joins = self.step_string(Step::BuildAfterJoinsClause, &[Arg::Parsed(Some(&grouped))])?;
654        push(&mut parts, after_joins);
655        let where_ = self.build_where_clause(&grouped, join_filter_where)?;
656        push(&mut parts, where_);
657        let group_by = self.build_group_by_clause(&grouped)?;
658        push(&mut parts, group_by);
659        let after_group_by = self.step_string(Step::BuildAfterGroupByClause, &[])?;
660        push(&mut parts, after_group_by);
661        let having = self.build_having_clause(&grouped)?;
662        push(&mut parts, having);
663        let window = self.build_window_clause()?;
664        push(&mut parts, window);
665        let order_by = self.build_order_by_clause()?;
666        push(&mut parts, order_by);
667        let after_order_by = self.step_string(Step::BuildAfterOrderByClause, &[])?;
668        push(&mut parts, after_order_by);
669        let limit = self.build_limit_clause(&grouped)?;
670        push(&mut parts, limit);
671        let locking = self.build_locking_clause()?;
672        push(&mut parts, locking);
673        let settings = self.step_string(Step::BuildSettingsClause, &[])?;
674        push(&mut parts, settings);
675
676        let mut sql = parts.join(" ");
677        let union_suffix = self.build_union_suffix()?;
678        if !union_suffix.is_empty() {
679            sql = self.step_string(Step::WrapUnionMember, &[Arg::Str(&sql)])? + &union_suffix;
680        }
681        let sql = cte_prefix + &sql;
682
683        let mut result = Statement::with_parts(sql, self.binding_values(), true, self.core.executor.clone(), None);
684        for callback in self.core.after_build.clone() {
685            result = callback(self.core.owner, result)?;
686        }
687        Ok(result)
688    }
689
690    fn build_cte_prefix(&mut self) -> Result<String> {
691        if self.core.ctes.is_empty() {
692            return Ok(String::new());
693        }
694        let mut recursive = false;
695        let mut parts = Vec::with_capacity(self.core.ctes.len());
696        for cte in self.core.ctes.clone() {
697            if cte.recursive {
698                recursive = true;
699            }
700            self.add_bindings(cte.bindings);
701            let mut name = self.quote(&cte.name)?;
702            if !cte.columns.is_empty() {
703                let columns = cte.columns.iter().map(|c| self.quote(c)).collect::<Result<Vec<_>>>()?;
704                name.push('(');
705                name.push_str(&columns.join(", "));
706                name.push(')');
707            }
708            parts.push(format!("{name} AS ({})", cte.query));
709        }
710        let keyword = if recursive { "WITH RECURSIVE" } else { "WITH" };
711        Ok(format!("{keyword} {} ", parts.join(", ")))
712    }
713
714    pub(crate) fn prepare_alias_qualification(&mut self, grouped: &ParsedQuery) {
715        self.core.qualify = false;
716        self.core.aggregation_aliases.clear();
717        if grouped.joins.is_empty() || self.core.alias.is_empty() {
718            return;
719        }
720        self.core.qualify = true;
721        for aggregate in &grouped.aggregations {
722            if !aggregate.alias().is_empty() {
723                self.core.aggregation_aliases.insert(aggregate.alias().to_owned());
724            }
725        }
726    }
727
728    fn build_select_clause(&mut self, grouped: &ParsedQuery) -> Result<String> {
729        let mut parts = Vec::new();
730        for aggregate in &grouped.aggregations {
731            parts.push(self.step_string(Step::CompileAggregate, &[Arg::Query(aggregate)])?);
732        }
733        if let Some(selection) = grouped.selections.first() {
734            parts.push(self.step_string(Step::CompileSelect, &[Arg::Query(selection)])?);
735        }
736        for sub in self.core.sub_selects.clone() {
737            let mut subquery = sub.subquery.clone();
738            let result = subquery.build()?;
739            parts.push(format!("({}) AS {}", result.query, self.quote(&sub.alias)?));
740            self.add_bindings(result.bindings);
741        }
742        for raw in self.core.raw_selects.clone() {
743            parts.push(raw.expression);
744            self.add_bindings(raw.bindings);
745        }
746        for window in self.core.window_selects.clone() {
747            parts.push(self.compile_window_select(&window)?);
748        }
749        for case in self.core.cases.clone() {
750            parts.push(self.compile_case(&case)?);
751        }
752        let list = if parts.is_empty() { "*".to_owned() } else { parts.join(", ") };
753        let keyword = if grouped.distinct { "SELECT DISTINCT" } else { "SELECT" };
754        Ok(format!("{keyword} {list}"))
755    }
756
757    fn compile_window_select(&mut self, window: &WindowSelect) -> Result<String> {
758        if let Some(name) = &window.window_name {
759            return Ok(format!("{} OVER {} AS {}", window.function, self.quote(name)?, self.quote(&window.alias)?));
760        }
761        let mut over = Vec::new();
762        if let Some(partition) = window.partition_by.as_ref().filter(|p| !p.is_empty()) {
763            let columns = partition.iter().map(|c| self.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
764            over.push(format!("PARTITION BY {}", columns.join(", ")));
765        }
766        if let Some(order) = window.order_by.as_ref().filter(|o| !o.is_empty()) {
767            over.push(format!("ORDER BY {}", self.compile_order_by_list(order)?));
768        }
769        if let Some(frame) = &window.frame {
770            over.push(frame.to_sql());
771        }
772        Ok(format!("{} OVER ({}) AS {}", window.function, over.join(" "), self.quote(&window.alias)?))
773    }
774
775    pub(crate) fn compile_order_by_list(&mut self, order_by: &[String]) -> Result<String> {
776        let mut columns = Vec::with_capacity(order_by.len());
777        for column in order_by {
778            match column.strip_prefix('-') {
779                Some(name) => columns.push(format!("{} DESC", self.resolve_and_wrap(name)?)),
780                None => columns.push(format!("{} ASC", self.resolve_and_wrap(column)?)),
781            }
782        }
783        Ok(columns.join(", "))
784    }
785
786    pub(crate) fn base_build_table_clause(&mut self) -> Result<String> {
787        if self.core.tableless {
788            return Ok(String::new());
789        }
790        if let Some(sub) = self.core.from_subquery.clone() {
791            let mut subquery = sub.subquery;
792            let result = subquery.build()?;
793            self.add_bindings(result.bindings);
794            return Ok(format!("FROM ({}) AS {}", result.query, self.quote(&sub.alias)?));
795        }
796        let mut sql = format!("FROM {}", self.quote(&self.core.table.clone())?);
797        if !self.core.alias.is_empty() {
798            sql.push_str(" AS ");
799            sql.push_str(&self.quote(&self.core.alias.clone())?);
800        }
801        if let Some((percent, method)) = &self.core.sample {
802            sql.push_str(&format!(" TABLESAMPLE {method}({})", php_std::number::to_string(*percent)));
803        }
804        Ok(sql)
805    }
806
807    fn build_joins_clause(&mut self, grouped: &ParsedQuery, join_filter_where: &mut Vec<Condition>) -> Result<String> {
808        let mut parts = Vec::new();
809        if !grouped.joins.is_empty() {
810            let join_indices: Vec<usize> =
811                self.core.pending.iter().enumerate().filter(|(_, q)| q.method().is_join()).map(|(i, _)| i).collect();
812            for (join_index, join) in grouped.joins.iter().enumerate() {
813                let pending_index = join_indices.get(join_index).copied();
814                let builder = pending_index.and_then(|i| self.core.joins.get(&i)).cloned();
815                let mut sql = match builder {
816                    Some(builder) => {
817                        self.step_string(Step::CompileJoinWithBuilder, &[Arg::Query(join), Arg::Join(&builder)])?
818                    }
819                    None => self.step_string(Step::CompileJoin, &[Arg::Query(join)])?,
820                };
821                let join_type = match join.method() {
822                    Method::Join => JoinType::Inner,
823                    Method::LeftJoin => JoinType::Left,
824                    Method::RightJoin => JoinType::Right,
825                    Method::CrossJoin => JoinType::Cross,
826                    Method::FullOuterJoin => JoinType::FullOuter,
827                    Method::NaturalJoin => JoinType::Natural,
828                    other => return Err(Error::Unsupported(format!("Unsupported join method: {}", other.as_str()))),
829                };
830                let is_cross = matches!(join_type, JoinType::Cross | JoinType::Natural);
831                let table = if join.alias().is_empty() { join.attribute() } else { join.alias() }.to_owned();
832                for hook in self.core.join_filter_hooks.clone() {
833                    let Some(result) = hook.filter_join(&table, join_type)? else {
834                        continue;
835                    };
836                    let placement = match self.step(
837                        Step::ResolveJoinFilterPlacement,
838                        &[Arg::Placement(result.placement), Arg::Bool(is_cross)],
839                    )? {
840                        crate::builder::Ret::Placement(placement) => placement,
841                        _ => result.placement,
842                    };
843                    if placement == Placement::On {
844                        sql.push_str(" AND ");
845                        sql.push_str(&result.condition.expression);
846                        self.add_bindings(result.condition.bindings);
847                    } else {
848                        join_filter_where.push(result.condition);
849                    }
850                }
851                parts.push(sql);
852            }
853        }
854        for lateral in self.core.lateral_joins.clone() {
855            let mut subquery = lateral.subquery;
856            let result = subquery.build()?;
857            self.add_bindings(result.bindings);
858            let keyword = if lateral.join_type == JoinType::Left { "LEFT JOIN" } else { "JOIN" };
859            parts.push(format!("{keyword} LATERAL ({}) AS {} ON true", result.query, self.quote(&lateral.alias)?));
860        }
861        Ok(parts.join(" "))
862    }
863
864    fn build_where_clause(&mut self, grouped: &ParsedQuery, join_filter_where: Vec<Condition>) -> Result<String> {
865        let mut clauses = Vec::new();
866        for filter in &grouped.filters {
867            clauses.push(self.step_string(Step::CompileFilter, &[Arg::Query(filter)])?);
868        }
869        let table = if self.core.alias.is_empty() { self.core.table.clone() } else { self.core.alias.clone() };
870        for hook in self.core.filter_hooks.clone() {
871            let condition = hook.filter(&table)?;
872            clauses.push(condition.expression);
873            self.add_bindings(condition.bindings);
874        }
875        for condition in join_filter_where {
876            clauses.push(condition.expression);
877            self.add_bindings(condition.bindings);
878        }
879        for sub in self.core.where_in_subqueries.clone() {
880            let mut subquery = sub.subquery;
881            let result = subquery.build()?;
882            let prefix = if sub.not { "NOT IN" } else { "IN" };
883            clauses.push(format!("{} {prefix} ({})", self.resolve_and_wrap(&sub.column)?, result.query));
884            self.add_bindings(result.bindings);
885        }
886        for sub in self.core.exists_subqueries.clone() {
887            let mut subquery = sub.subquery;
888            let result = subquery.build()?;
889            let prefix = if sub.not { "NOT EXISTS" } else { "EXISTS" };
890            clauses.push(format!("{prefix} ({})", result.query));
891            self.add_bindings(result.bindings);
892        }
893        if grouped.cursor.is_some() && grouped.cursor_direction.is_some() {
894            let cursor = Query::cursor_queries(&self.core.pending).first().map(|q| (*q).clone());
895            if let Some(cursor) = cursor {
896                let sql = self.step_string(Step::CompileCursor, &[Arg::Query(&cursor)])?;
897                if !sql.is_empty() {
898                    clauses.push(sql);
899                }
900            }
901        }
902        for raw in self.core.raw_wheres.clone() {
903            clauses.push(self.step_string(Step::Enclose, &[Arg::Str(&raw.expression)])?);
904            self.add_bindings(raw.bindings);
905        }
906        for predicate in self.core.column_predicates.clone() {
907            clauses.push(format!(
908                "{} {} {}",
909                self.resolve_and_wrap(&predicate.left)?,
910                predicate.operator,
911                self.resolve_and_wrap(&predicate.right)?
912            ));
913        }
914        if clauses.is_empty() {
915            return Ok(String::new());
916        }
917        Ok(format!("WHERE {}", clauses.join(" AND ")))
918    }
919
920    fn build_group_by_clause(&mut self, grouped: &ParsedQuery) -> Result<String> {
921        const COLUMN: Param<'static> =
922            Param::method("Utopia\\Query\\Builder::resolveAndWrap", 1, "attribute", "Builder.php", 776);
923        let mut parts = Vec::new();
924        for column in &grouped.group_by {
925            parts.push(self.resolve_and_wrap(&COLUMN.string(column)?)?);
926        }
927        let function = time_bucket_function::<D>();
928        for bucket in &grouped.time_buckets {
929            let interval = Param::method(function, 2, "interval", "Builder.php", 781).string(&bucket.interval)?;
930            parts.push(
931                self.step_string(Step::CompileGroupByTimeBucket, &[Arg::Str(&bucket.attribute), Arg::Str(&interval)])?,
932            );
933        }
934        for raw in self.core.raw_groups.clone() {
935            parts.push(raw.expression);
936            self.add_bindings(raw.bindings);
937        }
938        if parts.is_empty() {
939            return Ok(String::new());
940        }
941        Ok(format!("GROUP BY {}", parts.join(", ")))
942    }
943
944    fn build_having_clause(&mut self, grouped: &ParsedQuery) -> Result<String> {
945        let alias_to_expression = self.build_aggregation_alias_map(grouped)?;
946        let mut clauses = Vec::new();
947        for having in &grouped.having {
948            for value in having.values().values() {
949                let sub = query_value(value, "compileFilter")?;
950                match alias_to_expression.iter().find(|(alias, _)| alias == sub.attribute()) {
951                    Some((_, expression)) => clauses.push(
952                        self.step_string(Step::CompileHavingCondition, &[Arg::Query(sub), Arg::Str(expression)])?,
953                    ),
954                    None => clauses.push(self.step_string(Step::CompileFilter, &[Arg::Query(sub)])?),
955                }
956            }
957        }
958        for raw in self.core.raw_havings.clone() {
959            clauses.push(self.step_string(Step::Enclose, &[Arg::Str(&raw.expression)])?);
960            self.add_bindings(raw.bindings);
961        }
962        if clauses.is_empty() {
963            return Ok(String::new());
964        }
965        Ok(format!("HAVING {}", clauses.join(" AND ")))
966    }
967
968    fn build_aggregation_alias_map(&mut self, grouped: &ParsedQuery) -> Result<Vec<(String, String)>> {
969        let mut map: Vec<(String, String)> = Vec::new();
970        for aggregate in &grouped.aggregations {
971            let alias = aggregate.alias();
972            if alias.is_empty() {
973                continue;
974            }
975            let attribute = aggregate.attribute();
976            let column = if attribute == "*" || attribute.is_empty() {
977                "*".to_owned()
978            } else if is_numeric(&value::string(attribute)) {
979                attribute.to_owned()
980            } else {
981                self.resolve_and_wrap(attribute)?
982            };
983            let expression = if aggregate.method() == Method::CountDistinct {
984                format!("COUNT(DISTINCT {column})")
985            } else {
986                let function = aggregate.method().sql_function().unwrap_or(aggregate.method().as_str());
987                format!("{function}({column})")
988            };
989            match map.iter_mut().find(|(a, _)| a == alias) {
990                Some(entry) => entry.1 = expression,
991                None => map.push((alias.to_owned(), expression)),
992            }
993        }
994        Ok(map)
995    }
996
997    fn build_window_clause(&mut self) -> Result<String> {
998        if self.core.window_definitions.is_empty() {
999            return Ok(String::new());
1000        }
1001        let mut parts = Vec::new();
1002        for definition in self.core.window_definitions.clone() {
1003            let mut over = Vec::new();
1004            if let Some(partition) = definition.partition_by.as_ref().filter(|p| !p.is_empty()) {
1005                let columns = partition.iter().map(|c| self.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
1006                over.push(format!("PARTITION BY {}", columns.join(", ")));
1007            }
1008            if let Some(order) = definition.order_by.as_ref().filter(|o| !o.is_empty()) {
1009                over.push(format!("ORDER BY {}", self.compile_order_by_list(order)?));
1010            }
1011            if let Some(frame) = &definition.frame {
1012                over.push(frame.to_sql());
1013            }
1014            parts.push(format!("{} AS ({})", self.quote(&definition.name)?, over.join(" ")));
1015        }
1016        Ok(format!("WINDOW {}", parts.join(", ")))
1017    }
1018
1019    fn build_order_by_clause(&mut self) -> Result<String> {
1020        let mut clauses = Vec::new();
1021        let vector = match self.step(Step::CompileVectorOrderExpression, &[])? {
1022            crate::builder::Ret::Condition(vector) => vector,
1023            _ => None,
1024        };
1025        if let Some(vector) = vector {
1026            clauses.push(vector.expression);
1027            self.add_bindings(vector.bindings);
1028        }
1029        for raw in self.core.raw_orders.clone() {
1030            clauses.push(raw.expression);
1031            self.add_bindings(raw.bindings);
1032        }
1033        let orders: Vec<Query> =
1034            Query::by_type(&self.core.pending, &[Method::OrderAsc, Method::OrderDesc, Method::OrderRandom])
1035                .into_iter()
1036                .cloned()
1037                .collect();
1038        for order in &orders {
1039            clauses.push(self.step_string(Step::CompileOrder, &[Arg::Query(order)])?);
1040        }
1041        if clauses.is_empty() {
1042            return Ok(String::new());
1043        }
1044        Ok(format!("ORDER BY {}", clauses.join(", ")))
1045    }
1046
1047    fn build_limit_clause(&mut self, grouped: &ParsedQuery) -> Result<String> {
1048        let mut parts = Vec::new();
1049        if let Some(limit) = grouped.limit {
1050            parts.push("LIMIT ?");
1051            self.add_binding(Value::Int(limit), None);
1052        }
1053        if self.step_bool(Step::ShouldEmitOffset, &[Arg::Int(grouped.offset), Arg::Int(grouped.limit)])? {
1054            parts.push("OFFSET ?");
1055            self.add_binding(grouped.offset.map(Value::Int).unwrap_or(Value::Null), None);
1056        }
1057        if let Some(count) = self.core.fetch_count {
1058            self.add_binding(Value::Int(count), None);
1059            parts.push(if self.core.fetch_with_ties {
1060                "FETCH FIRST ? ROWS WITH TIES"
1061            } else {
1062                "FETCH FIRST ? ROWS ONLY"
1063            });
1064        }
1065        Ok(parts.join(" "))
1066    }
1067
1068    fn build_locking_clause(&mut self) -> Result<String> {
1069        let Some(mode) = self.core.lock_mode else {
1070            return Ok(String::new());
1071        };
1072        let mut sql = mode.to_sql().to_owned();
1073        if let Some(table) = self.core.lock_of_table.clone() {
1074            sql.push_str(" OF ");
1075            sql.push_str(&self.quote(&table)?);
1076        }
1077        Ok(sql)
1078    }
1079
1080    fn build_union_suffix(&mut self) -> Result<String> {
1081        let mut suffix = String::new();
1082        for union in self.core.unions.clone() {
1083            suffix.push(' ');
1084            suffix.push_str(union.union_type.as_str());
1085            suffix.push(' ');
1086            suffix.push_str(&self.step_string(Step::WrapUnionMember, &[Arg::Str(&union.query)])?);
1087            self.add_bindings(union.bindings);
1088        }
1089        Ok(suffix)
1090    }
1091
1092    // ----- writes ---------------------------------------------------------
1093
1094    /// `INSERT INTO table (columns) VALUES (...), ...` and its bindings.
1095    pub(crate) fn base_compile_insert_body(&mut self) -> Result<(String, Vec<Value>)> {
1096        self.validate_table()?;
1097        self.validate_rows("insert")?;
1098        let columns = self.validate_and_get_columns()?;
1099        let wrapped = columns.iter().map(|c| self.resolve_and_wrap(&key_string(c))).collect::<Result<Vec<_>>>()?;
1100        let mut bindings = Vec::new();
1101        let mut rows = Vec::with_capacity(self.core.rows.len());
1102        for row in &self.core.rows {
1103            let mut placeholders = Vec::with_capacity(columns.len());
1104            for column in &columns {
1105                bindings.push(row_value(row, column));
1106                match self.core.insert_column_expressions.get(&key_string(column)) {
1107                    Some(expression) => {
1108                        placeholders.push(expression.clone());
1109                        if let Some(extra) = self.core.insert_column_expression_bindings.get(&key_string(column)) {
1110                            bindings.extend(extra.iter().cloned());
1111                        }
1112                    }
1113                    None => placeholders.push("?".to_owned()),
1114                }
1115            }
1116            rows.push(format!("({})", placeholders.join(", ")));
1117        }
1118        let mut table = self.quote(&self.core.table.clone())?;
1119        if !self.core.insert_alias.is_empty() {
1120            table.push_str(" AS ");
1121            table.push_str(&self.quote(&self.core.insert_alias.clone())?);
1122        }
1123        Ok((format!("INSERT INTO {table} ({}) VALUES {}", wrapped.join(", "), rows.join(", ")), bindings))
1124    }
1125
1126    /// The `column = ?` assignments of an `UPDATE`, binding their values.
1127    ///
1128    /// PHP: `compileAssignments()`.
1129    pub(crate) fn base_compile_assignments(&mut self) -> Result<Vec<String>> {
1130        let mut assignments = Vec::new();
1131        if let Some(row) = self.core.rows.first().cloned() {
1132            for (column, value) in row.iter() {
1133                assignments.push(format!("{} = ?", self.resolve_and_wrap(&key_ref_string(column))?));
1134                self.add_binding(value.clone(), None);
1135            }
1136        }
1137        for (column, expression) in self.core.raw_sets.0.clone() {
1138            assignments.push(format!("{} = {expression}", self.resolve_and_wrap(&column)?));
1139            if let Some(bindings) = self.core.raw_set_bindings.get(&column).cloned() {
1140                self.add_bindings(bindings);
1141            }
1142        }
1143        for (column, case) in self.core.case_sets.0.clone() {
1144            let wrapped = self.resolve_and_wrap(&column)?;
1145            assignments.push(format!("{wrapped} = {}", self.compile_case(&case)?));
1146        }
1147        Ok(assignments)
1148    }
1149
1150    /// The `WHERE` of updates and deletes.
1151    pub(crate) fn base_compile_where_clauses(
1152        &mut self,
1153        parts: &mut Vec<String>,
1154        grouped: Option<&ParsedQuery>,
1155    ) -> Result<()> {
1156        let owned;
1157        let grouped = match grouped {
1158            Some(g) => g,
1159            None => {
1160                owned = Query::group_by_type(&self.core.pending);
1161                &owned
1162            }
1163        };
1164        let mut clauses = Vec::new();
1165        for filter in &grouped.filters {
1166            clauses.push(self.step_string(Step::CompileFilter, &[Arg::Query(filter)])?);
1167        }
1168        let table = if self.core.alias.is_empty() { self.core.table.clone() } else { self.core.alias.clone() };
1169        for hook in self.core.filter_hooks.clone() {
1170            let condition = hook.filter(&table)?;
1171            clauses.push(condition.expression);
1172            self.add_bindings(condition.bindings);
1173        }
1174        for sub in self.core.where_in_subqueries.clone() {
1175            let mut subquery = sub.subquery;
1176            let result = subquery.build()?;
1177            let prefix = if sub.not { "NOT IN" } else { "IN" };
1178            clauses.push(format!("{} {prefix} ({})", self.resolve_and_wrap(&sub.column)?, result.query));
1179            self.add_bindings(result.bindings);
1180        }
1181        for sub in self.core.exists_subqueries.clone() {
1182            let mut subquery = sub.subquery;
1183            let result = subquery.build()?;
1184            let prefix = if sub.not { "NOT EXISTS" } else { "EXISTS" };
1185            clauses.push(format!("{prefix} ({})", result.query));
1186            self.add_bindings(result.bindings);
1187        }
1188        for raw in self.core.raw_wheres.clone() {
1189            clauses.push(self.step_string(Step::Enclose, &[Arg::Str(&raw.expression)])?);
1190            self.add_bindings(raw.bindings);
1191        }
1192        for predicate in self.core.column_predicates.clone() {
1193            clauses.push(format!(
1194                "{} {} {}",
1195                self.resolve_and_wrap(&predicate.left)?,
1196                predicate.operator,
1197                self.resolve_and_wrap(&predicate.right)?
1198            ));
1199        }
1200        if !clauses.is_empty() {
1201            parts.push(format!("WHERE {}", clauses.join(" AND ")));
1202        }
1203        Ok(())
1204    }
1205
1206    /// The `ORDER BY` and `LIMIT` of updates and deletes.
1207    pub(crate) fn base_compile_order_and_limit(
1208        &mut self,
1209        parts: &mut Vec<String>,
1210        grouped: Option<&ParsedQuery>,
1211    ) -> Result<()> {
1212        let owned;
1213        let grouped = match grouped {
1214            Some(g) => g,
1215            None => {
1216                owned = Query::group_by_type(&self.core.pending);
1217                &owned
1218            }
1219        };
1220        let mut clauses = Vec::new();
1221        let orders: Vec<Query> =
1222            Query::by_type(&self.core.pending, &[Method::OrderAsc, Method::OrderDesc, Method::OrderRandom])
1223                .into_iter()
1224                .cloned()
1225                .collect();
1226        for order in &orders {
1227            clauses.push(self.step_string(Step::CompileOrder, &[Arg::Query(order)])?);
1228        }
1229        for raw in self.core.raw_orders.clone() {
1230            clauses.push(raw.expression);
1231            self.add_bindings(raw.bindings);
1232        }
1233        if !clauses.is_empty() {
1234            parts.push(format!("ORDER BY {}", clauses.join(", ")));
1235        }
1236        if let Some(limit) = grouped.limit {
1237            parts.push("LIMIT ?".to_owned());
1238            self.add_binding(Value::Int(limit), None);
1239        }
1240        Ok(())
1241    }
1242
1243    pub(crate) fn base_insert(&mut self) -> Result<Statement> {
1244        self.core.bindings.clear();
1245        let (sql, bindings) = self.compile_insert_body()?;
1246        self.add_bindings(bindings);
1247        Ok(self.statement(sql))
1248    }
1249
1250    pub(crate) fn base_insert_default_values(&mut self) -> Result<Statement> {
1251        self.core.bindings.clear();
1252        self.validate_table()?;
1253        let sql = format!("INSERT INTO {} DEFAULT VALUES", self.quote(&self.core.table.clone())?);
1254        Ok(self.statement(sql))
1255    }
1256
1257    pub(crate) fn base_insert_select(&mut self) -> Result<Statement> {
1258        self.core.bindings.clear();
1259        self.validate_table()?;
1260        let Some(source) = self.core.insert_select_source.clone() else {
1261            return Err(Error::Validation(
1262                "No SELECT source specified. Call fromSelect() before insertSelect().".into(),
1263            ));
1264        };
1265        if self.core.insert_select_columns.is_empty() {
1266            return Err(Error::Validation(
1267                "No columns specified. Call fromSelect() with columns before insertSelect().".into(),
1268            ));
1269        }
1270        let columns = self.core.insert_select_columns.clone();
1271        let wrapped = columns.iter().map(|c| self.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
1272        let mut source = source;
1273        let result = source.build()?;
1274        let sql =
1275            format!("INSERT INTO {} ({}) {}", self.quote(&self.core.table.clone())?, wrapped.join(", "), result.query);
1276        self.add_bindings(result.bindings);
1277        Ok(self.statement(sql))
1278    }
1279
1280    pub(crate) fn base_update(&mut self) -> Result<Statement> {
1281        self.core.bindings.clear();
1282        self.validate_table()?;
1283        let assignments = self.compile_assignments()?;
1284        if assignments.is_empty() {
1285            return Err(Error::Validation("No assignments for UPDATE. Call set() or setRaw() before update().".into()));
1286        }
1287        let grouped = Query::group_by_type(&self.core.pending);
1288        let mut parts =
1289            vec![format!("UPDATE {} SET {}", self.quote(&self.core.table.clone())?, assignments.join(", "))];
1290        self.compile_where_clauses(&mut parts, Some(&grouped))?;
1291        self.compile_order_and_limit(&mut parts, Some(&grouped))?;
1292        Ok(self.statement(parts.join(" ")))
1293    }
1294
1295    pub(crate) fn base_delete(&mut self) -> Result<Statement> {
1296        self.core.bindings.clear();
1297        self.validate_table()?;
1298        let grouped = Query::group_by_type(&self.core.pending);
1299        let mut parts = vec![format!("DELETE FROM {}", self.quote(&self.core.table.clone())?)];
1300        self.compile_where_clauses(&mut parts, Some(&grouped))?;
1301        self.compile_order_and_limit(&mut parts, Some(&grouped))?;
1302        Ok(self.statement(parts.join(" ")))
1303    }
1304
1305    pub(crate) fn base_explain(&mut self, analyze: bool) -> Result<Statement> {
1306        let result = self.built()?;
1307        let prefix = if analyze { "EXPLAIN ANALYZE " } else { "EXPLAIN " };
1308        Ok(Statement::with_parts(
1309            format!("{prefix}{}", result.query),
1310            result.bindings,
1311            true,
1312            self.core.executor.clone(),
1313            None,
1314        ))
1315    }
1316
1317    pub(crate) fn base_add_hook(&mut self, hook: Hook) {
1318        if let Some(filter) = hook.filter {
1319            self.core.filter_hooks.push(filter);
1320        }
1321        if let Some(attribute) = hook.attribute {
1322            self.core.attribute_hooks.push(attribute);
1323        }
1324        if let Some(join_filter) = hook.join_filter {
1325            self.core.join_filter_hooks.push(join_filter);
1326        }
1327    }
1328
1329    /// The SQL dialects' `ON CONFLICT` / `ON DUPLICATE KEY UPDATE` clause.
1330    pub(crate) fn compile_conflict_clause(
1331        &mut self,
1332        header: impl FnOnce(&mut Self) -> Result<String>,
1333        assignment: impl Fn(&mut Self, &str) -> Result<String>,
1334    ) -> Result<String> {
1335        let mut updates = Vec::new();
1336        for column in self.core.conflict_update_columns.clone() {
1337            let wrapped = self.resolve_and_wrap(&column)?;
1338            match self.core.conflict_raw_sets.get(&column).cloned() {
1339                Some(expression) => {
1340                    updates.push(format!("{wrapped} = {expression}"));
1341                    if let Some(bindings) = self.core.conflict_raw_set_bindings.get(&column).cloned() {
1342                        self.add_bindings(bindings);
1343                    }
1344                }
1345                None => {
1346                    let assigned = assignment(self, &wrapped)?;
1347                    updates.push(format!("{wrapped} = {assigned}"));
1348                }
1349            }
1350        }
1351        // The header last, as PHP writes it.
1352        let header = header(self)?;
1353        Ok(format!("{header} {}", updates.join(", ")))
1354    }
1355
1356    /// `INSERT ... VALUES ... <conflict clause>` (the shared upsert).
1357    pub(crate) fn compile_upsert(&mut self, conflict: impl FnOnce(&mut Self) -> Result<String>) -> Result<Statement> {
1358        self.core.bindings.clear();
1359        self.validate_table()?;
1360        self.validate_rows("upsert")?;
1361        let columns = self.validate_and_get_columns()?;
1362        if self.core.conflict_keys.is_empty() {
1363            return Err(Error::Validation("No conflict keys specified. Call onConflict() before upsert().".into()));
1364        }
1365        if self.core.conflict_update_columns.is_empty() {
1366            return Err(Error::Validation(
1367                "No conflict update columns specified. Call onConflict() with update columns before upsert().".into(),
1368            ));
1369        }
1370        for column in &self.core.conflict_update_columns {
1371            if !columns.iter().any(|c| matches!(c, ArrayKey::Str(s) if s.as_bytes() == column.as_bytes())) {
1372                return Err(Error::Validation(format!(
1373                    "Conflict update column '{column}' is not present in the row data."
1374                )));
1375            }
1376        }
1377        let wrapped = columns.iter().map(|c| self.resolve_and_wrap(&key_string(c))).collect::<Result<Vec<_>>>()?;
1378        let mut rows = Vec::new();
1379        for row in self.core.rows.clone() {
1380            let mut placeholders = Vec::with_capacity(columns.len());
1381            for column in &columns {
1382                self.add_binding(row_value(&row, column), None);
1383                match self.core.insert_column_expressions.get(&key_string(column)).cloned() {
1384                    Some(expression) => {
1385                        placeholders.push(expression);
1386                        if let Some(extra) =
1387                            self.core.insert_column_expression_bindings.get(&key_string(column)).cloned()
1388                        {
1389                            self.add_bindings(extra);
1390                        }
1391                    }
1392                    None => placeholders.push("?".to_owned()),
1393                }
1394            }
1395            rows.push(format!("({})", placeholders.join(", ")));
1396        }
1397        let mut table = self.quote(&self.core.table.clone())?;
1398        if !self.core.insert_alias.is_empty() {
1399            table.push_str(" AS ");
1400            table.push_str(&self.quote(&self.core.insert_alias.clone())?);
1401        }
1402        let mut sql = format!("INSERT INTO {table} ({}) VALUES {}", wrapped.join(", "), rows.join(", "));
1403        sql.push(' ');
1404        sql.push_str(&conflict(self)?);
1405        Ok(self.statement(sql))
1406    }
1407
1408    /// `INSERT ... SELECT ... <conflict clause>` (the shared upsertSelect).
1409    pub(crate) fn compile_upsert_select(
1410        &mut self,
1411        conflict: impl FnOnce(&mut Self) -> Result<String>,
1412    ) -> Result<Statement> {
1413        self.core.bindings.clear();
1414        self.validate_table()?;
1415        let Some(source) = self.core.insert_select_source.clone() else {
1416            return Err(Error::Validation(
1417                "No SELECT source specified. Call fromSelect() before upsertSelect().".into(),
1418            ));
1419        };
1420        if self.core.insert_select_columns.is_empty() {
1421            return Err(Error::Validation(
1422                "No columns specified. Call fromSelect() with columns before upsertSelect().".into(),
1423            ));
1424        }
1425        if self.core.conflict_keys.is_empty() {
1426            return Err(Error::Validation(
1427                "No conflict keys specified. Call onConflict() before upsertSelect().".into(),
1428            ));
1429        }
1430        if self.core.conflict_update_columns.is_empty() {
1431            return Err(Error::Validation(
1432                "No conflict update columns specified. Call onConflict() with update columns before upsertSelect()."
1433                    .into(),
1434            ));
1435        }
1436        let columns = self.core.insert_select_columns.clone();
1437        let wrapped = columns.iter().map(|c| self.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
1438        let mut source = source;
1439        let result = source.build()?;
1440        let mut sql =
1441            format!("INSERT INTO {} ({}) {}", self.quote(&self.core.table.clone())?, wrapped.join(", "), result.query);
1442        self.add_bindings(result.bindings);
1443        sql.push(' ');
1444        sql.push_str(&conflict(self)?);
1445        Ok(self.statement(sql))
1446    }
1447
1448    /// Appends ` RETURNING columns` (PostgreSQL, MariaDB).
1449    pub(crate) fn base_append_returning(&mut self, result: Statement) -> Result<Statement> {
1450        if self.core.returning.is_empty() {
1451            return Ok(result);
1452        }
1453        let mut columns = Vec::with_capacity(self.core.returning.len());
1454        for column in self.core.returning.clone() {
1455            columns.push(if column == "*" { "*".to_owned() } else { self.resolve_and_wrap(&column)? });
1456        }
1457        Ok(Statement::with_parts(
1458            format!("{} RETURNING {}", result.query, columns.join(", ")),
1459            result.bindings,
1460            false,
1461            self.core.executor.clone(),
1462            None,
1463        ))
1464    }
1465
1466    // ----- compile ----------------------------------------------------------
1467
1468    /// The SQL of a `CASE` expression, binding its values.
1469    ///
1470    /// PHP: `compileCase()`.
1471    pub(crate) fn base_compile_case(&mut self, case: &CaseExpression) -> Result<String> {
1472        if case.whens().is_empty() {
1473            return Err(Error::Validation("CASE expression requires at least one WHEN clause.".into()));
1474        }
1475        let mut sql = "CASE".to_owned();
1476        for when in case.whens() {
1477            let condition = self.compile_when_condition(when)?;
1478            sql.push_str(" WHEN ");
1479            sql.push_str(&condition);
1480            sql.push_str(" THEN ?");
1481            self.add_binding(when.then.clone(), None);
1482        }
1483        if case.has_else() {
1484            sql.push_str(" ELSE ?");
1485            self.add_binding(case.else_value().clone(), None);
1486        }
1487        sql.push_str(" END");
1488        if !case.get_alias().is_empty() {
1489            sql.push_str(" AS ");
1490            sql.push_str(&self.quote(case.get_alias())?);
1491        }
1492        Ok(sql)
1493    }
1494
1495    fn compile_when_condition(&mut self, when: &WhenClause) -> Result<String> {
1496        match when.kind {
1497            CaseKind::Comparison => {
1498                let (Some(column), Some(operator)) = (&when.column, when.operator) else {
1499                    return Err(Error::Validation("Comparison WHEN clause requires column and operator.".into()));
1500                };
1501                self.add_binding(when.value.clone(), None);
1502                Ok(format!("{} {} ?", self.quote(column)?, operator.sql_operator()))
1503            }
1504            CaseKind::Null => {
1505                let column = when
1506                    .column
1507                    .as_ref()
1508                    .ok_or_else(|| Error::Validation("Null WHEN clause requires column.".into()))?;
1509                Ok(format!("{} IS NULL", self.quote(column)?))
1510            }
1511            CaseKind::NotNull => {
1512                let column = when
1513                    .column
1514                    .as_ref()
1515                    .ok_or_else(|| Error::Validation("NotNull WHEN clause requires column.".into()))?;
1516                Ok(format!("{} IS NOT NULL", self.quote(column)?))
1517            }
1518            CaseKind::In => {
1519                let column =
1520                    when.column.as_ref().ok_or_else(|| Error::Validation("In WHEN clause requires column.".into()))?;
1521                if when.values.is_empty() {
1522                    return Err(Error::Validation("In WHEN clause requires at least one value.".into()));
1523                }
1524                let placeholders = vec!["?"; when.values.len()].join(", ");
1525                for value in &when.values {
1526                    self.add_binding(value.clone(), None);
1527                }
1528                Ok(format!("{} IN ({placeholders})", self.quote(column)?))
1529            }
1530            CaseKind::Raw => {
1531                let condition = when
1532                    .raw_condition
1533                    .clone()
1534                    .ok_or_else(|| Error::Validation("Raw WHEN clause requires condition.".into()))?;
1535                for binding in &when.raw_bindings {
1536                    self.add_binding(binding.clone(), None);
1537                }
1538                Ok(condition)
1539            }
1540        }
1541    }
1542
1543    /// PHP's base `compileFilter()`.
1544    pub(crate) fn base_compile_filter(&mut self, query: &Query) -> Result<String> {
1545        let method = query.method();
1546        let raw = query.attribute();
1547        let attribute = self.resolve_and_wrap(raw)?;
1548        let values = query.values();
1549        let column = if raw.is_empty() { None } else { Some(raw) };
1550        use Method::*;
1551        match method {
1552            Equal => self.compile_in(&attribute, values, column),
1553            NotEqual => self.compile_not_in(&attribute, values, column),
1554            LessThan => self.compile_comparison(&attribute, "<", values, column),
1555            LessThanEqual => self.compile_comparison(&attribute, "<=", values, column),
1556            GreaterThan => self.compile_comparison(&attribute, ">", values, column),
1557            GreaterThanEqual => self.compile_comparison(&attribute, ">=", values, column),
1558            Between => Ok(self.compile_between(&attribute, values, false, column)),
1559            NotBetween => Ok(self.compile_between(&attribute, values, true, column)),
1560            StartsWith => self.step_string(
1561                Step::CompileLike,
1562                &[
1563                    Arg::Str(&attribute),
1564                    Arg::Values(values),
1565                    Arg::Str(""),
1566                    Arg::Str("%"),
1567                    Arg::Bool(false),
1568                    Arg::MaybeStr(column),
1569                ],
1570            ),
1571            NotStartsWith => self.step_string(
1572                Step::CompileLike,
1573                &[
1574                    Arg::Str(&attribute),
1575                    Arg::Values(values),
1576                    Arg::Str(""),
1577                    Arg::Str("%"),
1578                    Arg::Bool(true),
1579                    Arg::MaybeStr(column),
1580                ],
1581            ),
1582            EndsWith => self.step_string(
1583                Step::CompileLike,
1584                &[
1585                    Arg::Str(&attribute),
1586                    Arg::Values(values),
1587                    Arg::Str("%"),
1588                    Arg::Str(""),
1589                    Arg::Bool(false),
1590                    Arg::MaybeStr(column),
1591                ],
1592            ),
1593            NotEndsWith => self.step_string(
1594                Step::CompileLike,
1595                &[
1596                    Arg::Str(&attribute),
1597                    Arg::Values(values),
1598                    Arg::Str("%"),
1599                    Arg::Str(""),
1600                    Arg::Bool(true),
1601                    Arg::MaybeStr(column),
1602                ],
1603            ),
1604            Contains => self.step_string(
1605                Step::CompileContains,
1606                &[Arg::Str(&attribute), Arg::Values(values), Arg::MaybeStr(column)],
1607            ),
1608            ContainsAny => {
1609                if query.on_array() {
1610                    self.compile_in(&attribute, values, column)
1611                } else {
1612                    self.step_string(
1613                        Step::CompileContains,
1614                        &[Arg::Str(&attribute), Arg::Values(values), Arg::MaybeStr(column)],
1615                    )
1616                }
1617            }
1618            ContainsAll => self.step_string(
1619                Step::CompileContainsAll,
1620                &[Arg::Str(&attribute), Arg::Values(values), Arg::MaybeStr(column)],
1621            ),
1622            NotContains => self.step_string(
1623                Step::CompileNotContains,
1624                &[Arg::Str(&attribute), Arg::Values(values), Arg::MaybeStr(column)],
1625            ),
1626            Search | NotSearch => Err(Error::Unsupported("Full-text search is not supported by this dialect.".into())),
1627            Regex => self
1628                .step_string(Step::CompileRegex, &[Arg::Str(&attribute), Arg::Values(values), Arg::MaybeStr(column)]),
1629            IsNull => Ok(format!("{attribute} IS NULL")),
1630            IsNotNull => Ok(format!("{attribute} IS NOT NULL")),
1631            And | Having => self.compile_logical(query, "AND"),
1632            Or => self.compile_logical(query, "OR"),
1633            Exists => self.compile_exists(query, false),
1634            NotExists => self.compile_exists(query, true),
1635            Raw => self.compile_raw(query),
1636            On => self.compile_on(query),
1637            other => Err(Error::Unsupported(format!("Unsupported filter type: {}", other.as_str()))),
1638        }
1639    }
1640
1641    pub(crate) fn base_compile_having_condition(&mut self, query: &Query, expression: &str) -> Result<String> {
1642        let values = query.values();
1643        use Method::*;
1644        match query.method() {
1645            Equal => self.compile_in(expression, values, None),
1646            NotEqual => self.compile_not_in(expression, values, None),
1647            LessThan => self.compile_comparison(expression, "<", values, None),
1648            LessThanEqual => self.compile_comparison(expression, "<=", values, None),
1649            GreaterThan => self.compile_comparison(expression, ">", values, None),
1650            GreaterThanEqual => self.compile_comparison(expression, ">=", values, None),
1651            Between => Ok(self.compile_between(expression, values, false, None)),
1652            NotBetween => Ok(self.compile_between(expression, values, true, None)),
1653            IsNull => Ok(format!("{expression} IS NULL")),
1654            IsNotNull => Ok(format!("{expression} IS NOT NULL")),
1655            other => Err(Error::Unsupported(format!("Unsupported HAVING condition type: {}", other.as_str()))),
1656        }
1657    }
1658
1659    /// PHP's `compileOrder()`.
1660    pub(crate) fn compile_order_query(&mut self, query: &Query) -> Result<String> {
1661        let mut sql = match query.method() {
1662            Method::OrderAsc => format!("{} ASC", self.resolve_and_wrap(query.attribute())?),
1663            Method::OrderDesc => format!("{} DESC", self.resolve_and_wrap(query.attribute())?),
1664            Method::OrderRandom => self.step_string(Step::CompileRandom, &[])?,
1665            other => return Err(Error::Unsupported(format!("Unsupported order type: {}", other.as_str()))),
1666        };
1667        if let Some(Value::Ext(Object::Nulls(nulls))) = query.value() {
1668            sql.push_str(" NULLS ");
1669            sql.push_str(nulls.as_str());
1670        }
1671        Ok(sql)
1672    }
1673
1674    /// PHP's `compileLimit()`.
1675    pub(crate) fn compile_limit_query(&mut self, query: &Query) -> String {
1676        self.add_binding(query.value().cloned().unwrap_or(Value::Null), None);
1677        "LIMIT ?".to_owned()
1678    }
1679
1680    /// PHP's `compileOffset()`.
1681    pub(crate) fn compile_offset_query(&mut self, query: &Query) -> String {
1682        self.add_binding(query.value().cloned().unwrap_or(Value::Null), None);
1683        "OFFSET ?".to_owned()
1684    }
1685
1686    /// PHP's `compileSelect()`.
1687    pub(crate) fn compile_select_query(&mut self, query: &Query) -> Result<String> {
1688        const COLUMN: Param =
1689            Param::closure("Utopia\\Query\\Builder::{closure:Utopia\\Query\\Builder::compileSelect():1362}", 1, "col");
1690        let mut columns = Vec::with_capacity(query.values().len());
1691        for column in query.values().values() {
1692            columns.push(self.resolve_and_wrap(&COLUMN.string(column)?)?);
1693        }
1694        Ok(columns.join(", "))
1695    }
1696
1697    /// PHP's `compileCursor()`.
1698    pub(crate) fn compile_cursor_query(&mut self, query: &Query) -> Result<String> {
1699        let value = resolve_cursor_value(query.value().cloned().unwrap_or(Value::Null))?;
1700        self.add_binding(value, None);
1701        let operator = if query.method() == Method::CursorAfter { ">" } else { "<" };
1702        Ok(format!("{} {operator} ?", self.quote("_cursor")?))
1703    }
1704
1705    /// PHP's `compileAggregate()`, as the builder's [`Flavor`] compiles it.
1706    ///
1707    /// [`Flavor`]: crate::builder::Flavor
1708    pub(crate) fn compile_aggregate_query(&mut self, query: &Query) -> Result<String> {
1709        match self.flavored_aggregate(query) {
1710            Some(compiled) => compiled,
1711            None => self.base_compile_aggregate(query),
1712        }
1713    }
1714
1715    /// The base builder's `compileAggregate()`.
1716    pub(crate) fn base_compile_aggregate(&mut self, query: &Query) -> Result<String> {
1717        let method = query.method();
1718        let attribute = query.attribute();
1719        if method == Method::CountDistinct {
1720            let column = if attribute == "*" || attribute.is_empty() {
1721                "*".to_owned()
1722            } else {
1723                self.resolve_and_wrap(attribute)?
1724            };
1725            let mut sql = format!("COUNT(DISTINCT {column})");
1726            if !query.alias().is_empty() {
1727                sql.push_str(" AS ");
1728                sql.push_str(&self.quote(query.alias())?);
1729            }
1730            return Ok(sql);
1731        }
1732        let function = method
1733            .sql_function()
1734            .ok_or_else(|| Error::Validation(format!("Unknown aggregate: {}", method.as_str())))?;
1735        let column = if attribute == "*" || attribute.is_empty() {
1736            "*".to_owned()
1737        } else if is_numeric(&value::string(attribute)) {
1738            attribute.to_owned()
1739        } else {
1740            self.resolve_and_wrap(attribute)?
1741        };
1742        let mut sql = format!("{function}({column})");
1743        if !query.alias().is_empty() {
1744            sql.push_str(" AS ");
1745            sql.push_str(&self.quote(query.alias())?);
1746        }
1747        Ok(sql)
1748    }
1749
1750    /// PHP's `compileGroupBy()`.
1751    pub(crate) fn compile_group_by_query(&mut self, query: &Query) -> Result<String> {
1752        let interval_param = Param::method(time_bucket_function::<D>(), 2, "interval", "Builder.php", 1448);
1753        const COLUMN: Param =
1754            Param::closure("Utopia\\Query\\Builder::{closure:Utopia\\Query\\Builder::compileGroupBy():1454}", 1, "col");
1755        if query.method() == Method::GroupByTimeBucket {
1756            let interval = match query.value() {
1757                None | Some(Value::Null) => value::string(""),
1758                Some(v) => v.clone(),
1759            };
1760            let interval = interval_param.string(&interval)?;
1761            return self
1762                .step_string(Step::CompileGroupByTimeBucket, &[Arg::Str(query.attribute()), Arg::Str(&interval)]);
1763        }
1764        let mut columns = Vec::with_capacity(query.values().len());
1765        for column in query.values().values() {
1766            columns.push(self.resolve_and_wrap(&COLUMN.string(column)?)?);
1767        }
1768        Ok(columns.join(", "))
1769    }
1770
1771    /// PHP's `compileJoin()`.
1772    pub(crate) fn compile_join_query(&mut self, query: &Query) -> Result<String> {
1773        let keyword = join_keyword(query.method())?;
1774        let mut table = self.quote(query.attribute())?;
1775        if !query.alias().is_empty() {
1776            table.push_str(" AS ");
1777            table.push_str(&self.quote(query.alias())?);
1778        }
1779        if matches!(query.method(), Method::CrossJoin | Method::NaturalJoin) {
1780            return Ok(format!("{keyword} {table}"));
1781        }
1782        let on = self.compile_join_on(query)?;
1783        let sql = format!("{keyword} {table} ON {}", on.join(" AND "));
1784        self.collate_join(query, sql)
1785    }
1786
1787    fn compile_join_on(&mut self, query: &Query) -> Result<Vec<String>> {
1788        let on: Vec<Query> = query.join_on_queries().into_iter().cloned().collect();
1789        if on.is_empty() {
1790            return Err(Error::Validation("Join ON requires at least one condition".into()));
1791        }
1792        let mut parts = Vec::with_capacity(on.len());
1793        for condition in &on {
1794            assert_join_on_predicate(condition)?;
1795            if condition.method() == Method::On {
1796                parts.push(self.compile_on(condition)?);
1797            } else {
1798                parts.push(self.step_string(Step::CompileFilter, &[Arg::Query(condition)])?);
1799            }
1800        }
1801        Ok(parts)
1802    }
1803
1804    fn compile_on(&mut self, query: &Query) -> Result<String> {
1805        const COLUMN: Param =
1806            Param::method("Utopia\\Query\\Builder::resolveAndWrap", 1, "attribute", "Builder.php", 1547);
1807        let (left, operator, right) = on_values(query);
1808        if is_empty_string(&left) || is_empty_string(&right) {
1809            return Err(Error::Validation("Join ON requires left and right columns".into()));
1810        }
1811        let operator = match operator {
1812            Value::Str(s) if ["=", "!=", "<", ">", "<=", ">=", "<>"].iter().any(|o| o.as_bytes() == s.as_bytes()) => {
1813                String::from_utf8_lossy(s.as_bytes()).into_owned()
1814            }
1815            other => return Err(Error::Validation(format!("Invalid join operator: {}", value::concat(&other)?))),
1816        };
1817        let left = self.resolve_and_wrap(&COLUMN.string(&left)?)?;
1818        let right = self.resolve_and_wrap(&COLUMN.string(&right)?)?;
1819        Ok(format!("{left} {operator} {right}"))
1820    }
1821
1822    pub(crate) fn base_compile_join_with_builder(&mut self, query: &Query, join: &JoinBuilder) -> Result<String> {
1823        let keyword = join_keyword(query.method())?;
1824        let mut table = self.quote(query.attribute())?;
1825        if !query.alias().is_empty() {
1826            table.push_str(" AS ");
1827            table.push_str(&self.quote(query.alias())?);
1828        }
1829        let mut parts = Vec::new();
1830        for on in join.ons() {
1831            parts.push(format!(
1832                "{} {} {}",
1833                self.resolve_and_wrap(&on.left)?,
1834                on.operator,
1835                self.resolve_and_wrap(&on.right)?
1836            ));
1837        }
1838        for condition in join.wheres() {
1839            parts.push(condition.expression.clone());
1840            self.add_bindings(condition.bindings.clone());
1841        }
1842        let sql = if parts.is_empty() {
1843            format!("{keyword} {table}")
1844        } else {
1845            format!("{keyword} {table} ON {}", parts.join(" AND "))
1846        };
1847        if self.core.flavor.ids.is_none() {
1848            return Ok(sql);
1849        }
1850        let comparisons: Vec<(String, String, String)> =
1851            join.ons().iter().map(|on| (on.left.clone(), on.operator.clone(), on.right.clone())).collect();
1852        self.collate_comparisons(sql, &comparisons)
1853    }
1854
1855    /// `attribute [NOT ]LIKE ?`, naming the escape character where the dialect does.
1856    ///
1857    /// PHP: `compileLikePredicate()`, `likeEscape()`.
1858    /// `$prefix . $this->escapeLikeValue($value) . $suffix`: a subclass's own `escapeLikeValue()`
1859    /// when it has one. Without one the value keeps its bytes.
1860    pub(crate) fn like_value(&mut self, prefix: &str, value: &Value, suffix: &str) -> Result<Value> {
1861        if !self.overrides(Step::EscapeLikeValue) {
1862            return Ok(like_pattern(prefix, value, suffix, D::LIKE_ESCAPE));
1863        }
1864        let escaped = self.step_string(Step::EscapeLikeValue, &[Arg::Value(value)])?;
1865        Ok(value::string(format!("{prefix}{escaped}{suffix}")))
1866    }
1867
1868    pub(crate) fn like_predicate(&mut self, attribute: &str, not: bool) -> Result<String> {
1869        self.step_string(Step::CompileLikePredicate, &[Arg::Str(attribute), Arg::Bool(not)])
1870    }
1871
1872    /// The builder's own `compileLikePredicate()`.
1873    pub(crate) fn base_like_predicate(&mut self, attribute: &str, not: bool) -> Result<String> {
1874        // PHP asks for the keyword before the escape clause.
1875        let like = self.like_keyword()?;
1876        let escape = self.step_string(Step::LikeEscape, &[])?;
1877        Ok(format!("{attribute} {}{like} ?{escape}", if not { "NOT " } else { "" }))
1878    }
1879
1880    /// The builder's own `likeEscape()`: the `ESCAPE` clause, where the dialect declares one.
1881    pub(crate) fn base_like_escape(&self) -> Result<String> {
1882        if !D::DECLARES_LIKE_ESCAPE {
1883            return Ok(String::new());
1884        }
1885        Ok(format!(" ESCAPE {}", D::LITERAL.quote(&char::from(D::LIKE_ESCAPE).to_string())?))
1886    }
1887
1888    pub(crate) fn base_compile_like(
1889        &mut self,
1890        attribute: &str,
1891        values: &Array,
1892        prefix: &str,
1893        suffix: &str,
1894        not: bool,
1895        column: Option<&str>,
1896    ) -> Result<String> {
1897        let pattern = self.like_value(prefix, &first(values), suffix)?;
1898        self.add_binding(pattern, column);
1899        self.like_predicate(attribute, not)
1900    }
1901
1902    pub(crate) fn base_compile_contains(
1903        &mut self,
1904        attribute: &str,
1905        values: &Array,
1906        column: Option<&str>,
1907    ) -> Result<String> {
1908        if values.len() == 1 {
1909            let pattern = self.like_value("%", &first(values), "%")?;
1910            self.add_binding(pattern, column);
1911            return self.like_predicate(attribute, false);
1912        }
1913        let mut parts = Vec::with_capacity(values.len());
1914        for v in values.values() {
1915            let pattern = self.like_value("%", v, "%")?;
1916            self.add_binding(pattern, column);
1917            parts.push(self.like_predicate(attribute, false)?);
1918        }
1919        Ok(format!("({})", parts.join(" OR ")))
1920    }
1921
1922    pub(crate) fn base_compile_contains_all(
1923        &mut self,
1924        attribute: &str,
1925        values: &Array,
1926        column: Option<&str>,
1927    ) -> Result<String> {
1928        let mut parts = Vec::with_capacity(values.len());
1929        for v in values.values() {
1930            let pattern = self.like_value("%", v, "%")?;
1931            self.add_binding(pattern, column);
1932            parts.push(self.like_predicate(attribute, false)?);
1933        }
1934        Ok(format!("({})", parts.join(" AND ")))
1935    }
1936
1937    pub(crate) fn base_compile_not_contains(
1938        &mut self,
1939        attribute: &str,
1940        values: &Array,
1941        column: Option<&str>,
1942    ) -> Result<String> {
1943        if values.len() == 1 {
1944            let pattern = self.like_value("%", &first(values), "%")?;
1945            self.add_binding(pattern, column);
1946            return self.like_predicate(attribute, true);
1947        }
1948        let mut parts = Vec::with_capacity(values.len());
1949        for v in values.values() {
1950            let pattern = self.like_value("%", v, "%")?;
1951            self.add_binding(pattern, column);
1952            parts.push(self.like_predicate(attribute, true)?);
1953        }
1954        Ok(format!("({})", parts.join(" AND ")))
1955    }
1956
1957    /// `attribute IN (?, ...)`, with `IS NULL` for null values; `1 = 0` for none.
1958    pub(crate) fn compile_in(&mut self, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
1959        self.step_string(Step::CompileIn, &[Arg::Str(attribute), Arg::Values(values), Arg::MaybeStr(column)])
1960    }
1961
1962    pub(crate) fn base_compile_in(&mut self, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
1963        let collated = self.collate(attribute, column)?;
1964        let attribute = collated.as_str();
1965        if values.is_empty() {
1966            return Ok("1 = 0".into());
1967        }
1968        let has_nulls = values.values().any(|v| matches!(v, Value::Null));
1969        let non_nulls: Vec<Value> = values.values().filter(|v| !matches!(v, Value::Null)).cloned().collect();
1970        if has_nulls && non_nulls.is_empty() {
1971            return Ok(format!("{attribute} IS NULL"));
1972        }
1973        let placeholders = vec!["?"; non_nulls.len()].join(", ");
1974        for v in non_nulls {
1975            self.add_binding(v, column);
1976        }
1977        let clause = format!("{attribute} IN ({placeholders})");
1978        Ok(if has_nulls { format!("({clause} OR {attribute} IS NULL)") } else { clause })
1979    }
1980
1981    /// `attribute != ?` / `NOT IN (...)`, with `IS NOT NULL` for null values; `1 = 1` for none.
1982    pub(crate) fn compile_not_in(&mut self, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
1983        self.step_string(Step::CompileNotIn, &[Arg::Str(attribute), Arg::Values(values), Arg::MaybeStr(column)])
1984    }
1985
1986    pub(crate) fn base_compile_not_in(
1987        &mut self,
1988        attribute: &str,
1989        values: &Array,
1990        column: Option<&str>,
1991    ) -> Result<String> {
1992        let collated = self.collate(attribute, column)?;
1993        let attribute = collated.as_str();
1994        if values.is_empty() {
1995            return Ok("1 = 1".into());
1996        }
1997        let has_nulls = values.values().any(|v| matches!(v, Value::Null));
1998        let non_nulls: Vec<Value> = values.values().filter(|v| !matches!(v, Value::Null)).cloned().collect();
1999        if has_nulls && non_nulls.is_empty() {
2000            return Ok(format!("{attribute} IS NOT NULL"));
2001        }
2002        let clause = if non_nulls.len() == 1 {
2003            self.add_binding(non_nulls[0].clone(), column);
2004            format!("{attribute} != ?")
2005        } else {
2006            let placeholders = vec!["?"; non_nulls.len()].join(", ");
2007            for v in non_nulls {
2008                self.add_binding(v, column);
2009            }
2010            format!("{attribute} NOT IN ({placeholders})")
2011        };
2012        Ok(if has_nulls { format!("({clause} AND {attribute} IS NOT NULL)") } else { clause })
2013    }
2014
2015    pub(crate) fn compile_comparison(
2016        &mut self,
2017        attribute: &str,
2018        operator: &str,
2019        values: &Array,
2020        column: Option<&str>,
2021    ) -> Result<String> {
2022        self.step_string(
2023            Step::CompileComparison,
2024            &[Arg::Str(attribute), Arg::Str(operator), Arg::Values(values), Arg::MaybeStr(column)],
2025        )
2026    }
2027
2028    /// The builder's own `compileComparison()`.
2029    pub(crate) fn base_compile_comparison(
2030        &mut self,
2031        attribute: &str,
2032        operator: &str,
2033        values: &Array,
2034        column: Option<&str>,
2035    ) -> String {
2036        self.add_binding(first(values), column);
2037        format!("{attribute} {operator} ?")
2038    }
2039
2040    fn compile_between(&mut self, attribute: &str, values: &Array, not: bool, column: Option<&str>) -> String {
2041        self.add_binding(first(values), column);
2042        self.add_binding(values.get(&ArrayKey::Int(1)).cloned().unwrap_or(Value::Null), column);
2043        let keyword = if not { "NOT BETWEEN" } else { "BETWEEN" };
2044        format!("{attribute} {keyword} ? AND ?")
2045    }
2046
2047    fn compile_logical(&mut self, query: &Query, operator: &str) -> Result<String> {
2048        let mut parts = Vec::with_capacity(query.values().len());
2049        for value in query.values().values() {
2050            let sub = query_value(value, "compileFilter")?;
2051            parts.push(self.step_string(Step::CompileFilter, &[Arg::Query(sub)])?);
2052        }
2053        if parts.is_empty() {
2054            return Ok(if operator == "OR" { "1 = 0" } else { "1 = 1" }.into());
2055        }
2056        Ok(format!("({})", parts.join(&format!(" {operator} "))))
2057    }
2058
2059    fn compile_exists(&mut self, query: &Query, not: bool) -> Result<String> {
2060        let mut parts = Vec::with_capacity(query.values().len());
2061        let suffix = if not { "IS NULL" } else { "IS NOT NULL" };
2062        let param = Param::method(
2063            "Utopia\\Query\\Builder::resolveAndWrap",
2064            1,
2065            "attribute",
2066            "Builder.php",
2067            if not { 1906 } else { 1891 },
2068        );
2069        for attribute in query.values().values() {
2070            parts.push(format!("{} {suffix}", self.resolve_and_wrap(&param.string(attribute)?)?));
2071        }
2072        if parts.is_empty() {
2073            return Ok("1 = 1".into());
2074        }
2075        Ok(format!("({})", parts.join(" AND ")))
2076    }
2077
2078    fn compile_raw(&mut self, query: &Query) -> Result<String> {
2079        if query.attribute().is_empty() {
2080            return Ok("1 = 1".into());
2081        }
2082        for binding in query.values().values() {
2083            self.add_binding(binding.clone(), None);
2084        }
2085        self.step_string(Step::Enclose, &[Arg::Str(query.attribute())])
2086    }
2087}
2088
2089/// `value` in single quotes with `'` doubled, and `\` doubled when
2090/// `backslashes` is set.
2091pub(crate) fn quote_bytes(value: &[u8], backslashes: bool) -> Vec<u8> {
2092    let mut out = Vec::with_capacity(value.len() + 2);
2093    out.push(b'\'');
2094    for &b in value {
2095        if b == b'\'' || (backslashes && b == b'\\') {
2096            out.push(b);
2097        }
2098        out.push(b);
2099    }
2100    out.push(b'\'');
2101    out
2102}
2103
2104/// A raw SQL condition enclosed in parentheses. Conditions are joined with
2105/// AND, which binds tighter than OR, so a raw `a = ? OR b = ?` left bare
2106/// beside a hook's `tenant_id IN (?)` would let the OR escape the tenant and
2107/// permission conditions.
2108///
2109/// PHP: `Builder::enclose()`.
2110pub(crate) fn enclose(condition: &str) -> String {
2111    format!("({condition})")
2112}
2113
2114/// The PHP method compiling a time bucket for dialect `D` (ClickHouse
2115/// overrides the base one): what PHP's type errors name.
2116fn time_bucket_function<D: Dialect>() -> &'static str {
2117    if D::CLASS == "Utopia\\Query\\Builder\\ClickHouse" {
2118        "Utopia\\Query\\Builder\\ClickHouse::compileGroupByTimeBucket"
2119    } else {
2120        "Utopia\\Query\\Builder::compileGroupByTimeBucket"
2121    }
2122}
2123
2124/// The value at index 0 (`$values[0]`, null when absent).
2125pub(crate) fn first(values: &Array) -> Value {
2126    values.get(&ArrayKey::Int(0)).cloned().unwrap_or(Value::Null)
2127}
2128
2129/// The query of a nested value (PHP's typed parameter rejects anything else).
2130pub(crate) fn query_value<'a>(value: &'a Value, function: &str) -> Result<&'a Query> {
2131    match value {
2132        Value::Ext(Object::Query(q)) => Ok(q),
2133        other => Err(Error::Type(format!(
2134            "Utopia\\Query\\Builder::{function}(): Argument #1 ($query) must be of type Utopia\\Query\\Query, {} given",
2135            value::value_name(other)
2136        ))),
2137    }
2138}
2139
2140/// `left`, `operator` (default `=`) and `right` of an `on` query, as the
2141/// query holds them (`$values[0] ?? ''`, `$values[1] ?? '='`, `$values[2] ?? ''`).
2142pub(crate) fn on_values(query: &Query) -> (Value, Value, Value) {
2143    let at = |i: i64, default: &str| match query.values().get(&ArrayKey::Int(i)) {
2144        None | Some(Value::Null) => value::string(default),
2145        Some(v) => v.clone(),
2146    };
2147    (at(0, ""), at(1, "="), at(2, ""))
2148}
2149
2150/// `$value === ''`.
2151pub(crate) fn is_empty_string(value: &Value) -> bool {
2152    matches!(value, Value::Str(s) if s.is_empty())
2153}
2154
2155/// `left`, `operator` (default `=`) and `right` of an `on` query.
2156pub(crate) fn on_parts(query: &Query) -> (String, String, String) {
2157    let at = |i: i64, default: &str| {
2158        query
2159            .values()
2160            .get(&ArrayKey::Int(i))
2161            .filter(|v| !matches!(v, Value::Null))
2162            .map(value::to_php_string)
2163            .unwrap_or_else(|| default.to_owned())
2164    };
2165    (at(0, ""), at(1, "="), at(2, ""))
2166}
2167
2168/// Refuses join conditions other than `on`, filters and `and`/`or` of them.
2169pub(crate) fn assert_join_on_predicate(query: &Query) -> Result<()> {
2170    let method = query.method();
2171    if !method.is_join_condition() {
2172        return Err(Error::Validation(format!("Unsupported join ON condition: {}", method.as_str())));
2173    }
2174    if method != Method::And && method != Method::Or {
2175        return Ok(());
2176    }
2177    for child in query.nested() {
2178        assert_join_on_predicate(child)?;
2179    }
2180    Ok(())
2181}
2182
2183/// The SQL keyword of a join method.
2184pub(crate) fn join_keyword(method: Method) -> Result<&'static str> {
2185    Ok(match method {
2186        Method::Join => "JOIN",
2187        Method::LeftJoin => "LEFT JOIN",
2188        Method::RightJoin => "RIGHT JOIN",
2189        Method::CrossJoin => "CROSS JOIN",
2190        Method::FullOuterJoin => "FULL OUTER JOIN",
2191        Method::NaturalJoin => "NATURAL JOIN",
2192        other => return Err(Error::Unsupported(format!("Unsupported join type: {}", other.as_str()))),
2193    })
2194}
2195
2196/// The value a cursor compares: the row's `_cursor` column (a bare value is used as is).
2197pub(crate) fn resolve_cursor_value(cursor: Value) -> Result<Value> {
2198    let row = match &cursor {
2199        Value::Array(a) => Some(a.get(&ArrayKey::from("_cursor")).cloned().ok_or(()).map_err(|_| ())),
2200        Value::Ext(Object::Row { fields, .. }) => Some(fields.get(&ArrayKey::from("_cursor")).cloned().ok_or(())),
2201        Value::Object(props) => Some(props.get(&ArrayKey::Str(php_std::Str::from("_cursor"))).cloned().ok_or(())),
2202        Value::Ext(_) => Some(Err(())),
2203        _ => None,
2204    };
2205    match row {
2206        None => Ok(cursor),
2207        Some(Ok(value)) => Ok(value),
2208        Some(Err(())) => Err(Error::Validation("Cursor row has no _cursor value".into())),
2209    }
2210}
2211
2212/// PHP's `escapeLikeValue()`: the value as a string (arrays as JSON), with
2213/// `\`, `%` and `_` escaped.
2214///
2215/// PHP's `str_replace` works on bytes: a string that is not valid UTF-8
2216/// keeps its bytes (PDO pgsql then cannot quote it, and the statement fails
2217/// silently), so it is escaped byte by byte, never converted lossily.
2218pub(crate) fn escape_like_value(value: &Value, escape: u8) -> Vec<u8> {
2219    let text: Vec<u8> = match value {
2220        Value::Array(_) => value::json_encode(value, Flags::NONE).unwrap_or_default().into_bytes(),
2221        Value::Int(_) | Value::Float(_) | Value::Bool(_) => value::to_php_string(value).into_bytes(),
2222        Value::Str(s) => s.as_bytes().to_vec(),
2223        _ => Vec::new(),
2224    };
2225    let mut out = Vec::with_capacity(text.len() + 4);
2226    for &b in &text {
2227        match b {
2228            b'%' | b'_' => out.extend_from_slice(&[escape, b]),
2229            b if b == escape => out.extend_from_slice(&[escape, b]),
2230            b => out.push(b),
2231        }
2232    }
2233    out
2234}
2235
2236/// `$prefix . $this->escapeLikeValue($value) . $suffix`, as a string value.
2237pub(crate) fn like_pattern(prefix: &str, value: &Value, suffix: &str, escape: u8) -> Value {
2238    value::string([prefix.as_bytes(), &escape_like_value(value, escape), suffix.as_bytes()].concat())
2239}
2240
2241fn key_value(key: ArrayKey) -> Value {
2242    match key {
2243        ArrayKey::Int(i) => Value::Int(i),
2244        ArrayKey::Str(s) => Value::Str(s),
2245    }
2246}
2247
2248/// A column key as the string PHP's string parameters coerce it to.
2249pub(crate) fn key_string(key: &ArrayKey) -> String {
2250    match key {
2251        ArrayKey::Int(i) => i.to_string(),
2252        ArrayKey::Str(s) => String::from_utf8_lossy(s.as_bytes()).into_owned(),
2253    }
2254}
2255
2256fn key_ref_string(key: php_std::types::KeyRef<'_>) -> String {
2257    key_string(&key.to_owned())
2258}
2259
2260/// `$row[$column] ?? null`.
2261pub(crate) fn row_value(row: &Array, column: &ArrayKey) -> Value {
2262    row.get(column).cloned().unwrap_or(Value::Null)
2263}
2264
2265#[cfg(test)]
2266mod tests {
2267    use super::*;
2268
2269    // packages/query/src/Builder.php:1743 escapeLikeValue(): str_replace on
2270    // the string's bytes, so a byte that is not UTF-8 stays as it is.
2271    #[test]
2272    fn escape_like_value_keeps_bytes() {
2273        assert_eq!(escape_like_value(&value::string(b"a%_\\\xff"), b'\\'), b"a\\%\\_\\\\\xff".to_vec());
2274        assert_eq!(escape_like_value(&value::string(b"a%_\\!"), b'!'), b"a!%!_\\!!".to_vec());
2275        assert_eq!(like_pattern("%", &value::string(b"\xff"), "%", b'\\'), value::string(b"%\xff%"));
2276        assert_eq!(escape_like_value(&Value::Int(5), b'\\'), b"5".to_vec());
2277    }
2278}