Skip to main content

utopia_query/builder/
clickhouse.rs

1//! ClickHouse: [`ClickHouse`], its bulk-insert [`Format`]s and
2//! [`FormattedInsertStatement`], and the ASOF join [`AsofOperator`].
3//!
4//! ClickHouse extends the base builder directly (not the SQL dialects): it
5//! adds `PREWHERE`, `FINAL`, `SAMPLE`, `ARRAY JOIN`, `ASOF JOIN`,
6//! `LIMIT ... BY`, `WITH FILL`, `SETTINGS`, the `-If` conditional
7//! aggregates, the approximate aggregates (`quantile`, `uniq`, `topK`, ...),
8//! mutations (`ALTER TABLE ... UPDATE` / `DELETE`), `FORMAT` inserts and
9//! named, typed placeholders (`{param0:Int64}`).
10//!
11//! | PHP | Rust |
12//! |---|---|
13//! | `Builder\ClickHouse` | [`ClickHouse`] ([`ClickHouseDialect`]) |
14//! | `ClickHouse::DELETE_MODE_LIGHTWEIGHT`, `DELETE_MODE_MUTATION`, `deleteMode()` | [`DeleteMode`], [`Builder::delete_mode`] |
15//! | `Builder\ClickHouse\AsofOperator` | [`AsofOperator`] |
16//! | `Builder\ClickHouse\Format`, `Format::serialize()` | [`Format`], [`Format::serialize`] |
17//! | `Builder\ClickHouse\FormattedInsertStatement` | [`FormattedInsertStatement`] |
18//! | `bulkInsert()`, `bulkInsertSparse()`, `insertFormat()` + `insert()` | [`Builder::bulk_insert`], [`Builder::bulk_insert_sparse`], [`Builder::insert_format`] + [`Builder::formatted_insert`] |
19//! | `Feature\ClickHouse\LimitBy`, `ArrayJoins`, `AsofJoins`, `WithFill`, `ApproximateAggregates` | inherent methods of [`ClickHouse`] |
20//! | `prewhere()`, `final()`, `sample()`, `settings()` | [`Builder::prewhere`], [`Builder::final_`], [`Builder::sample`], [`Builder::settings`] |
21//! | `useNamedBindings()`, `withParamType()`, `withParamTypes()` | [`Builder::use_named_bindings`], [`Builder::with_param_type`], [`Builder::with_param_types`] |
22
23use std::collections::HashMap;
24use std::ops::Deref;
25
26use php_std::ArrayKey;
27use php_std::json::Flags;
28
29use crate::builder::core::{Builder, Dialect, first, key_string};
30use crate::builder::feature::{
31    BitwiseAggregates, ConditionalAggregates, CrossJoins, Cube, FullOuterJoins, Hints, RawSql, Rollup,
32    StringAggregates, TableSampling, Totals, is_plain_identifier,
33};
34use crate::builder::types::{Condition, Executor, Statement};
35use crate::error::{Error, Result};
36use crate::hook::Placement;
37use crate::method::backed_enum;
38use crate::query::{ParsedQuery, Query};
39use crate::value::{self, Array, Value};
40
41/// A ClickHouse builder.
42///
43/// PHP: `Utopia\Query\Builder\ClickHouse`.
44///
45/// ```
46/// use utopia_query::Query;
47/// use utopia_query::builder::ClickHouse;
48///
49/// let statement = ClickHouse::new()
50///     .from("events", "")
51///     .final_()
52///     .sample(0.1)?
53///     .prewhere([Query::equal("type", ["click"])])
54///     .filter([Query::greater_than("count", 5)])
55///     .build()?;
56/// assert_eq!(
57///     statement.query,
58///     "SELECT * FROM `events` FINAL SAMPLE 0.1 PREWHERE `type` IN (?) WHERE `count` > ?"
59/// );
60/// # Ok::<(), utopia_query::Error>(())
61/// ```
62///
63/// ```php
64/// use Utopia\Query\Builder\ClickHouse;
65/// use Utopia\Query\Query;
66///
67/// echo (new ClickHouse())
68///     ->from('events')
69///     ->final()
70///     ->sample(0.1)
71///     ->prewhere([Query::equal('type', ['click'])])
72///     ->filter([Query::greaterThan('count', 5)])
73///     ->build()->query, "\n";
74/// // SELECT * FROM `events` FINAL SAMPLE 0.1 PREWHERE `type` IN (?) WHERE `count` > ?
75/// ```
76pub type ClickHouse = Builder<ClickHouseDialect>;
77
78/// An `ARRAY JOIN` / `LEFT ARRAY JOIN` of a column.
79#[derive(Debug, Clone, PartialEq, Eq)]
80struct ArrayJoin {
81    left: bool,
82    column: String,
83    alias: String,
84}
85
86/// The ClickHouse dialect and its own state.
87#[derive(Debug, Clone, Default)]
88pub struct ClickHouseDialect {
89    prewhere: Vec<Query>,
90    final_: bool,
91    sample_fraction: Option<f64>,
92    limit_by: Option<(i64, Vec<String>)>,
93    array_joins: Vec<ArrayJoin>,
94    raw_joins: Vec<String>,
95    insert_format: Option<String>,
96    insert_format_columns: Vec<String>,
97    param_types: HashMap<String, String>,
98    named_bindings: bool,
99    delete_mode: DeleteMode,
100}
101
102/// Which `DELETE` form [`Builder::delete`] emits.
103///
104/// PHP: the `ClickHouse::DELETE_MODE_*` constants.
105#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
106pub enum DeleteMode {
107    /// `DELETE FROM t WHERE ...`: rows are masked as deleted (the default).
108    ///
109    /// PHP: `ClickHouse::DELETE_MODE_LIGHTWEIGHT` (`'lightweight'`).
110    #[default]
111    Lightweight,
112    /// `ALTER TABLE t DELETE WHERE ...`: parts are rewritten on disk.
113    ///
114    /// PHP: `ClickHouse::DELETE_MODE_MUTATION` (`'mutation'`).
115    Mutation,
116}
117
118impl DeleteMode {
119    /// The mode's name: `lightweight` or `mutation`.
120    pub const fn as_str(self) -> &'static str {
121        match self {
122            DeleteMode::Lightweight => "lightweight",
123            DeleteMode::Mutation => "mutation",
124        }
125    }
126
127    /// The mode named `mode`.
128    ///
129    /// PHP: the validation of `deleteMode()`, which throws `ValidationException`.
130    pub fn parse(mode: &str) -> Result<DeleteMode> {
131        match mode {
132            "lightweight" => Ok(DeleteMode::Lightweight),
133            "mutation" => Ok(DeleteMode::Mutation),
134            other => Err(Error::Validation(format!(
135                "Invalid ClickHouse delete mode: {other}. Allowed: lightweight, mutation"
136            ))),
137        }
138    }
139}
140
141backed_enum! {
142    /// The inequality of an `ASOF JOIN`.
143    ///
144    /// PHP: `Utopia\Query\Builder\ClickHouse\AsofOperator`.
145    pub enum AsofOperator: "Utopia\\Query\\Builder\\ClickHouse\\AsofOperator" {
146        /// `<`.
147        LessThan = "<",
148        /// `<=`.
149        LessThanEqual = "<=",
150        /// `>`.
151        GreaterThan = ">",
152        /// `>=`.
153        GreaterThanEqual = ">=",
154    }
155}
156
157backed_enum! {
158    /// A ClickHouse input format for bulk inserts.
159    ///
160    /// PHP: `Utopia\Query\Builder\ClickHouse\Format`.
161    pub enum Format: "Utopia\\Query\\Builder\\ClickHouse\\Format" {
162        /// One JSON object per line.
163        JSONEachRow = "JSONEachRow",
164        /// Tab-separated values, one row per line, `\N` for null.
165        TabSeparated = "TabSeparated",
166    }
167}
168
169impl Format {
170    /// The rows in this format, one per line. With `columns`, each row has
171    /// exactly those columns in that order (missing ones are null).
172    ///
173    /// PHP: `Format::serialize()`.
174    ///
175    /// ```
176    /// use utopia_query::builder::Format;
177    /// use utopia_query::{Array, Value};
178    ///
179    /// let mut row = Array::default();
180    /// row.set("id".into(), Value::Int(1));
181    /// row.set("note".into(), Value::Null);
182    /// assert_eq!(Format::TabSeparated.serialize(&[row.clone()], None)?, "1\t\\N");
183    /// assert_eq!(Format::JSONEachRow.serialize(&[row], None)?, r#"{"id":1,"note":null}"#);
184    /// # Ok::<(), utopia_query::Error>(())
185    /// ```
186    ///
187    /// ```php
188    /// use Utopia\Query\Builder\ClickHouse\Format;
189    ///
190    /// echo json_encode(Format::TabSeparated->serialize([['id' => 1, 'note' => null]])), "\n";
191    /// // "1\t\\N"
192    /// echo Format::JSONEachRow->serialize([['id' => 1, 'note' => null]]), "\n";
193    /// // {"id":1,"note":null}
194    /// ```
195    pub fn serialize(self, rows: &[Array], columns: Option<&[String]>) -> Result<String> {
196        let mut lines = Vec::with_capacity(rows.len());
197        for row in rows {
198            lines.push(match self {
199                Format::JSONEachRow => json_each_row_line(row, columns)?,
200                Format::TabSeparated => tab_separated_line(row, columns)?,
201            });
202        }
203        Ok(lines.join("\n"))
204    }
205}
206
207/// `$row[$column] ?? null`.
208fn column_value(row: &Array, column: &str) -> Value {
209    row.get(&ArrayKey::from(column)).cloned().unwrap_or(Value::Null)
210}
211
212fn json_each_row_line(row: &Array, columns: Option<&[String]>) -> Result<String> {
213    let object = match columns {
214        None => row.clone(),
215        Some(columns) => {
216            let mut ordered = Array::with_capacity(columns.len());
217            for column in columns {
218                ordered.set(ArrayKey::from(column.as_str()), column_value(row, column));
219            }
220            ordered
221        }
222    };
223    let flags = Flags::THROW_ON_ERROR | Flags::UNESCAPED_SLASHES | Flags::UNESCAPED_UNICODE;
224    value::json_encode(&Value::Object(object), flags)
225        .map_err(|e| Error::Json { message: e.message().to_owned(), code: e.code().code() })
226}
227
228fn tab_separated_line(row: &Array, columns: Option<&[String]>) -> Result<String> {
229    let mut values = Vec::new();
230    match columns {
231        None => {
232            for v in row.values() {
233                values.push(escape_tab_separated(v)?);
234            }
235        }
236        Some(columns) => {
237            for column in columns {
238                values.push(escape_tab_separated(&column_value(row, column))?);
239            }
240        }
241    }
242    Ok(values.join("\t"))
243}
244
245/// One TabSeparated field: `\N` for null, `1`/`0` for booleans, numbers as
246/// PHP prints them, strings with `\`, tab, newline and carriage return escaped.
247fn escape_tab_separated(value: &Value) -> Result<String> {
248    let text = match value {
249        Value::Null => return Ok("\\N".into()),
250        Value::Bool(b) => return Ok(if *b { "1" } else { "0" }.into()),
251        Value::Int(_) | Value::Float(_) => return Ok(value::to_php_string(value)),
252        Value::Str(s) => String::from_utf8_lossy(s.as_bytes()).into_owned(),
253        other => {
254            return Err(Error::Validation(format!(
255                "TabSeparated values must be scalar, null, or stringable. Received: {}",
256                other.debug_type()
257            )));
258        }
259    };
260    let mut out = String::with_capacity(text.len());
261    for c in text.chars() {
262        match c {
263            '\\' => out.push_str("\\\\"),
264            '\t' => out.push_str("\\t"),
265            '\n' => out.push_str("\\n"),
266            '\r' => out.push_str("\\r"),
267            c => out.push(c),
268        }
269    }
270    Ok(out)
271}
272
273/// An `INSERT INTO table [(columns)] FORMAT name` envelope (no bindings),
274/// with the format, the columns and, from [`Builder::bulk_insert`], the
275/// serialized rows to send with it.
276///
277/// It is a [`Statement`] (it derefs to one) with three more fields.
278///
279/// PHP: `Utopia\Query\Builder\ClickHouse\FormattedInsertStatement` (extends `Statement`).
280#[derive(Debug, Clone, PartialEq)]
281pub struct FormattedInsertStatement {
282    /// The envelope statement.
283    pub statement: Statement,
284    /// The columns, in order.
285    pub columns: Vec<String>,
286    /// The format name (`JSONEachRow`).
287    pub format: String,
288    /// The serialized rows; `None` when built by `insert()` after `insert_format()`.
289    pub body: Option<String>,
290}
291
292impl Deref for FormattedInsertStatement {
293    type Target = Statement;
294
295    /// The envelope statement.
296    fn deref(&self) -> &Statement {
297        &self.statement
298    }
299}
300
301impl FormattedInsertStatement {
302    /// The same statement run by `executor`.
303    ///
304    /// PHP: `withExecutor()`.
305    pub fn with_executor(&self, executor: Executor) -> FormattedInsertStatement {
306        FormattedInsertStatement { statement: self.statement.with_executor(executor), ..self.clone() }
307    }
308}
309
310/// `/^[A-Za-z0-9_=., ]+$/`.
311fn is_hint(hint: &str) -> bool {
312    let bytes = hint.as_bytes();
313    !bytes.is_empty()
314        && bytes.iter().all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'=' | b'.' | b',' | b' '))
315}
316
317/// `/^[a-zA-Z0-9_.]+$/`.
318fn is_setting_value(text: &str) -> bool {
319    let bytes = text.as_bytes();
320    !bytes.is_empty() && bytes.iter().all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.'))
321}
322
323/// `/^[A-Za-z][A-Za-z0-9_]*$/`.
324fn is_format_name(text: &str) -> bool {
325    let bytes = text.as_bytes();
326    bytes.first().is_some_and(u8::is_ascii_alphabetic) && bytes.iter().all(|&b| b.is_ascii_alphanumeric() || b == b'_')
327}
328
329/// `/^[A-Za-z][A-Za-z0-9_]*(?:\((?:[^()]*|\([^()]*\))*\))?$/`: a type name
330/// with an optional argument list nesting parentheses one level deep.
331fn is_clickhouse_type(text: &str) -> bool {
332    fn full(bytes: &[u8]) -> bool {
333        if !bytes.first().is_some_and(u8::is_ascii_alphabetic) {
334            return false;
335        }
336        let mut i = 1;
337        while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
338            i += 1;
339        }
340        if i == bytes.len() {
341            return true;
342        }
343        if bytes[i] != b'(' {
344            return false;
345        }
346        i += 1;
347        while i < bytes.len() {
348            match bytes[i] {
349                b')' => return i == bytes.len() - 1,
350                b'(' => {
351                    let mut j = i + 1;
352                    while j < bytes.len() && bytes[j] != b'(' && bytes[j] != b')' {
353                        j += 1;
354                    }
355                    if j == bytes.len() || bytes[j] == b'(' {
356                        return false;
357                    }
358                    i = j + 1;
359                }
360                _ => i += 1,
361            }
362        }
363        false
364    }
365    full(text.as_bytes())
366}
367
368/// The ClickHouse type of a binding without a registered type.
369fn infer_type(value: Option<&Value>) -> &'static str {
370    match value {
371        Some(Value::Int(_)) => "Int64",
372        Some(Value::Float(_)) => "Float64",
373        Some(Value::Bool(_)) => "UInt8",
374        None | Some(Value::Null) => "Nullable(String)",
375        Some(_) => "String",
376    }
377}
378
379/// Rewrites the `?` placeholders (not `??`, `?|`, `?&`) to `{paramN:Type}`
380/// and attaches the named bindings, when named bindings are on.
381/// `$this->applyNamedTypedBindings()`: a subclass's own when it has one.
382fn named(b: &mut ClickHouse, statement: Statement) -> Result<Statement> {
383    use crate::builder::{Arg, Ret, Step};
384    if !b.overrides(Step::ApplyNamedTypedBindings) {
385        return Ok(apply_named_typed_bindings(b, statement));
386    }
387    match b.step(Step::ApplyNamedTypedBindings, &[Arg::Statement(&statement)])? {
388        Ret::Statement(statement) => Ok(statement),
389        _ => Ok(statement),
390    }
391}
392
393impl ClickHouse {
394    /// `statement` with its `?` placeholders named and typed, when named bindings are on.
395    ///
396    /// PHP: `applyNamedTypedBindings()`.
397    pub fn apply_named_typed_bindings(&self, statement: Statement) -> Statement {
398        apply_named_typed_bindings(self, statement)
399    }
400}
401
402fn apply_named_typed_bindings(b: &ClickHouse, statement: Statement) -> Statement {
403    if !b.dialect.named_bindings || statement.bindings.is_empty() {
404        return statement;
405    }
406    let sql = statement.query.as_bytes();
407    let mut rewritten = Vec::with_capacity(sql.len() + statement.bindings.len() * 16);
408    let mut named = Array::with_capacity(statement.bindings.len());
409    let mut index = 0usize;
410    for (i, &byte) in sql.iter().enumerate() {
411        let placeholder =
412            byte == b'?' && (i == 0 || sql[i - 1] != b'?') && !matches!(sql.get(i + 1), Some(b'|' | b'&' | b'?'));
413        if !placeholder {
414            rewritten.push(byte);
415            continue;
416        }
417        let binding = b.core.bindings.get(index);
418        let type_name = match binding.and_then(|binding| binding.column.as_ref()) {
419            Some(column) if b.dialect.param_types.contains_key(column) => b.dialect.param_types[column].as_str(),
420            _ => infer_type(binding.map(|binding| &binding.value)),
421        };
422        let name = format!("param{index}");
423        named.set(ArrayKey::from(name.as_str()), statement.bindings.get(index).cloned().unwrap_or(Value::Null));
424        rewritten.extend_from_slice(format!("{{{name}:{type_name}}}").as_bytes());
425        index += 1;
426    }
427    Statement::with_parts(
428        String::from_utf8_lossy(&rewritten).into_owned(),
429        statement.bindings,
430        statement.read_only,
431        b.core.executor.clone(),
432        Some(named),
433    )
434}
435
436/// `function(column) [AS alias]` in the select list.
437fn select_function(b: &mut ClickHouse, expression: String, alias: &str) -> Result<()> {
438    let mut expression = expression;
439    if !alias.is_empty() {
440        expression.push_str(" AS ");
441        expression.push_str(&b.quote(alias)?);
442    }
443    b.select_raw(expression, Array::default());
444    Ok(())
445}
446
447impl Dialect for ClickHouseDialect {
448    const CLASS: &'static str = "Utopia\\Query\\Builder\\ClickHouse";
449
450    fn base_step(
451        _b: &mut Builder<Self>,
452        step: crate::builder::Step,
453        arguments: &[crate::builder::Arg<'_>],
454    ) -> Option<Result<crate::builder::Ret>> {
455        if let (crate::builder::Step::ApplyNamedTypedBindings, [crate::builder::Arg::Statement(statement)]) =
456            (step, arguments)
457        {
458            return Some(Ok(crate::builder::Ret::Statement(apply_named_typed_bindings(_b, (*statement).clone()))));
459        }
460        crate::builder::feature::aggregates_base_step::<Self>(step, arguments)
461    }
462    const LITERAL: crate::StringLiteral = crate::StringLiteral::BackslashUtf8;
463
464    fn compile_random(_b: &Builder<Self>) -> String {
465        "rand()".into()
466    }
467
468    fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
469        b.add_binding(first(values), column);
470        Ok(format!("match({attribute}, ?)"))
471    }
472
473    fn compile_like(
474        b: &mut Builder<Self>,
475        attribute: &str,
476        values: &Array,
477        prefix: &str,
478        suffix: &str,
479        not: bool,
480        column: Option<&str>,
481    ) -> Result<String> {
482        let raw = first(values);
483        let function = match (prefix, suffix) {
484            ("", "%") => Some("startsWith"),
485            ("%", "") => Some("endsWith"),
486            _ => None,
487        };
488        if let Some(function) = function {
489            b.add_binding(raw, column);
490            let not = if not { "NOT " } else { "" };
491            return Ok(format!("{not}{function}({attribute}, ?)"));
492        }
493        let pattern = b.like_value(prefix, &raw, suffix)?;
494        b.add_binding(pattern, column);
495        b.like_predicate(attribute, not)
496    }
497
498    fn compile_contains(
499        b: &mut Builder<Self>,
500        attribute: &str,
501        values: &Array,
502        column: Option<&str>,
503    ) -> Result<String> {
504        if values.len() == 1 {
505            b.add_binding(first(values), column);
506            return Ok(format!("position({attribute}, ?) > 0"));
507        }
508        let mut parts = Vec::with_capacity(values.len());
509        for v in values.values() {
510            b.add_binding(v.clone(), column);
511            parts.push(format!("position({attribute}, ?) > 0"));
512        }
513        Ok(format!("({})", parts.join(" OR ")))
514    }
515
516    fn compile_contains_all(
517        b: &mut Builder<Self>,
518        attribute: &str,
519        values: &Array,
520        column: Option<&str>,
521    ) -> Result<String> {
522        let mut parts = Vec::with_capacity(values.len());
523        for v in values.values() {
524            b.add_binding(v.clone(), column);
525            parts.push(format!("position({attribute}, ?) > 0"));
526        }
527        Ok(format!("({})", parts.join(" AND ")))
528    }
529
530    fn compile_not_contains(
531        b: &mut Builder<Self>,
532        attribute: &str,
533        values: &Array,
534        column: Option<&str>,
535    ) -> Result<String> {
536        if values.len() == 1 {
537            b.add_binding(first(values), column);
538            return Ok(format!("position({attribute}, ?) = 0"));
539        }
540        let mut parts = Vec::with_capacity(values.len());
541        for v in values.values() {
542            b.add_binding(v.clone(), column);
543            parts.push(format!("position({attribute}, ?) = 0"));
544        }
545        Ok(format!("({})", parts.join(" AND ")))
546    }
547
548    fn build_table_clause(b: &mut Builder<Self>) -> Result<String> {
549        if let Some(sub) = b.core.from_subquery.clone() {
550            let mut subquery = sub.subquery;
551            let result = subquery.build()?;
552            b.add_bindings(result.bindings);
553            return Ok(format!("FROM ({}) AS {}", result.query, b.quote(&sub.alias)?));
554        }
555        let mut sql = format!("FROM {}", b.quote(&b.core.table.clone())?);
556        if b.dialect.final_ {
557            sql.push_str(" FINAL");
558        }
559        if let Some(fraction) = b.dialect.sample_fraction {
560            // `%.10g` of a float cannot fail.
561            let formatted =
562                php_std::format::sprintf(b"%.10g", &[php_std::format::Arg::Float(fraction)]).unwrap_or_default();
563            sql.push_str(" SAMPLE ");
564            sql.push_str(&String::from_utf8_lossy(&formatted));
565        }
566        if !b.core.alias.is_empty() {
567            sql.push_str(" AS ");
568            sql.push_str(&b.quote(&b.core.alias.clone())?);
569        }
570        Ok(sql)
571    }
572
573    fn build_after_joins_clause(b: &mut Builder<Self>, _grouped: &ParsedQuery) -> Result<String> {
574        let mut parts = Vec::new();
575        if !b.dialect.array_joins.is_empty() {
576            let mut joins = Vec::with_capacity(b.dialect.array_joins.len());
577            for join in b.dialect.array_joins.clone() {
578                let keyword = if join.left { "LEFT ARRAY JOIN" } else { "ARRAY JOIN" };
579                let mut clause = format!("{keyword} {}", b.resolve_and_wrap(&join.column)?);
580                if !join.alias.is_empty() {
581                    clause.push_str(" AS ");
582                    clause.push_str(&b.quote(&join.alias)?);
583                }
584                joins.push(clause);
585            }
586            parts.push(joins.join(" "));
587        }
588        if !b.dialect.raw_joins.is_empty() {
589            parts.push(b.dialect.raw_joins.join(" "));
590        }
591        if !b.dialect.prewhere.is_empty() {
592            let mut clauses = Vec::with_capacity(b.dialect.prewhere.len());
593            for query in b.dialect.prewhere.clone() {
594                clauses.push(Self::compile_filter(b, &query)?);
595            }
596            parts.push(format!("PREWHERE {}", clauses.join(" AND ")));
597        }
598        Ok(parts.join(" "))
599    }
600
601    fn build_after_group_by_clause(b: &mut Builder<Self>) -> Result<String> {
602        Ok(b.core.group_by_modifier.clone().unwrap_or_default())
603    }
604
605    fn build_after_order_by_clause(b: &mut Builder<Self>) -> Result<String> {
606        let Some((count, columns)) = b.dialect.limit_by.clone() else {
607            return Ok(String::new());
608        };
609        let columns = columns.iter().map(|c| b.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
610        b.add_binding(Value::Int(count), None);
611        Ok(format!("LIMIT ? BY {}", columns.join(", ")))
612    }
613
614    fn build_settings_clause(b: &mut Builder<Self>) -> Result<String> {
615        if b.core.hints.is_empty() {
616            return Ok(String::new());
617        }
618        Ok(format!("SETTINGS {}", b.core.hints.join(", ")))
619    }
620
621    fn compile_group_by_time_bucket(b: &mut Builder<Self>, attribute: &str, interval: &str) -> Result<String> {
622        let function = match interval {
623            "1m" => "toStartOfMinute",
624            "5m" => "toStartOfFiveMinutes",
625            "15m" => "toStartOfFifteenMinutes",
626            "1h" => "toStartOfHour",
627            "1d" => "toStartOfDay",
628            "1w" => "toStartOfWeek",
629            "1M" => "toStartOfMonth",
630            _ => {
631                return Err(Error::Validation(format!(
632                    "Invalid groupByTimeBucket interval for ClickHouse: {interval}"
633                )));
634            }
635        };
636        Ok(format!("{function}({})", b.resolve_and_wrap(attribute)?))
637    }
638
639    fn resolve_join_filter_placement(_b: &Builder<Self>, _requested: Placement, _is_cross_join: bool) -> Placement {
640        Placement::Where
641    }
642
643    fn build(b: &mut Builder<Self>) -> Result<Statement> {
644        let result = b.base_build()?;
645        named(b, result)
646    }
647
648    fn insert(b: &mut Builder<Self>) -> Result<Statement> {
649        match b.formatted_insert()? {
650            Some(formatted) => Ok(formatted.statement),
651            None => {
652                let result = b.base_insert()?;
653                named(b, result)
654            }
655        }
656    }
657
658    fn update(b: &mut Builder<Self>) -> Result<Statement> {
659        b.core.bindings.clear();
660        b.validate_table()?;
661        let assignments = b.compile_assignments()?;
662        if assignments.is_empty() {
663            return Err(Error::Validation("No assignments for UPDATE. Call set() or setRaw() before update().".into()));
664        }
665        let mut parts = Vec::new();
666        b.compile_where_clauses(&mut parts, None)?;
667        if parts.is_empty() {
668            return Err(Error::Validation("ClickHouse UPDATE requires a WHERE clause.".into()));
669        }
670        let sql = format!(
671            "ALTER TABLE {} UPDATE {} {}",
672            b.quote(&b.core.table.clone())?,
673            assignments.join(", "),
674            parts.join(" ")
675        );
676        let statement = b.statement(sql);
677        named(b, statement)
678    }
679
680    fn delete(b: &mut Builder<Self>) -> Result<Statement> {
681        b.core.bindings.clear();
682        b.validate_table()?;
683        let mut parts = Vec::new();
684        b.compile_where_clauses(&mut parts, None)?;
685        if parts.is_empty() {
686            return Err(Error::Validation("ClickHouse DELETE requires a WHERE clause.".into()));
687        }
688        let table = b.quote(&b.core.table.clone())?;
689        let mut sql = match b.dialect.delete_mode {
690            DeleteMode::Lightweight => format!("DELETE FROM {table} {}", parts.join(" ")),
691            DeleteMode::Mutation => format!("ALTER TABLE {table} DELETE {}", parts.join(" ")),
692        };
693        let settings = b.step_string(crate::builder::Step::BuildSettingsClause, &[])?;
694        if !settings.is_empty() {
695            sql.push(' ');
696            sql.push_str(&settings);
697        }
698        let statement = b.statement(sql);
699        named(b, statement)
700    }
701
702    fn reset(b: &mut Builder<Self>) {
703        b.dialect = ClickHouseDialect::default();
704        b.core.hints.clear();
705        b.reset_group_by_modifier();
706    }
707
708    fn ast_dialect() -> crate::builder::AstDialect {
709        crate::builder::AstDialect::ClickHouse
710    }
711}
712
713impl Hints for ClickHouseDialect {
714    fn hint(b: &mut Builder<Self>, hint: &str) -> Result<()> {
715        if !is_hint(hint) {
716            return Err(Error::Validation(format!("Invalid hint: {hint}")));
717        }
718        b.core.hints.push(hint.to_owned());
719        Ok(())
720    }
721}
722
723impl ConditionalAggregates for ClickHouseDialect {
724    /// ClickHouse's `-If` combinator: `countIf(condition)`, `sumIf(column, condition)`.
725    fn aggregate_filter(
726        b: &mut Builder<Self>,
727        aggregate: &str,
728        column: Option<&str>,
729        condition: &str,
730        alias: &str,
731    ) -> Result<String> {
732        let arguments = match column {
733            None => condition.to_owned(),
734            Some(column) => format!("{}, {condition}", b.resolve_and_wrap(column)?),
735        };
736        let mut expression = format!("{}If({arguments})", aggregate.to_ascii_lowercase());
737        if !alias.is_empty() {
738            expression.push_str(" AS ");
739            expression.push_str(&b.quote(alias)?);
740        }
741        Ok(expression)
742    }
743}
744
745impl TableSampling for ClickHouseDialect {
746    /// `SAMPLE percent / 100` (the method is ignored).
747    fn tablesample(b: &mut Builder<Self>, percent: f64, _method: &str) -> Result<()> {
748        b.sample(percent / 100.0)?;
749        Ok(())
750    }
751}
752
753impl StringAggregates for ClickHouseDialect {
754    fn group_concat_expr(column: &str, _order_by: &str) -> String {
755        format!("arrayStringConcat(groupArray({column}), ?)")
756    }
757    fn json_array_agg_expr(column: &str) -> String {
758        format!("toJSONString(groupArray({column}))")
759    }
760    fn json_object_agg_expr(key: &str, value: &str) -> String {
761        format!("toJSONString(CAST((groupArray({key}), groupArray({value})) AS Map(String, String)))")
762    }
763}
764
765impl Totals for ClickHouseDialect {
766    fn with_totals(b: &mut Builder<Self>) {
767        b.core.group_by_modifier = Some("WITH TOTALS".into());
768    }
769}
770
771impl Rollup for ClickHouseDialect {
772    fn with_rollup(b: &mut Builder<Self>) {
773        b.core.group_by_modifier = Some("WITH ROLLUP".into());
774    }
775}
776
777impl Cube for ClickHouseDialect {
778    fn with_cube(b: &mut Builder<Self>) {
779        b.core.group_by_modifier = Some("WITH CUBE".into());
780    }
781}
782
783impl FullOuterJoins for ClickHouseDialect {}
784impl BitwiseAggregates for ClickHouseDialect {}
785impl RawSql for ClickHouseDialect {}
786impl CrossJoins for ClickHouseDialect {}
787
788impl Builder<ClickHouseDialect> {
789    /// `PREWHERE` filters, evaluated before the other columns are read.
790    ///
791    /// PHP: `prewhere()`.
792    pub fn prewhere(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
793        self.dialect.prewhere.extend(queries);
794        self
795    }
796
797    /// `FINAL` after the table (merges the data parts first).
798    ///
799    /// PHP: `final()`.
800    pub fn final_(&mut self) -> &mut Self {
801        self.dialect.final_ = true;
802        self
803    }
804
805    /// `SAMPLE fraction` after the table; the fraction must be in `(0, 1)`.
806    ///
807    /// PHP: `sample()`.
808    pub fn sample(&mut self, fraction: f64) -> Result<&mut Self> {
809        if fraction <= 0.0 || fraction >= 1.0 {
810            return Err(Error::Validation("Sample fraction must be between 0 and 1 exclusive".into()));
811        }
812        self.dialect.sample_fraction = Some(fraction);
813        Ok(self)
814    }
815
816    /// `SETTINGS key=value, ...` at the end of selects and deletes; keys are
817    /// identifiers, values letters, digits, `_` and `.`.
818    ///
819    /// PHP: `settings()`.
820    pub fn settings<K: AsRef<str>, V: AsRef<str>>(
821        &mut self,
822        settings: impl IntoIterator<Item = (K, V)>,
823    ) -> Result<&mut Self> {
824        for (key, value) in settings {
825            let (key, value) = (key.as_ref(), value.as_ref());
826            if !is_plain_identifier(key) {
827                return Err(Error::Validation(format!("Invalid ClickHouse setting key: {key}")));
828            }
829            if !is_setting_value(value) {
830                return Err(Error::Validation(format!("Invalid ClickHouse setting value: {value}")));
831            }
832            self.core.hints.push(format!("{key}={value}"));
833        }
834        Ok(self)
835    }
836
837    /// The `INSERT INTO table [(columns)] FORMAT format` envelope with the
838    /// rows serialized in `format`. Each row must be an array; the columns
839    /// default to the first row's keys.
840    ///
841    /// PHP: `bulkInsert()`.
842    ///
843    /// ```
844    /// use utopia_query::builder::{ClickHouse, Format};
845    /// use utopia_query::{Array, Value};
846    ///
847    /// let mut row = Array::default();
848    /// row.set("id".into(), Value::Int(1));
849    /// let insert = ClickHouse::new().from("events", "").bulk_insert(Format::JSONEachRow, [Value::Array(row)], Vec::new())?;
850    /// assert_eq!(insert.query, "INSERT INTO `events` (`id`) FORMAT JSONEachRow");
851    /// assert_eq!(insert.body.as_deref(), Some(r#"{"id":1}"#));
852    /// # Ok::<(), utopia_query::Error>(())
853    /// ```
854    ///
855    /// ```php
856    /// use Utopia\Query\Builder\ClickHouse;
857    /// use Utopia\Query\Builder\ClickHouse\Format;
858    ///
859    /// $insert = (new ClickHouse())->from('events')->bulkInsert(Format::JSONEachRow, [['id' => 1]]);
860    /// echo $insert->query, "\n", $insert->body, "\n";
861    /// // INSERT INTO `events` (`id`) FORMAT JSONEachRow
862    /// // {"id":1}
863    /// ```
864    pub fn bulk_insert(
865        &mut self,
866        format: Format,
867        rows: impl IntoIterator<Item = Value>,
868        columns: Vec<String>,
869    ) -> Result<FormattedInsertStatement> {
870        let mut materialized = Vec::new();
871        for row in rows {
872            match row {
873                Value::Array(row) => materialized.push(row),
874                _ => return Err(Error::Validation("bulkInsert() rows must be associative arrays.".into())),
875            }
876        }
877        let mut columns = columns;
878        if columns.is_empty()
879            && let Some(row) = materialized.first()
880        {
881            columns = row.keys().map(|k| key_string(&k.to_owned())).collect();
882        }
883        let sql = self.format_insert_envelope(format.as_str(), &columns)?;
884        let body = format.serialize(&materialized, if columns.is_empty() { None } else { Some(&columns) })?;
885        Ok(FormattedInsertStatement {
886            statement: Statement::with_parts(sql, Vec::new(), false, self.core.executor.clone(), None),
887            columns,
888            format: format.as_str().to_owned(),
889            body: Some(body),
890        })
891    }
892
893    /// A columnless `INSERT INTO table FORMAT format` envelope with each row
894    /// serialized independently, keeping only the keys that row carries.
895    ///
896    /// Unlike [`Builder::bulk_insert`], no column list is derived from the
897    /// first row and no keys are projected or filled with `null`, so rows in
898    /// the same batch may have different shapes and omitted keys take their
899    /// ClickHouse column defaults. Requires a self-describing format
900    /// ([`Format::JSONEachRow`]); positional formats such as
901    /// [`Format::TabSeparated`] are rejected.
902    ///
903    /// PHP: `bulkInsertSparse()`.
904    ///
905    /// ```
906    /// use utopia_query::builder::{ClickHouse, Format};
907    /// use utopia_query::{Array, Value};
908    ///
909    /// let mut first = Array::default();
910    /// first.set("id".into(), Value::Int(1));
911    /// let mut second = Array::default();
912    /// second.set("id".into(), Value::Int(2));
913    /// second.set("note".into(), "hi".into());
914    /// let insert = ClickHouse::new()
915    ///     .from("events", "")
916    ///     .bulk_insert_sparse(Format::JSONEachRow, [Value::Array(first), Value::Array(second)])?;
917    /// assert_eq!(insert.query, "INSERT INTO `events` FORMAT JSONEachRow");
918    /// assert!(insert.columns.is_empty());
919    /// assert_eq!(insert.body.as_deref(), Some("{\"id\":1}\n{\"id\":2,\"note\":\"hi\"}"));
920    /// # Ok::<(), utopia_query::Error>(())
921    /// ```
922    ///
923    /// ```php
924    /// use Utopia\Query\Builder\ClickHouse;
925    /// use Utopia\Query\Builder\ClickHouse\Format;
926    ///
927    /// $insert = (new ClickHouse())
928    ///     ->from('events')
929    ///     ->bulkInsertSparse(Format::JSONEachRow, [['id' => 1], ['id' => 2, 'note' => 'hi']]);
930    /// echo $insert->query, "\n", $insert->body, "\n";
931    /// // INSERT INTO `events` FORMAT JSONEachRow
932    /// // {"id":1}
933    /// // {"id":2,"note":"hi"}
934    /// ```
935    pub fn bulk_insert_sparse(
936        &mut self,
937        format: Format,
938        rows: impl IntoIterator<Item = Value>,
939    ) -> Result<FormattedInsertStatement> {
940        if !matches!(format, Format::JSONEachRow) {
941            return Err(Error::Validation(format!(
942                "bulkInsertSparse() requires a self-describing format; {} is positional.",
943                format.as_str()
944            )));
945        }
946        let mut materialized = Vec::new();
947        for row in rows {
948            match row {
949                Value::Array(row) => materialized.push(row),
950                _ => return Err(Error::Validation("bulkInsertSparse() rows must be associative arrays.".into())),
951            }
952        }
953        let sql = self.format_insert_envelope(format.as_str(), &[])?;
954        let body = format.serialize(&materialized, None)?;
955        Ok(FormattedInsertStatement {
956            statement: Statement::with_parts(sql, Vec::new(), false, self.core.executor.clone(), None),
957            columns: Vec::new(),
958            format: format.as_str().to_owned(),
959            body: Some(body),
960        })
961    }
962
963    /// Makes [`Builder::insert`] (and [`Builder::formatted_insert`]) emit the
964    /// `FORMAT format` envelope only, for a body sent separately; the columns
965    /// default to the keys of the first row set.
966    ///
967    /// PHP: `insertFormat()`.
968    pub fn insert_format<S: Into<String>>(
969        &mut self,
970        format: &str,
971        columns: impl IntoIterator<Item = S>,
972    ) -> Result<&mut Self> {
973        if !is_format_name(format) {
974            return Err(Error::Validation(format!("Invalid ClickHouse INSERT format: {format}")));
975        }
976        self.dialect.insert_format = Some(format.to_owned());
977        self.dialect.insert_format_columns = columns.into_iter().map(Into::into).collect();
978        Ok(self)
979    }
980
981    /// The `FORMAT` envelope of an [`Builder::insert_format`] insert (with no
982    /// body), or `None` when no format was set.
983    ///
984    /// PHP: `insert()`, which returns a `FormattedInsertStatement` after `insertFormat()`.
985    pub fn formatted_insert(&mut self) -> Result<Option<FormattedInsertStatement>> {
986        let Some(format) = self.dialect.insert_format.clone() else {
987            return Ok(None);
988        };
989        let columns = if !self.dialect.insert_format_columns.is_empty() {
990            self.dialect.insert_format_columns.clone()
991        } else {
992            match self.core.rows.first() {
993                Some(row) => row.keys().map(|k| key_string(&k.to_owned())).collect(),
994                None => Vec::new(),
995            }
996        };
997        let sql = self.format_insert_envelope(&format, &columns)?;
998        Ok(Some(FormattedInsertStatement {
999            statement: Statement::with_parts(sql, Vec::new(), false, self.core.executor.clone(), None),
1000            columns,
1001            format,
1002            body: None,
1003        }))
1004    }
1005
1006    fn format_insert_envelope(&mut self, format: &str, columns: &[String]) -> Result<String> {
1007        self.core.bindings.clear();
1008        self.validate_table()?;
1009        if columns.iter().any(String::is_empty) {
1010            return Err(Error::Validation("Column names for FORMAT INSERT must be non-empty strings.".into()));
1011        }
1012        let mut sql = format!("INSERT INTO {}", self.quote(&self.core.table.clone())?);
1013        if !columns.is_empty() {
1014            let wrapped = columns.iter().map(|c| self.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
1015            sql.push_str(" (");
1016            sql.push_str(&wrapped.join(", "));
1017            sql.push(')');
1018        }
1019        sql.push_str(" FORMAT ");
1020        sql.push_str(format);
1021        Ok(sql)
1022    }
1023
1024    /// Rewrites the `?` placeholders of built statements to ClickHouse's
1025    /// `{paramN:Type}` and fills [`Statement::named_bindings`].
1026    ///
1027    /// PHP: `useNamedBindings()`.
1028    ///
1029    /// ```
1030    /// use utopia_query::Query;
1031    /// use utopia_query::builder::ClickHouse;
1032    ///
1033    /// let statement = ClickHouse::new()
1034    ///     .use_named_bindings(true)
1035    ///     .with_param_type("time", "DateTime64(3)")?
1036    ///     .from("events", "")
1037    ///     .filter([Query::greater_than("time", "2024-01-01 00:00:00"), Query::less_than_equal("value", 100)])
1038    ///     .build()?;
1039    /// assert_eq!(
1040    ///     statement.query,
1041    ///     "SELECT * FROM `events` WHERE `time` > {param0:DateTime64(3)} AND `value` <= {param1:Int64}"
1042    /// );
1043    /// # Ok::<(), utopia_query::Error>(())
1044    /// ```
1045    ///
1046    /// ```php
1047    /// use Utopia\Query\Builder\ClickHouse;
1048    /// use Utopia\Query\Query;
1049    ///
1050    /// echo (new ClickHouse())
1051    ///     ->useNamedBindings()
1052    ///     ->withParamType('time', 'DateTime64(3)')
1053    ///     ->from('events')
1054    ///     ->filter([Query::greaterThan('time', '2024-01-01 00:00:00'), Query::lessThanEqual('value', 100)])
1055    ///     ->build()->query, "\n";
1056    /// // SELECT * FROM `events` WHERE `time` > {param0:DateTime64(3)} AND `value` <= {param1:Int64}
1057    /// ```
1058    pub fn use_named_bindings(&mut self, enabled: bool) -> &mut Self {
1059        self.dialect.named_bindings = enabled;
1060        self
1061    }
1062
1063    /// The ClickHouse type of the named placeholders bound against `column`
1064    /// (others are inferred: `Int64`, `Float64`, `UInt8`, `Nullable(String)`,
1065    /// `String`).
1066    ///
1067    /// PHP: `withParamType()`.
1068    pub fn with_param_type(&mut self, column: impl Into<String>, type_name: &str) -> Result<&mut Self> {
1069        if !is_clickhouse_type(type_name) {
1070            return Err(Error::Validation(format!("Invalid ClickHouse type: {type_name}")));
1071        }
1072        self.dialect.param_types.insert(column.into(), type_name.to_owned());
1073        Ok(self)
1074    }
1075
1076    /// [`Builder::with_param_type`] for each pair.
1077    ///
1078    /// PHP: `withParamTypes()`.
1079    pub fn with_param_types<K: Into<String>, V: AsRef<str>>(
1080        &mut self,
1081        types: impl IntoIterator<Item = (K, V)>,
1082    ) -> Result<&mut Self> {
1083        for (column, type_name) in types {
1084            self.with_param_type(column, type_name.as_ref())?;
1085        }
1086        Ok(self)
1087    }
1088
1089    /// Which `DELETE` form [`Builder::delete`] emits.
1090    ///
1091    /// PHP: `deleteMode()` (with the mode's name; see [`DeleteMode::parse`]).
1092    pub fn delete_mode(&mut self, mode: DeleteMode) -> &mut Self {
1093        self.dialect.delete_mode = mode;
1094        self
1095    }
1096
1097    // ----- statistical aggregates (ClickHouse spells STDDEV and VARIANCE) ----
1098
1099    /// `stddevPop(column) [AS alias]`: ClickHouse has no bare `STDDEV`.
1100    ///
1101    /// PHP: `stddev()`.
1102    pub fn stddev(&mut self, attribute: &str, alias: &str) -> Result<&mut Self> {
1103        let expression = format!("stddevPop({})", self.resolve_and_wrap(attribute)?);
1104        select_function(self, expression, alias)?;
1105        Ok(self)
1106    }
1107
1108    /// `STDDEV_POP` (as an aggregate query).
1109    ///
1110    /// PHP: `stddevPop()`.
1111    pub fn stddev_pop(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1112        self.core.pending.push(Query::stddev_pop(attribute, alias));
1113        self
1114    }
1115
1116    /// `STDDEV_SAMP` (as an aggregate query).
1117    ///
1118    /// PHP: `stddevSamp()`.
1119    pub fn stddev_samp(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1120        self.core.pending.push(Query::stddev_samp(attribute, alias));
1121        self
1122    }
1123
1124    /// `varPop(column) [AS alias]`: ClickHouse has no bare `VARIANCE`.
1125    ///
1126    /// PHP: `variance()`.
1127    pub fn variance(&mut self, attribute: &str, alias: &str) -> Result<&mut Self> {
1128        let expression = format!("varPop({})", self.resolve_and_wrap(attribute)?);
1129        select_function(self, expression, alias)?;
1130        Ok(self)
1131    }
1132
1133    /// `VAR_POP` (as an aggregate query).
1134    ///
1135    /// PHP: `varPop()`.
1136    pub fn var_pop(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1137        self.core.pending.push(Query::var_pop(attribute, alias));
1138        self
1139    }
1140
1141    /// `VAR_SAMP` (as an aggregate query).
1142    ///
1143    /// PHP: `varSamp()`.
1144    pub fn var_samp(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1145        self.core.pending.push(Query::var_samp(attribute, alias));
1146        self
1147    }
1148
1149    // ----- approximate aggregates ---------------------------------------------
1150
1151    fn aggregate_function(&mut self, function: &str, columns: &[&str], alias: &str) -> Result<&mut Self> {
1152        let columns = columns.iter().map(|c| self.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
1153        select_function(self, format!("{function}({})", columns.join(", ")), alias)?;
1154        Ok(self)
1155    }
1156
1157    /// `quantile(level)(column)`.
1158    ///
1159    /// PHP: `quantile()`.
1160    pub fn quantile(&mut self, level: f64, column: &str, alias: &str) -> Result<&mut Self> {
1161        self.aggregate_function(&format!("quantile({})", php_std::number::to_string(level)), &[column], alias)
1162    }
1163
1164    /// `quantiles(level, ...)(column)`; levels must be in `[0, 1]`.
1165    ///
1166    /// PHP: `quantiles()`.
1167    pub fn quantiles(&mut self, levels: &[f64], column: &str, alias: &str) -> Result<&mut Self> {
1168        if levels.is_empty() {
1169            return Err(Error::Validation("quantiles() requires at least one level.".into()));
1170        }
1171        if levels.iter().any(|&level| !(0.0..=1.0).contains(&level)) {
1172            return Err(Error::Validation("quantiles() levels must be in the range [0, 1].".into()));
1173        }
1174        let levels: Vec<String> = levels.iter().map(|&level| php_std::number::to_string(level)).collect();
1175        self.aggregate_function(&format!("quantiles({})", levels.join(", ")), &[column], alias)
1176    }
1177
1178    /// `quantileExact(level)(column)`.
1179    ///
1180    /// PHP: `quantileExact()`.
1181    pub fn quantile_exact(&mut self, level: f64, column: &str, alias: &str) -> Result<&mut Self> {
1182        self.aggregate_function(&format!("quantileExact({})", php_std::number::to_string(level)), &[column], alias)
1183    }
1184
1185    /// `median(column)`.
1186    ///
1187    /// PHP: `median()`.
1188    pub fn median(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1189        self.aggregate_function("median", &[column], alias)
1190    }
1191
1192    /// `uniq(column)`.
1193    ///
1194    /// PHP: `uniq()`.
1195    pub fn uniq(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1196        self.aggregate_function("uniq", &[column], alias)
1197    }
1198
1199    /// `uniqExact(column)`.
1200    ///
1201    /// PHP: `uniqExact()`.
1202    pub fn uniq_exact(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1203        self.aggregate_function("uniqExact", &[column], alias)
1204    }
1205
1206    /// `uniqCombined(column)`.
1207    ///
1208    /// PHP: `uniqCombined()`.
1209    pub fn uniq_combined(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1210        self.aggregate_function("uniqCombined", &[column], alias)
1211    }
1212
1213    /// `argMin(value, arg)`.
1214    ///
1215    /// PHP: `argMin()`.
1216    pub fn arg_min(&mut self, value_column: &str, arg_column: &str, alias: &str) -> Result<&mut Self> {
1217        self.aggregate_function("argMin", &[value_column, arg_column], alias)
1218    }
1219
1220    /// `argMax(value, arg)`.
1221    ///
1222    /// PHP: `argMax()`.
1223    pub fn arg_max(&mut self, value_column: &str, arg_column: &str, alias: &str) -> Result<&mut Self> {
1224        self.aggregate_function("argMax", &[value_column, arg_column], alias)
1225    }
1226
1227    /// `topK(k)(column)`.
1228    ///
1229    /// PHP: `topK()`.
1230    pub fn top_k(&mut self, k: i64, column: &str, alias: &str) -> Result<&mut Self> {
1231        self.aggregate_function(&format!("topK({k})"), &[column], alias)
1232    }
1233
1234    /// `topKWeighted(k)(column, weight)`.
1235    ///
1236    /// PHP: `topKWeighted()`.
1237    pub fn top_k_weighted(&mut self, k: i64, column: &str, weight_column: &str, alias: &str) -> Result<&mut Self> {
1238        self.aggregate_function(&format!("topKWeighted({k})"), &[column, weight_column], alias)
1239    }
1240
1241    /// `any(column)`.
1242    ///
1243    /// PHP: `anyValue()`.
1244    pub fn any_value(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1245        self.aggregate_function("any", &[column], alias)
1246    }
1247
1248    /// `anyLast(column)`.
1249    ///
1250    /// PHP: `anyLastValue()`.
1251    pub fn any_last_value(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1252        self.aggregate_function("anyLast", &[column], alias)
1253    }
1254
1255    /// `groupUniqArray(column)`.
1256    ///
1257    /// PHP: `groupUniqArray()`.
1258    pub fn group_uniq_array(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1259        self.aggregate_function("groupUniqArray", &[column], alias)
1260    }
1261
1262    /// `groupArrayMovingAvg(column)`.
1263    ///
1264    /// PHP: `groupArrayMovingAvg()`.
1265    pub fn group_array_moving_avg(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1266        self.aggregate_function("groupArrayMovingAvg", &[column], alias)
1267    }
1268
1269    /// `groupArrayMovingSum(column)`.
1270    ///
1271    /// PHP: `groupArrayMovingSum()`.
1272    pub fn group_array_moving_sum(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1273        self.aggregate_function("groupArrayMovingSum", &[column], alias)
1274    }
1275
1276    // ----- joins, LIMIT BY, WITH FILL -----------------------------------------
1277
1278    /// `ARRAY JOIN column [AS alias]`.
1279    ///
1280    /// PHP: `arrayJoin()`.
1281    pub fn array_join(&mut self, column: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1282        self.dialect.array_joins.push(ArrayJoin { left: false, column: column.into(), alias: alias.into() });
1283        self
1284    }
1285
1286    /// `LEFT ARRAY JOIN column [AS alias]`.
1287    ///
1288    /// PHP: `leftArrayJoin()`.
1289    pub fn left_array_join(&mut self, column: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1290        self.dialect.array_joins.push(ArrayJoin { left: true, column: column.into(), alias: alias.into() });
1291        self
1292    }
1293
1294    /// `ASOF JOIN table [AS alias] ON l = r AND ... AND left operator right`.
1295    ///
1296    /// PHP: `asofJoin()`.
1297    pub fn asof_join<L: AsRef<str>, R: AsRef<str>>(
1298        &mut self,
1299        table: &str,
1300        equi_pairs: impl IntoIterator<Item = (L, R)>,
1301        left_inequality: &str,
1302        operator: AsofOperator,
1303        right_inequality: &str,
1304        alias: &str,
1305    ) -> Result<&mut Self> {
1306        let clause =
1307            self.asof_clause("ASOF JOIN", table, equi_pairs, left_inequality, operator, right_inequality, alias)?;
1308        self.dialect.raw_joins.push(clause);
1309        Ok(self)
1310    }
1311
1312    /// `ASOF LEFT JOIN ...`.
1313    ///
1314    /// PHP: `asofLeftJoin()`.
1315    pub fn asof_left_join<L: AsRef<str>, R: AsRef<str>>(
1316        &mut self,
1317        table: &str,
1318        equi_pairs: impl IntoIterator<Item = (L, R)>,
1319        left_inequality: &str,
1320        operator: AsofOperator,
1321        right_inequality: &str,
1322        alias: &str,
1323    ) -> Result<&mut Self> {
1324        let clause =
1325            self.asof_clause("ASOF LEFT JOIN", table, equi_pairs, left_inequality, operator, right_inequality, alias)?;
1326        self.dialect.raw_joins.push(clause);
1327        Ok(self)
1328    }
1329
1330    #[allow(clippy::too_many_arguments)]
1331    fn asof_clause<L: AsRef<str>, R: AsRef<str>>(
1332        &mut self,
1333        keyword: &str,
1334        table: &str,
1335        equi_pairs: impl IntoIterator<Item = (L, R)>,
1336        left_inequality: &str,
1337        operator: AsofOperator,
1338        right_inequality: &str,
1339        alias: &str,
1340    ) -> Result<String> {
1341        let pairs: Vec<(L, R)> = equi_pairs.into_iter().collect();
1342        if pairs.is_empty() {
1343            return Err(Error::Validation("ASOF JOIN requires at least one equi-join column pair.".into()));
1344        }
1345        let mut table = self.quote(table)?;
1346        if !alias.is_empty() {
1347            table.push_str(" AS ");
1348            table.push_str(&self.quote(alias)?);
1349        }
1350        let mut conditions = Vec::with_capacity(pairs.len() + 1);
1351        for (left, right) in &pairs {
1352            conditions.push(format!(
1353                "{} = {}",
1354                self.resolve_and_wrap(left.as_ref())?,
1355                self.resolve_and_wrap(right.as_ref())?
1356            ));
1357        }
1358        conditions.push(format!(
1359            "{} {} {}",
1360            self.resolve_and_wrap(left_inequality)?,
1361            operator.as_str(),
1362            self.resolve_and_wrap(right_inequality)?
1363        ));
1364        Ok(format!("{keyword} {table} ON {}", conditions.join(" AND ")))
1365    }
1366
1367    /// `LIMIT count BY columns`.
1368    ///
1369    /// PHP: `limitBy()`.
1370    pub fn limit_by<S: Into<String>>(&mut self, count: i64, columns: impl IntoIterator<Item = S>) -> &mut Self {
1371        self.dialect.limit_by = Some((count, columns.into_iter().map(Into::into).collect()));
1372        self
1373    }
1374
1375    /// `ORDER BY column ASC|DESC WITH FILL [FROM ?] [TO ?] [STEP ?]`.
1376    ///
1377    /// PHP: `orderWithFill()`.
1378    pub fn order_with_fill(
1379        &mut self,
1380        column: &str,
1381        direction: &str,
1382        from: Option<Value>,
1383        to: Option<Value>,
1384        step: Option<Value>,
1385    ) -> Result<&mut Self> {
1386        let normalized = direction.to_ascii_uppercase();
1387        if normalized != "ASC" && normalized != "DESC" {
1388            return Err(Error::Validation(format!("Invalid direction for orderWithFill: {direction}")));
1389        }
1390        let mut expression = format!("{} {normalized} WITH FILL", self.resolve_and_wrap(column)?);
1391        let mut bindings = Vec::new();
1392        for (keyword, value) in [(" FROM ?", from), (" TO ?", to), (" STEP ?", step)] {
1393            if let Some(value) = value.filter(|v| !matches!(v, Value::Null)) {
1394                expression.push_str(keyword);
1395                bindings.push(value);
1396            }
1397        }
1398        self.core.raw_orders.push(Condition::new(expression, bindings));
1399        Ok(self)
1400    }
1401}
1402
1403#[cfg(test)]
1404mod tests {
1405    use super::*;
1406
1407    #[test]
1408    fn type_names() {
1409        assert!(is_clickhouse_type("Int64"));
1410        assert!(is_clickhouse_type("Nullable(DateTime64(3))"));
1411        assert!(is_clickhouse_type("Decimal(10, 2)"));
1412        assert!(!is_clickhouse_type("Int64\n"));
1413        assert!(!is_clickhouse_type("DROP TABLE x; --"));
1414        assert!(!is_clickhouse_type("A(B(C(1)))"));
1415        assert!(!is_clickhouse_type("A(1))"));
1416    }
1417
1418    #[test]
1419    fn bulk_insert_sparse_keeps_each_rows_own_keys_without_column_list() {
1420        let mut first = Array::default();
1421        first.set("id".into(), Value::Int(1));
1422        first.set("is_bot".into(), Value::Int(0));
1423
1424        let mut second = Array::default();
1425        second.set("id".into(), Value::Int(2));
1426        second.set("city".into(), "Berlin".into());
1427
1428        let mut third = Array::default();
1429        third.set("id".into(), Value::Int(3));
1430
1431        let insert = ClickHouse::new()
1432            .from("analytics.events", "")
1433            .bulk_insert_sparse(Format::JSONEachRow, [Value::Array(first), Value::Array(second), Value::Array(third)])
1434            .unwrap();
1435
1436        assert_eq!(insert.query, "INSERT INTO `analytics`.`events` FORMAT JSONEachRow");
1437        assert!(insert.columns.is_empty());
1438        assert_eq!(insert.format, "JSONEachRow");
1439        assert!(insert.bindings.is_empty());
1440        assert_eq!(insert.body.as_deref(), Some("{\"id\":1,\"is_bot\":0}\n{\"id\":2,\"city\":\"Berlin\"}\n{\"id\":3}"));
1441    }
1442
1443    #[test]
1444    fn bulk_insert_sparse_empty_rows_emits_bare_envelope_and_empty_body() {
1445        let insert =
1446            ClickHouse::new().from("events", "").bulk_insert_sparse(Format::JSONEachRow, Vec::<Value>::new()).unwrap();
1447
1448        assert_eq!(insert.query, "INSERT INTO `events` FORMAT JSONEachRow");
1449        assert!(insert.columns.is_empty());
1450        assert_eq!(insert.body.as_deref(), Some(""));
1451    }
1452
1453    #[test]
1454    fn bulk_insert_sparse_rejects_positional_formats_and_non_array_rows() {
1455        let mut row = Array::default();
1456        row.set("id".into(), Value::Int(1));
1457
1458        let positional = ClickHouse::new()
1459            .from("events", "")
1460            .bulk_insert_sparse(Format::TabSeparated, [Value::Array(row)])
1461            .unwrap_err();
1462        assert!(matches!(positional, Error::Validation(_)));
1463
1464        let scalar =
1465            ClickHouse::new().from("events", "").bulk_insert_sparse(Format::JSONEachRow, [Value::Int(1)]).unwrap_err();
1466        assert!(matches!(scalar, Error::Validation(_)));
1467    }
1468}