Skip to main content

utopia_query/schema/
clickhouse.rs

1//! [`ClickHouse`]: the ClickHouse schema.
2
3use super::column::{self, Column};
4use super::enums::{ColumnType, Engine, IndexType};
5use super::feature::{self, ViewBody};
6use super::index::Index;
7use super::table::{self, Table};
8use super::{Schema, base, names};
9use crate::builder::{AnyBuilder, Executor, Statement};
10use crate::error::{Error, Result};
11use crate::value::Value;
12
13/// The ClickHouse schema: backtick quoting, `Nullable(...)` /
14/// `LowCardinality(...)` wrapping, engines with `ORDER BY`, `PARTITION BY`,
15/// `SAMPLE BY`, TTL and `SETTINGS`, data-skipping indexes, codecs and
16/// materialized views.
17///
18/// ```
19/// use utopia_query::schema::{ClickHouse, Engine, Schema};
20///
21/// let mut table = ClickHouse::new().table("events");
22/// table.big_integer("id").unsigned().primary();
23/// table.string("country", 255).low_cardinality();
24/// table.datetime("at", 3);
25/// table.engine(Engine::MergeTree, &[])?.partition_by("toYYYYMM(at)");
26/// assert_eq!(
27///     table.create()?.query,
28///     "CREATE TABLE `events` (`id` UInt64, `country` LowCardinality(String), `at` DateTime64(3)) \
29///      ENGINE = MergeTree() PARTITION BY toYYYYMM(at) ORDER BY (`id`)"
30/// );
31/// # Ok::<(), utopia_query::Error>(())
32/// ```
33///
34/// ```php
35/// use Utopia\Query\Schema\ClickHouse;
36/// use Utopia\Query\Schema\ClickHouse\Engine;
37///
38/// $table = (new ClickHouse())->table('events');
39/// $table->bigInteger('id')->unsigned()->primary();
40/// $table->string('country')->lowCardinality();
41/// $table->datetime('at', 3);
42/// $table->engine(Engine::MergeTree)->partitionBy('toYYYYMM(at)');
43/// echo $table->create()->query, "\n";
44/// ```
45///
46/// PHP: `Utopia\Query\Schema\ClickHouse`.
47#[derive(Clone, Default)]
48pub struct ClickHouse {
49    executor: Option<Executor>,
50}
51
52impl std::fmt::Debug for ClickHouse {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("ClickHouse").field("executor", &self.executor.is_some()).finish()
55    }
56}
57
58impl ClickHouse {
59    /// A ClickHouse schema without an executor.
60    ///
61    /// PHP: `new ClickHouse()`.
62    pub fn new() -> Self {
63        ClickHouse::default()
64    }
65
66    /// `INDEX name expr TYPE algorithm[(args)] GRANULARITY n`; without an
67    /// algorithm, `TYPE minmax GRANULARITY 3`.
68    fn skip_index(&self, index: &Index) -> Result<String> {
69        let columns = index.columns.iter().map(|c| self.quote_literal(c)).collect::<Result<Vec<_>>>()?;
70        let expr = if columns.len() == 1 { columns[0].clone() } else { format!("({})", columns.join(", ")) };
71        let Some(algorithm) = index.algorithm else {
72            return Ok(format!(
73                "INDEX {} {expr} TYPE minmax GRANULARITY {}",
74                self.quote(&index.name)?,
75                index.granularity.unwrap_or(3)
76            ));
77        };
78        let mut kind = algorithm.as_str().to_owned();
79        if !index.algorithm_args.is_empty() {
80            let args: Vec<String> = index
81                .algorithm_args
82                .iter()
83                .map(|arg| match arg {
84                    Value::Str(s) => self.literal().quote(&String::from_utf8_lossy(s.as_bytes())),
85                    Value::Float(f) => Ok(names::fixed(*f)),
86                    other => Ok(crate::value::to_php_string(other)),
87                })
88                .collect::<Result<_>>()?;
89            kind.push_str(&format!("({})", args.join(", ")));
90        }
91        Ok(format!(
92            "INDEX {} {expr} TYPE {kind} GRANULARITY {}",
93            self.quote(&index.name)?,
94            index.granularity.unwrap_or(1)
95        ))
96    }
97
98    /// The engine declaration: `Name()` or `Name(args...)`.
99    fn engine(&self, engine: Engine, args: &[String]) -> Result<String> {
100        let name = engine.as_str();
101        Ok(match engine {
102            Engine::MergeTree | Engine::AggregatingMergeTree => format!("{name}()"),
103            Engine::ReplacingMergeTree => match args.first() {
104                Some(version) => format!("{name}({})", self.quote_literal(version)?),
105                None => format!("{name}()"),
106            },
107            Engine::SummingMergeTree => {
108                let columns = args.iter().map(|c| self.quote_literal(c)).collect::<Result<Vec<_>>>()?;
109                format!("{name}({})", columns.join(", "))
110            }
111            Engine::CollapsingMergeTree => {
112                format!("{name}({})", self.quote_literal(args.first().map(String::as_str).unwrap_or_default())?)
113            }
114            Engine::ReplicatedMergeTree => {
115                let at = |i: usize| self.literal().quote(args.get(i).map(String::as_str).unwrap_or_default());
116                format!("{name}({}, {})", at(0)?, at(1)?)
117            }
118            Engine::Memory | Engine::Log | Engine::TinyLog | Engine::StripeLog => name.to_owned(),
119        })
120    }
121
122    /// An element type inside `Array(...)` / `Tuple(...)`, sized by the parent column.
123    fn element_type(element: ColumnType, parent: &Column<Self>) -> Result<String> {
124        let p = &parent.def;
125        let int = |signed: &str, unsigned: &str| if p.unsigned { unsigned } else { signed }.to_owned();
126        Ok(match element {
127            ColumnType::String
128            | ColumnType::Varchar
129            | ColumnType::Relationship
130            | ColumnType::Text
131            | ColumnType::MediumText
132            | ColumnType::LongText
133            | ColumnType::Json
134            | ColumnType::Object
135            | ColumnType::Binary => "String".into(),
136            ColumnType::TinyInteger => int("Int8", "UInt8"),
137            ColumnType::SmallInteger => int("Int16", "UInt16"),
138            ColumnType::Integer => int("Int32", "UInt32"),
139            ColumnType::BigInteger | ColumnType::Id => int("Int64", "UInt64"),
140            ColumnType::Float | ColumnType::Double => "Float64".into(),
141            ColumnType::Decimal => format!("Decimal({}, {})", p.precision.unwrap_or(10), p.scale.unwrap_or(0)),
142            ColumnType::Boolean => "UInt8".into(),
143            ColumnType::Datetime | ColumnType::Timestamp => match p.precision {
144                Some(precision) if precision != 0 => format!("DateTime64({precision})"),
145                _ => "DateTime".into(),
146            },
147            ColumnType::Uuid => "UUID".into(),
148            ColumnType::Uuid7 => "FixedString(36)".into(),
149            ColumnType::Point => "Tuple(Float64, Float64)".into(),
150            ColumnType::Linestring => "Array(Tuple(Float64, Float64))".into(),
151            ColumnType::Polygon => "Array(Array(Tuple(Float64, Float64)))".into(),
152            ColumnType::Vector => "Array(Float64)".into(),
153            ColumnType::Enum
154            | ColumnType::Serial
155            | ColumnType::BigSerial
156            | ColumnType::SmallSerial
157            | ColumnType::Array
158            | ColumnType::Tuple => {
159                return Err(Error::Unsupported(format!(
160                    "Nested element type {} is not supported inside Array/Tuple.",
161                    element.as_str()
162                )));
163            }
164        })
165    }
166
167    /// `Enum8('a' = 1, 'b' = 2, ...)`.
168    fn enumeration(&self, values: &[String]) -> Result<String> {
169        let parts = values
170            .iter()
171            .enumerate()
172            .map(|(i, value)| Ok(format!("{} = {}", self.literal().quote(value)?, i + 1)))
173            .collect::<Result<Vec<_>>>()?;
174        Ok(format!("Enum8({})", parts.join(", ")))
175    }
176}
177
178impl Schema for ClickHouse {
179    fn executor(&self) -> Option<&Executor> {
180        self.executor.as_ref()
181    }
182
183    fn set_executor(&mut self, executor: Executor) -> &mut Self {
184        self.executor = Some(executor);
185        self
186    }
187
188    fn literal(&self) -> crate::StringLiteral {
189        crate::StringLiteral::BackslashUtf8
190    }
191
192    fn quote(&self, identifier: &str) -> Result<String> {
193        crate::quote(identifier, '`')
194    }
195
196    fn quote_literal(&self, identifier: &str) -> Result<String> {
197        crate::quote_literal(identifier, '`')
198    }
199
200    fn compile_column_type(&self, column: &Column<Self>) -> Result<String> {
201        let c = &column.def;
202        if let Some(length) = c.fixed_string_length {
203            let mut kind = format!("FixedString({length})");
204            if c.nullable {
205                kind = format!("Nullable({kind})");
206            }
207            if c.low_cardinality {
208                kind = format!("LowCardinality({kind})");
209            }
210            return Ok(kind);
211        }
212        if let Some(element) = c.array_element_type {
213            if c.low_cardinality {
214                return Err(Error::Unsupported(
215                    "LowCardinality is not supported inside Array(...). Wrap the element type instead.".into(),
216                ));
217            }
218            if c.nullable {
219                return Err(Error::Unsupported(
220                    "Nullable(Array(...)) is not supported in ClickHouse. Use an empty array [] to represent a missing value instead."
221                        .into(),
222                ));
223            }
224            return Ok(format!("Array({})", Self::element_type(element, column)?));
225        }
226        if !c.tuple_element_types.is_empty() {
227            if c.low_cardinality {
228                return Err(Error::Unsupported("LowCardinality is not supported on Tuple(...) columns.".into()));
229            }
230            let inner = c
231                .tuple_element_types
232                .iter()
233                .map(|element| Self::element_type(*element, column))
234                .collect::<Result<Vec<_>>>()?;
235            if c.nullable {
236                return Err(Error::Unsupported(
237                    "Nullable(Tuple(...)) is an experimental ClickHouse feature and requires allow_experimental_nullable_tuple_type = 1. Use Tuple(Nullable(T1), Nullable(T2), ...) instead."
238                        .into(),
239                ));
240            }
241            return Ok(format!("Tuple({})", inner.join(", ")));
242        }
243        let int = |signed: &str, unsigned: &str| if c.unsigned { unsigned } else { signed }.to_owned();
244        let date = || match c.precision {
245            Some(p) if p != 0 => format!("DateTime64({p})"),
246            _ => "DateTime".into(),
247        };
248        let mut kind = match c.kind {
249            ColumnType::String | ColumnType::Varchar | ColumnType::Relationship => "String".into(),
250            ColumnType::Text => "String".into(),
251            ColumnType::MediumText | ColumnType::LongText => "String".into(),
252            ColumnType::TinyInteger => int("Int8", "UInt8"),
253            ColumnType::SmallInteger => int("Int16", "UInt16"),
254            ColumnType::Integer => int("Int32", "UInt32"),
255            ColumnType::BigInteger | ColumnType::Id => int("Int64", "UInt64"),
256            ColumnType::Serial | ColumnType::BigSerial | ColumnType::SmallSerial => {
257                return Err(Error::Unsupported(
258                    "SERIAL types are not supported in ClickHouse. Reached via addColumn(); Table\\ClickHouse has no serial() factory."
259                        .into(),
260                ));
261            }
262            ColumnType::Float | ColumnType::Double => "Float64".into(),
263            ColumnType::Decimal => format!("Decimal({}, {})", c.precision.unwrap_or(10), c.scale.unwrap_or(0)),
264            ColumnType::Boolean => "UInt8".into(),
265            ColumnType::Datetime | ColumnType::Timestamp => date(),
266            ColumnType::Json | ColumnType::Object => "String".into(),
267            ColumnType::Binary => "String".into(),
268            ColumnType::Enum => self.enumeration(&c.enum_values)?,
269            ColumnType::Point => "Tuple(Float64, Float64)".into(),
270            ColumnType::Linestring => "Array(Tuple(Float64, Float64))".into(),
271            ColumnType::Polygon => "Array(Array(Tuple(Float64, Float64)))".into(),
272            ColumnType::Uuid => "UUID".into(),
273            ColumnType::Uuid7 => "FixedString(36)".into(),
274            ColumnType::Vector => "Array(Float64)".into(),
275            ColumnType::Array | ColumnType::Tuple => {
276                return Err(Error::Unsupported(
277                    "Array/Tuple columns must be declared via Table\\ClickHouse::array() or ::tuple().".into(),
278                ));
279            }
280        };
281        if c.nullable {
282            kind = format!("Nullable({kind})");
283        }
284        if c.low_cardinality {
285            kind = format!("LowCardinality({kind})");
286        }
287        Ok(kind)
288    }
289
290    fn compile_auto_increment(&self) -> &'static str {
291        ""
292    }
293
294    fn compile_unsigned(&self) -> &'static str {
295        ""
296    }
297
298    /// Name, type, default, codecs, TTL and comment.
299    fn compile_column_definition(&self, column: &Column<Self>) -> Result<String> {
300        let c = &column.def;
301        let mut out = base::column_start(self, column)?;
302        base::add_default(self, &mut out, column)?;
303        if !c.codecs.is_empty() {
304            base::add(&mut out, &["CODEC(", &c.codecs.join(", "), ")"]);
305        }
306        if let Some(ttl) = &c.ttl {
307            base::add(&mut out, &["TTL ", ttl]);
308        }
309        if let Some(comment) = &c.comment {
310            base::add(&mut out, &["COMMENT ", &self.literal().quote(comment)?]);
311        }
312        Ok(out)
313    }
314
315    fn drop_index(&self, table: &str, name: &str) -> Result<Statement> {
316        base::plain(self, format!("ALTER TABLE {} DROP INDEX {}", self.quote(table)?, self.quote(name)?))
317    }
318
319    /// Columns, renames, drops and data-skipping indexes; settings cannot change here.
320    fn compile_alter(&self, table: &Table<Self>) -> Result<Statement> {
321        let t = table.definition();
322        let mut alterations = Vec::new();
323        for column in &t.columns {
324            let keyword = if column.def.modify { "MODIFY COLUMN" } else { "ADD COLUMN" };
325            alterations.push(format!("{keyword} {}", self.compile_column_definition(column)?));
326        }
327        for rename in &t.rename_columns {
328            alterations.push(format!(
329                "RENAME COLUMN {} TO {}",
330                self.quote_literal(&rename.from)?,
331                self.quote_literal(&rename.to)?
332            ));
333        }
334        for column in &t.drop_columns {
335            alterations.push(format!("DROP COLUMN {}", self.quote_literal(column)?));
336        }
337        for name in &t.drop_indexes {
338            alterations.push(format!("DROP INDEX {}", self.quote(name)?));
339        }
340        for index in &t.indexes {
341            if index.kind != IndexType::Index {
342                return Err(Error::Unsupported(
343                    "Only data-skipping indexes (index()) are supported in ClickHouse ALTER TABLE.".into(),
344                ));
345            }
346            alterations.push(format!("ADD {}", self.skip_index(index)?));
347        }
348        if !t.settings.is_empty() {
349            return Err(Error::Unsupported(
350                "Table SETTINGS can only be set on CREATE TABLE; emit `ALTER TABLE ... MODIFY SETTING` directly to change them."
351                    .into(),
352            ));
353        }
354        if alterations.is_empty() {
355            return Err(Error::Validation("ALTER TABLE requires at least one alteration.".into()));
356        }
357        base::plain(self, format!("ALTER TABLE {} {}", self.quote(&t.name)?, alterations.join(", ")))
358    }
359
360    /// Columns and skip indexes, then `ENGINE`, `PARTITION BY`, `ORDER BY`
361    /// (the primary key when unset), `SAMPLE BY`, `TTL` and `SETTINGS`.
362    fn compile_create(&self, table: &Table<Self>, if_not_exists: bool) -> Result<Statement> {
363        let t = table.definition();
364        let mut defs = Vec::new();
365        let mut primary = Vec::new();
366        for column in &t.columns {
367            defs.push(self.compile_column_definition(column)?);
368            if column.def.primary {
369                primary.push(self.quote_literal(&column.def.name)?);
370            }
371        }
372        if !t.composite_primary_key.is_empty() && !primary.is_empty() {
373            return Err(Error::Validation(
374                "Cannot combine column-level primary() with Table::primary() composite key.".into(),
375            ));
376        }
377        if primary.is_empty() && !t.composite_primary_key.is_empty() {
378            primary = t.composite_primary_key.iter().map(|c| self.quote_literal(c)).collect::<Result<_>>()?;
379        }
380        defs.extend(t.raw_column_defs.iter().cloned());
381        for index in &t.indexes {
382            if index.kind != IndexType::Index {
383                return Err(Error::Unsupported(
384                    "Only data-skipping indexes (index()) are supported in ClickHouse CREATE TABLE.".into(),
385                ));
386            }
387            defs.push(self.skip_index(index)?);
388        }
389        let engine = t.engine.unwrap_or(Engine::MergeTree);
390        let mut sql = format!(
391            "CREATE TABLE {}{} ({}) ENGINE = {}",
392            if if_not_exists { "IF NOT EXISTS " } else { "" },
393            self.quote(&t.name)?,
394            defs.join(", "),
395            self.engine(engine, &t.engine_args)?
396        );
397        if !t.partition_expression.is_empty() {
398            sql.push_str(" PARTITION BY ");
399            sql.push_str(&t.partition_expression);
400        }
401        if engine.requires_order_by() {
402            if let Some(raw) = &t.order_by_raw {
403                sql.push_str(" ORDER BY ");
404                sql.push_str(raw);
405            } else {
406                let order = if t.order_by.is_empty() {
407                    primary
408                } else {
409                    t.order_by.iter().map(|c| self.quote_literal(c)).collect::<Result<Vec<_>>>()?
410                };
411                if order.is_empty() {
412                    sql.push_str(" ORDER BY tuple()");
413                } else {
414                    sql.push_str(&format!(" ORDER BY ({})", order.join(", ")));
415                }
416            }
417        }
418        if let Some(sample) = &t.sample_by {
419            if !engine.requires_order_by() {
420                return Err(Error::Unsupported(
421                    "SAMPLE BY is only supported on engines that take an ORDER BY clause.".into(),
422                ));
423            }
424            sql.push_str(" SAMPLE BY ");
425            sql.push_str(sample);
426        }
427        if let Some(ttl) = &t.ttl {
428            sql.push_str(" TTL ");
429            sql.push_str(ttl);
430        }
431        if !t.settings.is_empty() {
432            let pairs: Vec<String> = t.settings.iter().map(|(k, v)| format!("{k} = {v}")).collect();
433            sql.push_str(" SETTINGS ");
434            sql.push_str(&pairs.join(", "));
435        }
436        base::plain(self, sql)
437    }
438}
439
440impl column::Comment for ClickHouse {}
441impl table::ColumnAlterations for ClickHouse {}
442impl table::CompositePrimary for ClickHouse {}
443
444impl feature::TableComments for ClickHouse {
445    fn comment_on_table(&self, table: &str, comment: &str) -> Result<Statement> {
446        base::plain(
447            self,
448            format!("ALTER TABLE {} MODIFY COMMENT {}", self.quote(table)?, self.literal().quote(comment)?),
449        )
450    }
451}
452
453impl feature::ColumnComments for ClickHouse {
454    fn comment_on_column(&self, table: &str, column: &str, comment: &str) -> Result<Statement> {
455        base::plain(
456            self,
457            format!(
458                "ALTER TABLE {} COMMENT COLUMN {} {}",
459                self.quote(table)?,
460                self.quote_literal(column)?,
461                self.literal().quote(comment)?
462            ),
463        )
464    }
465}
466
467impl feature::DropPartition for ClickHouse {
468    fn drop_partition(&self, table: &str, name: &str) -> Result<Statement> {
469        base::plain(self, format!("ALTER TABLE {} DROP PARTITION {}", self.quote(table)?, self.literal().quote(name)?))
470    }
471}
472
473impl feature::Views for ClickHouse {
474    fn create_view(&self, name: &str, query: &mut dyn AnyBuilder) -> Result<Statement> {
475        base::create_view(self, "CREATE VIEW", name, query)
476    }
477
478    fn drop_view(&self, name: &str) -> Result<Statement> {
479        base::plain(self, format!("DROP VIEW {}", self.quote(name)?))
480    }
481}
482
483impl feature::Databases for ClickHouse {
484    fn create_database(&self, name: &str) -> Result<Statement> {
485        base::plain(self, format!("CREATE DATABASE {}", self.quote(name)?))
486    }
487
488    fn drop_database(&self, name: &str) -> Result<Statement> {
489        base::plain(self, format!("DROP DATABASE {}", self.quote(name)?))
490    }
491}
492
493impl feature::MaterializedViews for ClickHouse {
494    fn create_materialized_view(
495        &self,
496        name: &str,
497        body: ViewBody<'_>,
498        target_table: Option<&str>,
499        if_not_exists: bool,
500    ) -> Result<Statement> {
501        base::create_materialized_view(self, name, body, target_table, if_not_exists)
502    }
503
504    fn drop_materialized_view(&self, name: &str, if_exists: bool) -> Result<Statement> {
505        base::drop_materialized_view(self, name, if_exists)
506    }
507}