1use 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
41pub type ClickHouse = Builder<ClickHouseDialect>;
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80struct ArrayJoin {
81 left: bool,
82 column: String,
83 alias: String,
84}
85
86#[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
106pub enum DeleteMode {
107 #[default]
111 Lightweight,
112 Mutation,
116}
117
118impl DeleteMode {
119 pub const fn as_str(self) -> &'static str {
121 match self {
122 DeleteMode::Lightweight => "lightweight",
123 DeleteMode::Mutation => "mutation",
124 }
125 }
126
127 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 pub enum AsofOperator: "Utopia\\Query\\Builder\\ClickHouse\\AsofOperator" {
146 LessThan = "<",
148 LessThanEqual = "<=",
150 GreaterThan = ">",
152 GreaterThanEqual = ">=",
154 }
155}
156
157backed_enum! {
158 pub enum Format: "Utopia\\Query\\Builder\\ClickHouse\\Format" {
162 JSONEachRow = "JSONEachRow",
164 TabSeparated = "TabSeparated",
166 }
167}
168
169impl Format {
170 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
207fn 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
245fn 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#[derive(Debug, Clone, PartialEq)]
281pub struct FormattedInsertStatement {
282 pub statement: Statement,
284 pub columns: Vec<String>,
286 pub format: String,
288 pub body: Option<String>,
290}
291
292impl Deref for FormattedInsertStatement {
293 type Target = Statement;
294
295 fn deref(&self) -> &Statement {
297 &self.statement
298 }
299}
300
301impl FormattedInsertStatement {
302 pub fn with_executor(&self, executor: Executor) -> FormattedInsertStatement {
306 FormattedInsertStatement { statement: self.statement.with_executor(executor), ..self.clone() }
307 }
308}
309
310fn 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
317fn 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
323fn 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
329fn 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
368fn 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
379fn 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 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
436fn 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 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 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 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 pub fn prewhere(&mut self, queries: impl IntoIterator<Item = Query>) -> &mut Self {
793 self.dialect.prewhere.extend(queries);
794 self
795 }
796
797 pub fn final_(&mut self) -> &mut Self {
801 self.dialect.final_ = true;
802 self
803 }
804
805 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 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 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 pub fn insert_format<S: Into<String>>(
899 &mut self,
900 format: &str,
901 columns: impl IntoIterator<Item = S>,
902 ) -> Result<&mut Self> {
903 if !is_format_name(format) {
904 return Err(Error::Validation(format!("Invalid ClickHouse INSERT format: {format}")));
905 }
906 self.dialect.insert_format = Some(format.to_owned());
907 self.dialect.insert_format_columns = columns.into_iter().map(Into::into).collect();
908 Ok(self)
909 }
910
911 pub fn formatted_insert(&mut self) -> Result<Option<FormattedInsertStatement>> {
916 let Some(format) = self.dialect.insert_format.clone() else {
917 return Ok(None);
918 };
919 let columns = if !self.dialect.insert_format_columns.is_empty() {
920 self.dialect.insert_format_columns.clone()
921 } else {
922 match self.core.rows.first() {
923 Some(row) => row.keys().map(|k| key_string(&k.to_owned())).collect(),
924 None => Vec::new(),
925 }
926 };
927 let sql = self.format_insert_envelope(&format, &columns)?;
928 Ok(Some(FormattedInsertStatement {
929 statement: Statement::with_parts(sql, Vec::new(), false, self.core.executor.clone(), None),
930 columns,
931 format,
932 body: None,
933 }))
934 }
935
936 fn format_insert_envelope(&mut self, format: &str, columns: &[String]) -> Result<String> {
937 self.core.bindings.clear();
938 self.validate_table()?;
939 if columns.iter().any(String::is_empty) {
940 return Err(Error::Validation("Column names for FORMAT INSERT must be non-empty strings.".into()));
941 }
942 let mut sql = format!("INSERT INTO {}", self.quote(&self.core.table.clone())?);
943 if !columns.is_empty() {
944 let wrapped = columns.iter().map(|c| self.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
945 sql.push_str(" (");
946 sql.push_str(&wrapped.join(", "));
947 sql.push(')');
948 }
949 sql.push_str(" FORMAT ");
950 sql.push_str(format);
951 Ok(sql)
952 }
953
954 pub fn use_named_bindings(&mut self, enabled: bool) -> &mut Self {
989 self.dialect.named_bindings = enabled;
990 self
991 }
992
993 pub fn with_param_type(&mut self, column: impl Into<String>, type_name: &str) -> Result<&mut Self> {
999 if !is_clickhouse_type(type_name) {
1000 return Err(Error::Validation(format!("Invalid ClickHouse type: {type_name}")));
1001 }
1002 self.dialect.param_types.insert(column.into(), type_name.to_owned());
1003 Ok(self)
1004 }
1005
1006 pub fn with_param_types<K: Into<String>, V: AsRef<str>>(
1010 &mut self,
1011 types: impl IntoIterator<Item = (K, V)>,
1012 ) -> Result<&mut Self> {
1013 for (column, type_name) in types {
1014 self.with_param_type(column, type_name.as_ref())?;
1015 }
1016 Ok(self)
1017 }
1018
1019 pub fn delete_mode(&mut self, mode: DeleteMode) -> &mut Self {
1023 self.dialect.delete_mode = mode;
1024 self
1025 }
1026
1027 pub fn stddev(&mut self, attribute: &str, alias: &str) -> Result<&mut Self> {
1033 let expression = format!("stddevPop({})", self.resolve_and_wrap(attribute)?);
1034 select_function(self, expression, alias)?;
1035 Ok(self)
1036 }
1037
1038 pub fn stddev_pop(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1042 self.core.pending.push(Query::stddev_pop(attribute, alias));
1043 self
1044 }
1045
1046 pub fn stddev_samp(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1050 self.core.pending.push(Query::stddev_samp(attribute, alias));
1051 self
1052 }
1053
1054 pub fn variance(&mut self, attribute: &str, alias: &str) -> Result<&mut Self> {
1058 let expression = format!("varPop({})", self.resolve_and_wrap(attribute)?);
1059 select_function(self, expression, alias)?;
1060 Ok(self)
1061 }
1062
1063 pub fn var_pop(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1067 self.core.pending.push(Query::var_pop(attribute, alias));
1068 self
1069 }
1070
1071 pub fn var_samp(&mut self, attribute: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1075 self.core.pending.push(Query::var_samp(attribute, alias));
1076 self
1077 }
1078
1079 fn aggregate_function(&mut self, function: &str, columns: &[&str], alias: &str) -> Result<&mut Self> {
1082 let columns = columns.iter().map(|c| self.resolve_and_wrap(c)).collect::<Result<Vec<_>>>()?;
1083 select_function(self, format!("{function}({})", columns.join(", ")), alias)?;
1084 Ok(self)
1085 }
1086
1087 pub fn quantile(&mut self, level: f64, column: &str, alias: &str) -> Result<&mut Self> {
1091 self.aggregate_function(&format!("quantile({})", php_std::number::to_string(level)), &[column], alias)
1092 }
1093
1094 pub fn quantiles(&mut self, levels: &[f64], column: &str, alias: &str) -> Result<&mut Self> {
1098 if levels.is_empty() {
1099 return Err(Error::Validation("quantiles() requires at least one level.".into()));
1100 }
1101 if levels.iter().any(|&level| !(0.0..=1.0).contains(&level)) {
1102 return Err(Error::Validation("quantiles() levels must be in the range [0, 1].".into()));
1103 }
1104 let levels: Vec<String> = levels.iter().map(|&level| php_std::number::to_string(level)).collect();
1105 self.aggregate_function(&format!("quantiles({})", levels.join(", ")), &[column], alias)
1106 }
1107
1108 pub fn quantile_exact(&mut self, level: f64, column: &str, alias: &str) -> Result<&mut Self> {
1112 self.aggregate_function(&format!("quantileExact({})", php_std::number::to_string(level)), &[column], alias)
1113 }
1114
1115 pub fn median(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1119 self.aggregate_function("median", &[column], alias)
1120 }
1121
1122 pub fn uniq(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1126 self.aggregate_function("uniq", &[column], alias)
1127 }
1128
1129 pub fn uniq_exact(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1133 self.aggregate_function("uniqExact", &[column], alias)
1134 }
1135
1136 pub fn uniq_combined(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1140 self.aggregate_function("uniqCombined", &[column], alias)
1141 }
1142
1143 pub fn arg_min(&mut self, value_column: &str, arg_column: &str, alias: &str) -> Result<&mut Self> {
1147 self.aggregate_function("argMin", &[value_column, arg_column], alias)
1148 }
1149
1150 pub fn arg_max(&mut self, value_column: &str, arg_column: &str, alias: &str) -> Result<&mut Self> {
1154 self.aggregate_function("argMax", &[value_column, arg_column], alias)
1155 }
1156
1157 pub fn top_k(&mut self, k: i64, column: &str, alias: &str) -> Result<&mut Self> {
1161 self.aggregate_function(&format!("topK({k})"), &[column], alias)
1162 }
1163
1164 pub fn top_k_weighted(&mut self, k: i64, column: &str, weight_column: &str, alias: &str) -> Result<&mut Self> {
1168 self.aggregate_function(&format!("topKWeighted({k})"), &[column, weight_column], alias)
1169 }
1170
1171 pub fn any_value(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1175 self.aggregate_function("any", &[column], alias)
1176 }
1177
1178 pub fn any_last_value(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1182 self.aggregate_function("anyLast", &[column], alias)
1183 }
1184
1185 pub fn group_uniq_array(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1189 self.aggregate_function("groupUniqArray", &[column], alias)
1190 }
1191
1192 pub fn group_array_moving_avg(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1196 self.aggregate_function("groupArrayMovingAvg", &[column], alias)
1197 }
1198
1199 pub fn group_array_moving_sum(&mut self, column: &str, alias: &str) -> Result<&mut Self> {
1203 self.aggregate_function("groupArrayMovingSum", &[column], alias)
1204 }
1205
1206 pub fn array_join(&mut self, column: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1212 self.dialect.array_joins.push(ArrayJoin { left: false, column: column.into(), alias: alias.into() });
1213 self
1214 }
1215
1216 pub fn left_array_join(&mut self, column: impl Into<String>, alias: impl Into<String>) -> &mut Self {
1220 self.dialect.array_joins.push(ArrayJoin { left: true, column: column.into(), alias: alias.into() });
1221 self
1222 }
1223
1224 pub fn asof_join<L: AsRef<str>, R: AsRef<str>>(
1228 &mut self,
1229 table: &str,
1230 equi_pairs: impl IntoIterator<Item = (L, R)>,
1231 left_inequality: &str,
1232 operator: AsofOperator,
1233 right_inequality: &str,
1234 alias: &str,
1235 ) -> Result<&mut Self> {
1236 let clause =
1237 self.asof_clause("ASOF JOIN", table, equi_pairs, left_inequality, operator, right_inequality, alias)?;
1238 self.dialect.raw_joins.push(clause);
1239 Ok(self)
1240 }
1241
1242 pub fn asof_left_join<L: AsRef<str>, R: AsRef<str>>(
1246 &mut self,
1247 table: &str,
1248 equi_pairs: impl IntoIterator<Item = (L, R)>,
1249 left_inequality: &str,
1250 operator: AsofOperator,
1251 right_inequality: &str,
1252 alias: &str,
1253 ) -> Result<&mut Self> {
1254 let clause =
1255 self.asof_clause("ASOF LEFT JOIN", table, equi_pairs, left_inequality, operator, right_inequality, alias)?;
1256 self.dialect.raw_joins.push(clause);
1257 Ok(self)
1258 }
1259
1260 #[allow(clippy::too_many_arguments)]
1261 fn asof_clause<L: AsRef<str>, R: AsRef<str>>(
1262 &mut self,
1263 keyword: &str,
1264 table: &str,
1265 equi_pairs: impl IntoIterator<Item = (L, R)>,
1266 left_inequality: &str,
1267 operator: AsofOperator,
1268 right_inequality: &str,
1269 alias: &str,
1270 ) -> Result<String> {
1271 let pairs: Vec<(L, R)> = equi_pairs.into_iter().collect();
1272 if pairs.is_empty() {
1273 return Err(Error::Validation("ASOF JOIN requires at least one equi-join column pair.".into()));
1274 }
1275 let mut table = self.quote(table)?;
1276 if !alias.is_empty() {
1277 table.push_str(" AS ");
1278 table.push_str(&self.quote(alias)?);
1279 }
1280 let mut conditions = Vec::with_capacity(pairs.len() + 1);
1281 for (left, right) in &pairs {
1282 conditions.push(format!(
1283 "{} = {}",
1284 self.resolve_and_wrap(left.as_ref())?,
1285 self.resolve_and_wrap(right.as_ref())?
1286 ));
1287 }
1288 conditions.push(format!(
1289 "{} {} {}",
1290 self.resolve_and_wrap(left_inequality)?,
1291 operator.as_str(),
1292 self.resolve_and_wrap(right_inequality)?
1293 ));
1294 Ok(format!("{keyword} {table} ON {}", conditions.join(" AND ")))
1295 }
1296
1297 pub fn limit_by<S: Into<String>>(&mut self, count: i64, columns: impl IntoIterator<Item = S>) -> &mut Self {
1301 self.dialect.limit_by = Some((count, columns.into_iter().map(Into::into).collect()));
1302 self
1303 }
1304
1305 pub fn order_with_fill(
1309 &mut self,
1310 column: &str,
1311 direction: &str,
1312 from: Option<Value>,
1313 to: Option<Value>,
1314 step: Option<Value>,
1315 ) -> Result<&mut Self> {
1316 let normalized = direction.to_ascii_uppercase();
1317 if normalized != "ASC" && normalized != "DESC" {
1318 return Err(Error::Validation(format!("Invalid direction for orderWithFill: {direction}")));
1319 }
1320 let mut expression = format!("{} {normalized} WITH FILL", self.resolve_and_wrap(column)?);
1321 let mut bindings = Vec::new();
1322 for (keyword, value) in [(" FROM ?", from), (" TO ?", to), (" STEP ?", step)] {
1323 if let Some(value) = value.filter(|v| !matches!(v, Value::Null)) {
1324 expression.push_str(keyword);
1325 bindings.push(value);
1326 }
1327 }
1328 self.core.raw_orders.push(Condition::new(expression, bindings));
1329 Ok(self)
1330 }
1331}
1332
1333#[cfg(test)]
1334mod tests {
1335 use super::*;
1336
1337 #[test]
1338 fn type_names() {
1339 assert!(is_clickhouse_type("Int64"));
1340 assert!(is_clickhouse_type("Nullable(DateTime64(3))"));
1341 assert!(is_clickhouse_type("Decimal(10, 2)"));
1342 assert!(!is_clickhouse_type("Int64\n"));
1343 assert!(!is_clickhouse_type("DROP TABLE x; --"));
1344 assert!(!is_clickhouse_type("A(B(C(1)))"));
1345 assert!(!is_clickhouse_type("A(1))"));
1346 }
1347}