Skip to main content

operator/
expr_helper.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(feature = "enterprise")]
16pub mod trigger;
17
18use std::collections::{HashMap, HashSet};
19
20use api::helper::ColumnDataTypeWrapper;
21use api::v1::alter_database_expr::Kind as AlterDatabaseKind;
22use api::v1::alter_table_expr::Kind as AlterTableKind;
23use api::v1::column_def::{self, options_from_column_schema, try_as_column_schema};
24use api::v1::{
25    AddColumn, AddColumns, AlterDatabaseExpr, AlterTableExpr, Analyzer, ColumnDataType,
26    ColumnDataTypeExtension, CreateFlowExpr, CreateTableExpr, CreateViewExpr, DropColumn,
27    DropColumns, DropDefaults, ExpireAfter, FulltextBackend as PbFulltextBackend,
28    JsonSettings as PbJsonSettings, JsonSkippingIndexOptions, JsonTypeHint as PbJsonTypeHint,
29    ModifyColumnType, ModifyColumnTypes, RenameTable, SemanticType, SetDatabaseOptions,
30    SetDefaults, SetFulltext, SetIndex, SetIndexes, SetInverted, SetJsonSettings, SetSkipping,
31    SetTableOptions, SkippingIndexType as PbSkippingIndexType, TableName, UnsetDatabaseOptions,
32    UnsetFulltext, UnsetIndex, UnsetIndexes, UnsetInverted, UnsetSkipping, UnsetTableOptions,
33    set_index, unset_index,
34};
35use common_catalog::consts::RELATIONAL_ENGINE;
36use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
37use common_error::ext::BoxedError;
38use common_grpc_expr::util::ColumnExpr;
39use common_query::prelude::greptime_timestamp;
40use common_time::Timezone;
41use datafusion::sql::planner::object_name_to_table_reference;
42use datatypes::json::JsonSettings;
43use datatypes::prelude::ConcreteDataType;
44use datatypes::schema::{
45    COLUMN_FULLTEXT_OPT_KEY_ANALYZER, COLUMN_FULLTEXT_OPT_KEY_BACKEND,
46    COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE, COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE,
47    COLUMN_FULLTEXT_OPT_KEY_GRANULARITY, COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE,
48    COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY, COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE, COMMENT_KEY,
49    ColumnDefaultConstraint, ColumnSchema, FulltextAnalyzer, FulltextBackend, Schema,
50    SkippingIndexType,
51};
52use file_engine::FileOptions;
53use query::sql::{
54    check_file_to_table_schema_compatibility, file_column_schemas_to_table,
55    infer_file_table_schema, prepare_file_table_files,
56};
57use session::context::QueryContextRef;
58use session::table_name::table_idents_to_full_name;
59use snafu::{OptionExt, ResultExt, ensure};
60use sql::ast::{
61    ColumnDef, ColumnOption, ColumnOptionDef, Expr, Ident, ObjectName, ObjectNamePartExt,
62};
63use sql::dialect::GreptimeDbDialect;
64use sql::parser::ParserContext;
65use sql::statements::alter::{
66    AlterDatabase, AlterDatabaseOperation, AlterTable, AlterTableOperation,
67};
68use sql::statements::create::{
69    Column as SqlColumn, ColumnExtensions, CreateExternalTable, CreateFlow, CreateTable,
70    CreateView, TableConstraint,
71};
72use sql::statements::{
73    OptionMap, column_to_schema, concrete_data_type_to_sql_data_type, sql_col_to_grpc_col_def,
74    sql_data_type_to_concrete_data_type, value_to_sql_value,
75};
76use sql::util::extract_tables_from_query;
77use store_api::mito_engine_options::{COMPACTION_OVERRIDE, COMPACTION_TYPE};
78use table::requests::{
79    FILE_TABLE_META_KEY, RELATIONAL_CONNECTION_KEY, RELATIONAL_META_KEY,
80    RELATIONAL_REMOTE_TABLE_KEY, RelationalOptions, TableOptions,
81};
82use table::table_reference::TableReference;
83#[cfg(feature = "enterprise")]
84pub use trigger::to_create_trigger_task_expr;
85
86use crate::error::{
87    BuildCreateExprOnInsertionSnafu, ColumnDataTypeSnafu, ConvertColumnDefaultConstraintSnafu,
88    ConvertIdentifierSnafu, EncodeJsonSnafu, ExternalSnafu, FindNewColumnsOnInsertionSnafu,
89    IllegalPrimaryKeysDefSnafu, InferFileTableSchemaSnafu, InvalidColumnDefSnafu,
90    InvalidFlowNameSnafu, InvalidSqlSnafu, MissingRelationalOptionSnafu, NotSupportedSnafu,
91    ParseSqlSnafu, ParseSqlValueSnafu, PrepareFileTableSnafu, ReservedTimeIndexColumnSnafu, Result,
92    SchemaIncompatibleSnafu, UnrecognizedTableOptionSnafu,
93};
94
95pub fn create_table_expr_by_column_schemas(
96    table_name: &TableReference<'_>,
97    column_schemas: &[api::v1::ColumnSchema],
98    engine: &str,
99    desc: Option<&str>,
100) -> Result<CreateTableExpr> {
101    let column_exprs = ColumnExpr::from_column_schemas(column_schemas);
102    let expr = common_grpc_expr::util::build_create_table_expr(
103        None,
104        table_name,
105        column_exprs,
106        engine,
107        desc.unwrap_or("Created on insertion"),
108    )
109    .context(BuildCreateExprOnInsertionSnafu)?;
110
111    validate_create_expr(&expr)?;
112    Ok(expr)
113}
114
115pub fn extract_add_columns_expr(
116    schema: &Schema,
117    column_exprs: Vec<ColumnExpr>,
118) -> Result<Option<AddColumns>> {
119    let add_columns = common_grpc_expr::util::extract_new_columns(schema, column_exprs)
120        .context(FindNewColumnsOnInsertionSnafu)?;
121    if let Some(add_columns) = &add_columns {
122        validate_add_columns_expr(add_columns)?;
123    }
124    Ok(add_columns)
125}
126
127//   cpu float64,
128//   memory float64,
129//   TIME INDEX (ts),
130//   PRIMARY KEY(host)
131// ) WITH (location='/var/data/city.csv', format='csv');
132// ```
133// The user needs to specify the TIME INDEX column. If there is no suitable
134// column in the file to use as TIME INDEX, an additional placeholder column
135// needs to be created as the TIME INDEX, and a `DEFAULT <value>` constraint
136// should be added.
137//
138//
139// When the `CREATE EXTERNAL TABLE` statement is in inferred form, like
140// ```sql
141// CREATE EXTERNAL TABLE IF NOT EXISTS city WITH (location='/var/data/city.csv',format='csv');
142// ```
143// 1. If the TIME INDEX column can be inferred from metadata, use that column
144//    as the TIME INDEX. Otherwise,
145// 2. If a column named `greptime_timestamp` exists (with the requirement that
146//    the column is with type TIMESTAMP, otherwise an error is thrown), use
147//    that column as the TIME INDEX. Otherwise,
148// 3. Automatically create the `greptime_timestamp` column and add a `DEFAULT 0`
149//    constraint.
150pub(crate) async fn create_external_expr(
151    create: CreateExternalTable,
152    query_ctx: &QueryContextRef,
153    local_file_access: &LocalFileAccess,
154    remote_storage_access: &RemoteStorageAccess,
155) -> Result<CreateTableExpr> {
156    let (catalog_name, schema_name, table_name) =
157        table_idents_to_full_name(&create.name, query_ctx)
158            .map_err(BoxedError::new)
159            .context(ExternalSnafu)?;
160
161    if create.engine == RELATIONAL_ENGINE {
162        create_relational_expr(create, query_ctx, catalog_name, schema_name, table_name).await
163    } else {
164        create_file_expr(
165            create,
166            query_ctx,
167            local_file_access,
168            remote_storage_access,
169            catalog_name,
170            schema_name,
171            table_name,
172        )
173        .await
174    }
175}
176
177async fn create_relational_expr(
178    create: CreateExternalTable,
179    query_ctx: &QueryContextRef,
180    catalog_name: String,
181    schema_name: String,
182    table_name: String,
183) -> Result<CreateTableExpr> {
184    let connection = create
185        .options
186        .get(RELATIONAL_CONNECTION_KEY)
187        .context(MissingRelationalOptionSnafu {
188            name: RELATIONAL_CONNECTION_KEY,
189        })?
190        .to_string();
191    let remote_table = create
192        .options
193        .get(RELATIONAL_REMOTE_TABLE_KEY)
194        .context(MissingRelationalOptionSnafu {
195            name: RELATIONAL_REMOTE_TABLE_KEY,
196        })?
197        .to_string();
198
199    let remote_columns = crate::relational::fetch_mysql_columns(&connection, &remote_table).await?;
200    build_relational_expr(
201        create,
202        query_ctx,
203        catalog_name,
204        schema_name,
205        table_name,
206        RelationalOptions {
207            connection,
208            remote_table,
209        },
210        &remote_columns,
211    )
212}
213
214fn build_relational_expr(
215    create: CreateExternalTable,
216    query_ctx: &QueryContextRef,
217    catalog_name: String,
218    schema_name: String,
219    table_name: String,
220    options: RelationalOptions,
221    remote_columns: &[crate::relational::MySqlColumn],
222) -> Result<CreateTableExpr> {
223    let mut table_options = create.options.into_map();
224    let remote_names = remote_columns
225        .iter()
226        .map(|column| column.name.as_str())
227        .collect::<HashSet<_>>();
228
229    let (time_index, primary_keys, table_column_schemas, remote_column_schemas) = if !create
230        .columns
231        .is_empty()
232    {
233        // Declared form: the user lists a subset of the remote table's
234        // columns, so only those columns are mapped and validated; the rest
235        // of the remote table is ignored. No synthetic time index is
236        // appended here, so a remote column named `greptime_timestamp` is an
237        // ordinary column, not a name clash.
238        let time_index = find_time_index(&create.constraints)?;
239        let primary_keys = find_primary_keys(&create.columns, &create.constraints)?;
240        let table_column_schemas =
241            columns_to_column_schemas(&create.columns, &time_index, Some(&query_ctx.timezone()))?;
242        let declared_names = table_column_schemas
243            .iter()
244            .map(|column| column.name.as_str())
245            .collect::<HashSet<_>>();
246        for column in &table_column_schemas {
247            let is_synthetic_time_index = column.is_time_index()
248                && column.name == greptime_timestamp()
249                && !remote_names.contains(column.name.as_str());
250            if is_synthetic_time_index {
251                continue;
252            }
253            ensure!(
254                remote_names.contains(column.name.as_str()),
255                InvalidSqlSnafu {
256                    err_msg: format!("column `{}` is not found in the remote table", column.name),
257                }
258            );
259        }
260        // `INFORMATION_SCHEMA.COLUMNS` nullability is not (yet) read, so
261        // treat every remote column as nullable.
262        let remote_column_schemas: Vec<ColumnSchema> =
263            crate::relational::map_mysql_columns(remote_columns, Some(&declared_names))?
264                .into_iter()
265                .map(|column| ColumnSchema::new(column.name, column.data_type, true))
266                .collect();
267        (
268            time_index,
269            primary_keys,
270            table_column_schemas,
271            remote_column_schemas,
272        )
273    } else {
274        // Inferred form: expose all remote columns + a synthetic time
275        // index. Every remote column is mapped, so an unmappable type is
276        // rejected here. The synthetic column is reserved, so a remote
277        // column with the same name must be rejected rather than silently
278        // replaced.
279        let remote_column_schemas: Vec<ColumnSchema> =
280            crate::relational::map_mysql_columns(remote_columns, None)?
281                .into_iter()
282                .map(|column| ColumnSchema::new(column.name, column.data_type, true))
283                .collect();
284        let synthetic_time_index = greptime_timestamp();
285        ensure!(
286            !remote_column_schemas
287                .iter()
288                .any(|column| column.name == synthetic_time_index),
289            ReservedTimeIndexColumnSnafu {
290                name: synthetic_time_index.to_string(),
291            }
292        );
293        let (table_column_schemas, time_index) =
294            file_column_schemas_to_table(&remote_column_schemas);
295        // No user columns → no PRIMARY KEY to derive; external tables are read-only.
296        let primary_keys = vec![];
297        (
298            time_index,
299            primary_keys,
300            table_column_schemas,
301            remote_column_schemas,
302        )
303    };
304
305    check_file_to_table_schema_compatibility(&remote_column_schemas, &table_column_schemas)
306        .context(SchemaIncompatibleSnafu)?;
307
308    let column_defs = column_schemas_to_defs(table_column_schemas, &primary_keys)?;
309
310    let meta = options;
311    table_options.insert(
312        RELATIONAL_META_KEY.to_string(),
313        serde_json::to_string(&meta).context(EncodeJsonSnafu)?,
314    );
315    // Drop the raw options so the plaintext connection isn't persisted twice
316    // nor echoed back by `SHOW CREATE TABLE`.
317    table_options.remove(RELATIONAL_CONNECTION_KEY);
318    table_options.remove(RELATIONAL_REMOTE_TABLE_KEY);
319
320    Ok(CreateTableExpr {
321        catalog_name,
322        schema_name,
323        table_name,
324        desc: String::default(),
325        column_defs,
326        time_index,
327        primary_keys,
328        create_if_not_exists: create.if_not_exists,
329        table_options,
330        table_id: None,
331        engine: create.engine.clone(),
332    })
333}
334
335async fn create_file_expr(
336    create: CreateExternalTable,
337    query_ctx: &QueryContextRef,
338    local_file_access: &LocalFileAccess,
339    remote_storage_access: &RemoteStorageAccess,
340    catalog_name: String,
341    schema_name: String,
342    table_name: String,
343) -> Result<CreateTableExpr> {
344    let mut table_options = create.options.into_map();
345    let (object_store, files) =
346        prepare_file_table_files(&table_options, local_file_access, remote_storage_access)
347            .await
348            .context(PrepareFileTableSnafu)?;
349
350    let file_column_schemas = infer_file_table_schema(&object_store, &files, &table_options)
351        .await
352        .context(InferFileTableSchemaSnafu)?
353        .column_schemas()
354        .to_vec();
355
356    let (time_index, primary_keys, table_column_schemas) = if !create.columns.is_empty() {
357        // expanded form
358        let time_index = find_time_index(&create.constraints)?;
359        let primary_keys = find_primary_keys(&create.columns, &create.constraints)?;
360        let column_schemas =
361            columns_to_column_schemas(&create.columns, &time_index, Some(&query_ctx.timezone()))?;
362        (time_index, primary_keys, column_schemas)
363    } else {
364        // inferred form
365        let (column_schemas, time_index) = file_column_schemas_to_table(&file_column_schemas);
366        let primary_keys = vec![];
367        (time_index, primary_keys, column_schemas)
368    };
369
370    check_file_to_table_schema_compatibility(&file_column_schemas, &table_column_schemas)
371        .context(SchemaIncompatibleSnafu)?;
372
373    let meta = FileOptions {
374        files,
375        file_column_schemas,
376    };
377    table_options.insert(
378        FILE_TABLE_META_KEY.to_string(),
379        serde_json::to_string(&meta).context(EncodeJsonSnafu)?,
380    );
381
382    let column_defs = column_schemas_to_defs(table_column_schemas, &primary_keys)?;
383    Ok(CreateTableExpr {
384        catalog_name,
385        schema_name,
386        table_name,
387        desc: String::default(),
388        column_defs,
389        time_index,
390        primary_keys,
391        create_if_not_exists: create.if_not_exists,
392        table_options,
393        table_id: None,
394        engine: create.engine.clone(),
395    })
396}
397
398/// Convert `CreateTable` statement to [`CreateTableExpr`] gRPC request.
399pub fn create_to_expr(
400    create: &CreateTable,
401    query_ctx: &QueryContextRef,
402) -> Result<CreateTableExpr> {
403    let (catalog_name, schema_name, table_name) =
404        table_idents_to_full_name(&create.name, query_ctx)
405            .map_err(BoxedError::new)
406            .context(ExternalSnafu)?;
407
408    let time_index = find_time_index(&create.constraints)?;
409    let mut table_options = HashMap::from(
410        &TableOptions::try_from_iter(create.options.to_str_map())
411            .context(UnrecognizedTableOptionSnafu)?,
412    );
413
414    if table_options.contains_key(COMPACTION_TYPE) {
415        table_options.insert(COMPACTION_OVERRIDE.to_string(), "true".to_string());
416    }
417
418    let primary_keys = find_primary_keys(&create.columns, &create.constraints)?;
419
420    let expr = CreateTableExpr {
421        catalog_name,
422        schema_name,
423        table_name,
424        desc: String::default(),
425        column_defs: columns_to_expr(
426            &create.columns,
427            &time_index,
428            &primary_keys,
429            Some(&query_ctx.timezone()),
430        )?,
431        time_index,
432        primary_keys,
433        create_if_not_exists: create.if_not_exists,
434        table_options,
435        table_id: None,
436        engine: create.engine.clone(),
437    };
438
439    validate_create_expr(&expr)?;
440    Ok(expr)
441}
442
443/// Convert gRPC's [`CreateTableExpr`] back to `CreateTable` statement.
444/// You can use `create_table_expr_by_column_schemas` to create a `CreateTableExpr` from column schemas.
445///
446/// # Parameters
447///
448/// * `expr` - The `CreateTableExpr` to convert
449/// * `quote_style` - Optional quote style for identifiers (defaults to MySQL style ` backtick)
450pub fn expr_to_create(expr: &CreateTableExpr, quote_style: Option<char>) -> Result<CreateTable> {
451    let quote_style = quote_style.unwrap_or('`');
452
453    // Convert table name
454    let table_name = ObjectName(vec![sql::ast::ObjectNamePart::Identifier(
455        sql::ast::Ident::with_quote(quote_style, &expr.table_name),
456    )]);
457
458    // Convert columns
459    let mut columns = Vec::with_capacity(expr.column_defs.len());
460    for column_def in &expr.column_defs {
461        let column_schema = try_as_column_schema(column_def).context(InvalidColumnDefSnafu {
462            column: &column_def.name,
463        })?;
464
465        let mut options = Vec::new();
466
467        // Add NULL/NOT NULL constraint
468        if column_def.is_nullable {
469            options.push(ColumnOptionDef {
470                name: None,
471                option: ColumnOption::Null,
472            });
473        } else {
474            options.push(ColumnOptionDef {
475                name: None,
476                option: ColumnOption::NotNull,
477            });
478        }
479
480        // Add DEFAULT constraint if present
481        if let Some(default_constraint) = column_schema.default_constraint() {
482            let expr = match default_constraint {
483                ColumnDefaultConstraint::Value(v) => {
484                    Expr::Value(value_to_sql_value(v).context(ParseSqlValueSnafu)?.into())
485                }
486                ColumnDefaultConstraint::Function(func_expr) => {
487                    ParserContext::parse_function(func_expr, &GreptimeDbDialect {})
488                        .context(ParseSqlSnafu)?
489                }
490            };
491            options.push(ColumnOptionDef {
492                name: None,
493                option: ColumnOption::Default(expr),
494            });
495        }
496
497        // Add COMMENT if present
498        if !column_def.comment.is_empty() {
499            options.push(ColumnOptionDef {
500                name: None,
501                option: ColumnOption::Comment(column_def.comment.clone()),
502            });
503        }
504
505        // Note: We don't add inline PRIMARY KEY options here,
506        // we'll handle all primary keys as constraints instead for consistency
507
508        // Handle column extensions (fulltext, inverted index, skipping index)
509        let mut extensions = ColumnExtensions::default();
510
511        // Add fulltext index options if present
512        if let Ok(Some(opt)) = column_schema.fulltext_options()
513            && opt.enable
514        {
515            let mut map = HashMap::from([
516                (
517                    COLUMN_FULLTEXT_OPT_KEY_ANALYZER.to_string(),
518                    opt.analyzer.to_string(),
519                ),
520                (
521                    COLUMN_FULLTEXT_OPT_KEY_CASE_SENSITIVE.to_string(),
522                    opt.case_sensitive.to_string(),
523                ),
524                (
525                    COLUMN_FULLTEXT_OPT_KEY_BACKEND.to_string(),
526                    opt.backend.to_string(),
527                ),
528            ]);
529            if opt.backend == FulltextBackend::Bloom {
530                map.insert(
531                    COLUMN_FULLTEXT_OPT_KEY_GRANULARITY.to_string(),
532                    opt.granularity.to_string(),
533                );
534                map.insert(
535                    COLUMN_FULLTEXT_OPT_KEY_FALSE_POSITIVE_RATE.to_string(),
536                    opt.false_positive_rate().to_string(),
537                );
538            }
539            extensions.fulltext_index_options = Some(map.into());
540        }
541
542        // Add skipping index options if present
543        if let Ok(Some(opt)) = column_schema.skipping_index_options() {
544            let map = HashMap::from([
545                (
546                    COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY.to_string(),
547                    opt.granularity.to_string(),
548                ),
549                (
550                    COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE.to_string(),
551                    opt.false_positive_rate().to_string(),
552                ),
553                (
554                    COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE.to_string(),
555                    opt.index_type.to_string(),
556                ),
557            ]);
558            extensions.skipping_index_options = Some(map.into());
559        }
560
561        // Add inverted index options if present
562        if column_schema.is_inverted_indexed() {
563            extensions.inverted_index_options = Some(HashMap::new().into());
564        }
565
566        if let Some(opt) = column_schema
567            .compression_options()
568            .map_err(BoxedError::new)
569            .context(ExternalSnafu)?
570        {
571            extensions.compression_options = Some(opt.to_options_map().into());
572        }
573
574        let sql_column = SqlColumn {
575            column_def: ColumnDef {
576                name: Ident::with_quote(quote_style, &column_def.name),
577                data_type: concrete_data_type_to_sql_data_type(&column_schema.data_type)
578                    .context(ParseSqlSnafu)?,
579                options,
580            },
581            extensions,
582        };
583
584        columns.push(sql_column);
585    }
586
587    // Convert constraints
588    let mut constraints = Vec::new();
589
590    // Add TIME INDEX constraint
591    constraints.push(TableConstraint::TimeIndex {
592        column: Ident::with_quote(quote_style, &expr.time_index),
593    });
594
595    // Add PRIMARY KEY constraint (always add as constraint for consistency)
596    if !expr.primary_keys.is_empty() {
597        let primary_key_columns: Vec<Ident> = expr
598            .primary_keys
599            .iter()
600            .map(|pk| Ident::with_quote(quote_style, pk))
601            .collect();
602
603        constraints.push(TableConstraint::PrimaryKey {
604            columns: primary_key_columns,
605        });
606    }
607
608    // Convert table options
609    let mut options = OptionMap::default();
610    for (key, value) in &expr.table_options {
611        options.insert(key.clone(), value.clone());
612    }
613
614    Ok(CreateTable {
615        if_not_exists: expr.create_if_not_exists,
616        table_id: expr.table_id.as_ref().map(|tid| tid.id).unwrap_or(0),
617        name: table_name,
618        columns,
619        engine: expr.engine.clone(),
620        constraints,
621        options,
622        partitions: None,
623    })
624}
625
626/// Validate the [`CreateTableExpr`] request.
627pub fn validate_create_expr(create: &CreateTableExpr) -> Result<()> {
628    // construct column list
629    let mut column_to_indices = HashMap::with_capacity(create.column_defs.len());
630    for (idx, column) in create.column_defs.iter().enumerate() {
631        if let Some(indices) = column_to_indices.get(&column.name) {
632            return InvalidSqlSnafu {
633                err_msg: format!(
634                    "column name `{}` is duplicated at index {} and {}",
635                    column.name, indices, idx
636                ),
637            }
638            .fail();
639        }
640        column_to_indices.insert(&column.name, idx);
641    }
642
643    // verify time_index exists
644    let time_index_idx =
645        column_to_indices
646            .get(&create.time_index)
647            .with_context(|| InvalidSqlSnafu {
648                err_msg: format!(
649                    "column name `{}` is not found in column list",
650                    create.time_index
651                ),
652            })?;
653
654    // verify time_index is a timestamp column
655    let time_index_column = &create.column_defs[*time_index_idx];
656    let data_type = ConcreteDataType::from(
657        ColumnDataTypeWrapper::try_new(
658            time_index_column.data_type,
659            time_index_column.datatype_extension.clone(),
660        )
661        .context(ColumnDataTypeSnafu)?,
662    );
663    ensure!(
664        data_type.is_timestamp(),
665        InvalidSqlSnafu {
666            err_msg: format!(
667                "column `{}` is not a timestamp type, it can't be used as time index",
668                create.time_index
669            ),
670        }
671    );
672
673    // verify primary_key exists
674    for pk in &create.primary_keys {
675        let _ = column_to_indices
676            .get(&pk)
677            .with_context(|| InvalidSqlSnafu {
678                err_msg: format!("column name `{}` is not found in column list", pk),
679            })?;
680    }
681
682    // construct primary_key set
683    let mut pk_set = HashSet::new();
684    for pk in &create.primary_keys {
685        if !pk_set.insert(pk) {
686            return InvalidSqlSnafu {
687                err_msg: format!("column name `{}` is duplicated in primary keys", pk),
688            }
689            .fail();
690        }
691    }
692
693    // verify time index is not primary key
694    if pk_set.contains(&create.time_index) {
695        return InvalidSqlSnafu {
696            err_msg: format!(
697                "column name `{}` is both primary key and time index",
698                create.time_index
699            ),
700        }
701        .fail();
702    }
703
704    for column in &create.column_defs {
705        // verify do not contain interval type column issue #3235
706        if is_interval_type(&column.data_type()) {
707            return InvalidSqlSnafu {
708                err_msg: format!(
709                    "column name `{}` is interval type, which is not supported",
710                    column.name
711                ),
712            }
713            .fail();
714        }
715        // verify do not contain datetime type column issue #5489
716        if is_date_time_type(&column.data_type()) {
717            return InvalidSqlSnafu {
718                err_msg: format!(
719                    "column name `{}` is datetime type, which is not supported, please use `timestamp` type instead",
720                    column.name
721                ),
722            }
723            .fail();
724        }
725    }
726    Ok(())
727}
728
729fn validate_add_columns_expr(add_columns: &AddColumns) -> Result<()> {
730    for add_column in &add_columns.add_columns {
731        let Some(column_def) = &add_column.column_def else {
732            continue;
733        };
734        if is_date_time_type(&column_def.data_type()) {
735            return InvalidSqlSnafu {
736                    err_msg: format!("column name `{}` is datetime type, which is not supported, please use `timestamp` type instead", column_def.name),
737                }
738                .fail();
739        }
740        if is_interval_type(&column_def.data_type()) {
741            return InvalidSqlSnafu {
742                err_msg: format!(
743                    "column name `{}` is interval type, which is not supported",
744                    column_def.name
745                ),
746            }
747            .fail();
748        }
749    }
750    Ok(())
751}
752
753fn is_date_time_type(data_type: &ColumnDataType) -> bool {
754    matches!(data_type, ColumnDataType::Datetime)
755}
756
757fn is_interval_type(data_type: &ColumnDataType) -> bool {
758    matches!(
759        data_type,
760        ColumnDataType::IntervalYearMonth
761            | ColumnDataType::IntervalDayTime
762            | ColumnDataType::IntervalMonthDayNano
763    )
764}
765
766fn find_primary_keys(
767    columns: &[SqlColumn],
768    constraints: &[TableConstraint],
769) -> Result<Vec<String>> {
770    let columns_pk = columns
771        .iter()
772        .filter_map(|x| {
773            if x.options()
774                .iter()
775                .any(|o| matches!(o.option, ColumnOption::PrimaryKey(_)))
776            {
777                Some(x.name().value.clone())
778            } else {
779                None
780            }
781        })
782        .collect::<Vec<String>>();
783
784    ensure!(
785        columns_pk.len() <= 1,
786        IllegalPrimaryKeysDefSnafu {
787            msg: "not allowed to inline multiple primary keys in columns options"
788        }
789    );
790
791    let constraints_pk = constraints
792        .iter()
793        .filter_map(|constraint| match constraint {
794            TableConstraint::PrimaryKey { columns, .. } => {
795                Some(columns.iter().map(|ident| ident.value.clone()))
796            }
797            _ => None,
798        })
799        .flatten()
800        .collect::<Vec<String>>();
801
802    ensure!(
803        columns_pk.is_empty() || constraints_pk.is_empty(),
804        IllegalPrimaryKeysDefSnafu {
805            msg: "found definitions of primary keys in multiple places"
806        }
807    );
808
809    let mut primary_keys = Vec::with_capacity(columns_pk.len() + constraints_pk.len());
810    primary_keys.extend(columns_pk);
811    primary_keys.extend(constraints_pk);
812    Ok(primary_keys)
813}
814
815pub fn find_time_index(constraints: &[TableConstraint]) -> Result<String> {
816    let time_index = constraints
817        .iter()
818        .filter_map(|constraint| match constraint {
819            TableConstraint::TimeIndex { column, .. } => Some(&column.value),
820            _ => None,
821        })
822        .collect::<Vec<&String>>();
823    ensure!(
824        time_index.len() == 1,
825        InvalidSqlSnafu {
826            err_msg: "must have one and only one TimeIndex columns",
827        }
828    );
829    Ok(time_index[0].clone())
830}
831
832fn columns_to_expr(
833    column_defs: &[SqlColumn],
834    time_index: &str,
835    primary_keys: &[String],
836    timezone: Option<&Timezone>,
837) -> Result<Vec<api::v1::ColumnDef>> {
838    let column_schemas = columns_to_column_schemas(column_defs, time_index, timezone)?;
839    column_schemas_to_defs(column_schemas, primary_keys)
840}
841
842fn columns_to_column_schemas(
843    columns: &[SqlColumn],
844    time_index: &str,
845    timezone: Option<&Timezone>,
846) -> Result<Vec<ColumnSchema>> {
847    columns
848        .iter()
849        .map(|c| column_to_schema(c, time_index, timezone).context(ParseSqlSnafu))
850        .collect::<Result<Vec<ColumnSchema>>>()
851}
852
853// TODO(weny): refactor this function to use `try_as_column_def`
854pub fn column_schemas_to_defs(
855    column_schemas: Vec<ColumnSchema>,
856    primary_keys: &[String],
857) -> Result<Vec<api::v1::ColumnDef>> {
858    let column_datatypes: Vec<(ColumnDataType, Option<ColumnDataTypeExtension>)> = column_schemas
859        .iter()
860        .map(|c| {
861            ColumnDataTypeWrapper::try_from(c.data_type.clone())
862                .map(|w| w.to_parts())
863                .context(ColumnDataTypeSnafu)
864        })
865        .collect::<Result<Vec<_>>>()?;
866
867    column_schemas
868        .iter()
869        .zip(column_datatypes)
870        .map(|(schema, datatype)| {
871            let semantic_type = if schema.is_time_index() {
872                SemanticType::Timestamp
873            } else if primary_keys.contains(&schema.name) {
874                SemanticType::Tag
875            } else {
876                SemanticType::Field
877            } as i32;
878            let comment = schema
879                .metadata()
880                .get(COMMENT_KEY)
881                .cloned()
882                .unwrap_or_default();
883
884            Ok(api::v1::ColumnDef {
885                name: schema.name.clone(),
886                data_type: datatype.0 as i32,
887                is_nullable: schema.is_nullable(),
888                default_constraint: match schema.default_constraint() {
889                    None => vec![],
890                    Some(v) => {
891                        v.clone()
892                            .try_into()
893                            .context(ConvertColumnDefaultConstraintSnafu {
894                                column_name: &schema.name,
895                            })?
896                    }
897                },
898                semantic_type,
899                comment,
900                datatype_extension: datatype.1,
901                options: options_from_column_schema(schema),
902            })
903        })
904        .collect()
905}
906
907#[derive(Debug, Clone, PartialEq, Eq)]
908pub struct RepartitionRequest {
909    pub catalog_name: String,
910    pub schema_name: String,
911    pub table_name: String,
912    pub source: RepartitionSource,
913    pub into_exprs: Vec<Expr>,
914    pub options: OptionMap,
915}
916
917#[derive(Debug, Clone, PartialEq, Eq)]
918pub enum RepartitionSource {
919    Partitions {
920        from_exprs: Vec<Expr>,
921        target_partition_columns: Option<Vec<String>>,
922    },
923    Unpartitioned {
924        partition_columns: Vec<String>,
925    },
926}
927
928pub(crate) fn to_repartition_request(
929    alter_table: AlterTable,
930    query_ctx: &QueryContextRef,
931) -> Result<RepartitionRequest> {
932    let AlterTable {
933        table_name,
934        alter_operation,
935        options,
936    } = alter_table;
937
938    let (catalog_name, schema_name, table_name) = table_idents_to_full_name(&table_name, query_ctx)
939        .map_err(BoxedError::new)
940        .context(ExternalSnafu)?;
941
942    let (source, into_exprs) = match alter_operation {
943        AlterTableOperation::Repartition { operation } => (
944            RepartitionSource::Partitions {
945                from_exprs: operation.from_exprs,
946                target_partition_columns: operation.partition_columns.map(|columns| {
947                    columns
948                        .into_iter()
949                        .map(|ident| ident.value)
950                        .collect::<Vec<_>>()
951                }),
952            },
953            operation.into_exprs,
954        ),
955        AlterTableOperation::Partition { partitions } => (
956            RepartitionSource::Unpartitioned {
957                partition_columns: partitions
958                    .column_list
959                    .into_iter()
960                    .map(|ident| ident.value)
961                    .collect(),
962            },
963            partitions.exprs,
964        ),
965        _ => {
966            return InvalidSqlSnafu {
967                err_msg: "expected REPARTITION or PARTITION operation",
968            }
969            .fail();
970        }
971    };
972
973    Ok(RepartitionRequest {
974        catalog_name,
975        schema_name,
976        table_name,
977        source,
978        into_exprs,
979        options,
980    })
981}
982
983fn json_settings_to_proto(settings: JsonSettings) -> Result<PbJsonSettings> {
984    let (type_hints, max_auto_expanded_paths) = settings.into_parts();
985    let type_hints = type_hints
986        .into_iter()
987        .map(|hint| {
988            let (data_type, datatype_extension) = ColumnDataTypeWrapper::try_from(hint.data_type)
989                .map(|w| w.to_parts())
990                .context(ColumnDataTypeSnafu)?;
991
992            Ok(PbJsonTypeHint {
993                path: hint.path,
994                data_type: data_type as i32,
995                datatype_extension,
996                inverted_index: hint.inverted_index,
997                fulltext_index: hint
998                    .fulltext_index
999                    .map(column_def::json_fulltext_options_to_proto),
1000                skipping_index: hint.skipping_index.map(|options| JsonSkippingIndexOptions {
1001                    granularity: options.granularity,
1002                    index_type: match options.index_type {
1003                        SkippingIndexType::BloomFilter => PbSkippingIndexType::BloomFilter.into(),
1004                    },
1005                    false_positive_rate: options.false_positive_rate(),
1006                }),
1007            })
1008        })
1009        .collect::<Result<Vec<_>>>()?;
1010
1011    Ok(PbJsonSettings {
1012        type_hints,
1013        max_auto_expanded_paths,
1014    })
1015}
1016
1017/// Converts a SQL alter table statement into a gRPC alter table expression.
1018pub(crate) fn to_alter_table_expr(
1019    alter_table: AlterTable,
1020    query_ctx: &QueryContextRef,
1021) -> Result<AlterTableExpr> {
1022    let (catalog_name, schema_name, table_name) =
1023        table_idents_to_full_name(alter_table.table_name(), query_ctx)
1024            .map_err(BoxedError::new)
1025            .context(ExternalSnafu)?;
1026
1027    // SQL must not reach the gRPC entry point's default-schema fallback.
1028    ensure!(
1029        !schema_name.is_empty(),
1030        crate::error::SchemaNotFoundSnafu {
1031            schema_info: &schema_name
1032        }
1033    );
1034
1035    let kind = match alter_table.alter_operation {
1036        AlterTableOperation::AddConstraint(_) => {
1037            return NotSupportedSnafu {
1038                feat: "ADD CONSTRAINT",
1039            }
1040            .fail();
1041        }
1042        AlterTableOperation::AddColumns { add_columns } => AlterTableKind::AddColumns(AddColumns {
1043            add_columns: add_columns
1044                .into_iter()
1045                .map(|add_column| {
1046                    let column_def =
1047                        sql_col_to_grpc_col_def(&add_column.column, Some(&query_ctx.timezone()))
1048                            .map_err(BoxedError::new)
1049                            .context(ExternalSnafu)?;
1050                    if is_interval_type(&column_def.data_type()) {
1051                        return NotSupportedSnafu {
1052                            feat: "Add column with interval type",
1053                        }
1054                        .fail();
1055                    }
1056                    Ok(AddColumn {
1057                        column_def: Some(column_def),
1058                        location: add_column.location.as_ref().map(From::from),
1059                        add_if_not_exists: add_column.add_if_not_exists,
1060                    })
1061                })
1062                .collect::<Result<Vec<AddColumn>>>()?,
1063        }),
1064        AlterTableOperation::ModifyColumnType {
1065            column_name,
1066            target_type,
1067            ..
1068        } => {
1069            let target_type =
1070                sql_data_type_to_concrete_data_type(&target_type).context(ParseSqlSnafu)?;
1071
1072            // Currently disallow modify column type to json2.
1073            if target_type.is_json2() {
1074                return NotSupportedSnafu {
1075                    feat: "ALTER TABLE MODIFY COLUMN to JSON2 type",
1076                }
1077                .fail();
1078            }
1079
1080            let (target_type, target_type_extension) = ColumnDataTypeWrapper::try_from(target_type)
1081                .map(|w| w.to_parts())
1082                .context(ColumnDataTypeSnafu)?;
1083            if is_interval_type(&target_type) {
1084                return NotSupportedSnafu {
1085                    feat: "Modify column type to interval type",
1086                }
1087                .fail();
1088            }
1089            AlterTableKind::ModifyColumnTypes(ModifyColumnTypes {
1090                modify_column_types: vec![ModifyColumnType {
1091                    column_name: column_name.value,
1092                    target_type: target_type as i32,
1093                    target_type_extension,
1094                }],
1095            })
1096        }
1097        AlterTableOperation::SetJsonSettings {
1098            column_name,
1099            json2_options,
1100        } => {
1101            let settings = match json2_options {
1102                Some(options) => options.build_json_settings().context(ParseSqlSnafu)?,
1103                None => datatypes::json::JsonSettings::new_v2(),
1104            };
1105
1106            AlterTableKind::SetJsonSettings(SetJsonSettings {
1107                column_name: column_name.value,
1108                settings: Some(json_settings_to_proto(settings)?),
1109            })
1110        }
1111        AlterTableOperation::DropColumn { name } => AlterTableKind::DropColumns(DropColumns {
1112            drop_columns: vec![DropColumn {
1113                name: name.value.clone(),
1114            }],
1115        }),
1116        AlterTableOperation::RenameTable { new_table_name } => {
1117            AlterTableKind::RenameTable(RenameTable {
1118                new_table_name: new_table_name.clone(),
1119            })
1120        }
1121        AlterTableOperation::SetTableOptions { options } => {
1122            AlterTableKind::SetTableOptions(SetTableOptions {
1123                table_options: options.into_iter().map(Into::into).collect(),
1124            })
1125        }
1126        AlterTableOperation::UnsetTableOptions { keys } => {
1127            AlterTableKind::UnsetTableOptions(UnsetTableOptions { keys })
1128        }
1129        AlterTableOperation::Repartition { .. } => {
1130            return NotSupportedSnafu {
1131                feat: "ALTER TABLE ... REPARTITION",
1132            }
1133            .fail();
1134        }
1135        AlterTableOperation::Partition { .. } => {
1136            return NotSupportedSnafu {
1137                feat: "ALTER TABLE ... PARTITION ON COLUMNS",
1138            }
1139            .fail();
1140        }
1141        AlterTableOperation::SetIndex { options } => {
1142            let option = match options {
1143                sql::statements::alter::SetIndexOperation::Fulltext {
1144                    column_name,
1145                    options,
1146                } => SetIndex {
1147                    options: Some(set_index::Options::Fulltext(SetFulltext {
1148                        column_name: column_name.value,
1149                        enable: options.enable,
1150                        analyzer: match options.analyzer {
1151                            FulltextAnalyzer::English => Analyzer::English.into(),
1152                            FulltextAnalyzer::Chinese => Analyzer::Chinese.into(),
1153                        },
1154                        case_sensitive: options.case_sensitive,
1155                        backend: match options.backend {
1156                            FulltextBackend::Bloom => PbFulltextBackend::Bloom.into(),
1157                            FulltextBackend::Tantivy => PbFulltextBackend::Tantivy.into(),
1158                        },
1159                        granularity: options.granularity as u64,
1160                        false_positive_rate: options.false_positive_rate(),
1161                    })),
1162                },
1163                sql::statements::alter::SetIndexOperation::Inverted { column_name } => SetIndex {
1164                    options: Some(set_index::Options::Inverted(SetInverted {
1165                        column_name: column_name.value,
1166                    })),
1167                },
1168                sql::statements::alter::SetIndexOperation::Skipping {
1169                    column_name,
1170                    options,
1171                } => SetIndex {
1172                    options: Some(set_index::Options::Skipping(SetSkipping {
1173                        column_name: column_name.value,
1174                        enable: true,
1175                        granularity: options.granularity as u64,
1176                        false_positive_rate: options.false_positive_rate(),
1177                        skipping_index_type: match options.index_type {
1178                            SkippingIndexType::BloomFilter => {
1179                                PbSkippingIndexType::BloomFilter.into()
1180                            }
1181                        },
1182                    })),
1183                },
1184            };
1185            AlterTableKind::SetIndexes(SetIndexes {
1186                set_indexes: vec![option],
1187            })
1188        }
1189        AlterTableOperation::UnsetIndex { options } => {
1190            let option = match options {
1191                sql::statements::alter::UnsetIndexOperation::Fulltext { column_name } => {
1192                    UnsetIndex {
1193                        options: Some(unset_index::Options::Fulltext(UnsetFulltext {
1194                            column_name: column_name.value,
1195                        })),
1196                    }
1197                }
1198                sql::statements::alter::UnsetIndexOperation::Inverted { column_name } => {
1199                    UnsetIndex {
1200                        options: Some(unset_index::Options::Inverted(UnsetInverted {
1201                            column_name: column_name.value,
1202                        })),
1203                    }
1204                }
1205                sql::statements::alter::UnsetIndexOperation::Skipping { column_name } => {
1206                    UnsetIndex {
1207                        options: Some(unset_index::Options::Skipping(UnsetSkipping {
1208                            column_name: column_name.value,
1209                        })),
1210                    }
1211                }
1212            };
1213
1214            AlterTableKind::UnsetIndexes(UnsetIndexes {
1215                unset_indexes: vec![option],
1216            })
1217        }
1218        AlterTableOperation::DropDefaults { columns } => {
1219            AlterTableKind::DropDefaults(DropDefaults {
1220                drop_defaults: columns
1221                    .into_iter()
1222                    .map(|col| {
1223                        let column_name = col.0.to_string();
1224                        Ok(api::v1::DropDefault { column_name })
1225                    })
1226                    .collect::<Result<Vec<_>>>()?,
1227            })
1228        }
1229        AlterTableOperation::SetDefaults { defaults } => AlterTableKind::SetDefaults(SetDefaults {
1230            set_defaults: defaults
1231                .into_iter()
1232                .map(|col| {
1233                    let column_name = col.column_name.to_string();
1234                    let default_constraint = serde_json::to_string(&col.default_constraint)
1235                        .context(EncodeJsonSnafu)?
1236                        .into_bytes();
1237                    Ok(api::v1::SetDefault {
1238                        column_name,
1239                        default_constraint,
1240                    })
1241                })
1242                .collect::<Result<Vec<_>>>()?,
1243        }),
1244    };
1245
1246    Ok(AlterTableExpr {
1247        catalog_name,
1248        schema_name,
1249        table_name,
1250        kind: Some(kind),
1251    })
1252}
1253
1254/// Try to cast the `[AlterDatabase]` statement into gRPC `[AlterDatabaseExpr]`.
1255pub fn to_alter_database_expr(
1256    alter_database: AlterDatabase,
1257    query_ctx: &QueryContextRef,
1258) -> Result<AlterDatabaseExpr> {
1259    let catalog = query_ctx.current_catalog();
1260    let schema = alter_database.database_name;
1261
1262    let kind = match alter_database.alter_operation {
1263        AlterDatabaseOperation::SetDatabaseOption { options } => {
1264            let options = options.into_iter().map(Into::into).collect();
1265            AlterDatabaseKind::SetDatabaseOptions(SetDatabaseOptions {
1266                set_database_options: options,
1267            })
1268        }
1269        AlterDatabaseOperation::UnsetDatabaseOption { keys } => {
1270            AlterDatabaseKind::UnsetDatabaseOptions(UnsetDatabaseOptions { keys })
1271        }
1272    };
1273
1274    Ok(AlterDatabaseExpr {
1275        catalog_name: catalog.to_string(),
1276        schema_name: schema.to_string(),
1277        kind: Some(kind),
1278    })
1279}
1280
1281/// Try to cast the `[CreateViewExpr]` statement into gRPC `[CreateViewExpr]`.
1282pub fn to_create_view_expr(
1283    stmt: CreateView,
1284    logical_plan: Vec<u8>,
1285    table_names: Vec<TableName>,
1286    columns: Vec<String>,
1287    plan_columns: Vec<String>,
1288    definition: String,
1289    query_ctx: QueryContextRef,
1290) -> Result<CreateViewExpr> {
1291    let (catalog_name, schema_name, view_name) = table_idents_to_full_name(&stmt.name, &query_ctx)
1292        .map_err(BoxedError::new)
1293        .context(ExternalSnafu)?;
1294
1295    let expr = CreateViewExpr {
1296        catalog_name,
1297        schema_name,
1298        view_name,
1299        logical_plan,
1300        create_if_not_exists: stmt.if_not_exists,
1301        or_replace: stmt.or_replace,
1302        table_names,
1303        columns,
1304        plan_columns,
1305        definition,
1306    };
1307
1308    Ok(expr)
1309}
1310
1311pub fn to_create_flow_task_expr(
1312    create_flow: CreateFlow,
1313    query_ctx: &QueryContextRef,
1314) -> Result<CreateFlowExpr> {
1315    // retrieve sink table name
1316    let sink_table_ref = object_name_to_table_reference(create_flow.sink_table_name.clone(), true)
1317        .with_context(|_| ConvertIdentifierSnafu {
1318            ident: create_flow.sink_table_name.to_string(),
1319        })?;
1320    let catalog = sink_table_ref
1321        .catalog()
1322        .unwrap_or(query_ctx.current_catalog())
1323        .to_string();
1324    let schema = sink_table_ref
1325        .schema()
1326        .map(|s| s.to_owned())
1327        .unwrap_or(query_ctx.current_schema());
1328
1329    ensure!(
1330        !schema.is_empty(),
1331        crate::error::SchemaNotFoundSnafu {
1332            schema_info: &schema
1333        }
1334    );
1335
1336    let sink_table_name = TableName {
1337        catalog_name: catalog,
1338        schema_name: schema,
1339        table_name: sink_table_ref.table().to_string(),
1340    };
1341
1342    let source_table_names = extract_tables_from_query(&create_flow.query)
1343        .map(|name| {
1344            let reference =
1345                object_name_to_table_reference(name.clone(), true).with_context(|_| {
1346                    ConvertIdentifierSnafu {
1347                        ident: name.to_string(),
1348                    }
1349                })?;
1350            let catalog = reference
1351                .catalog()
1352                .unwrap_or(query_ctx.current_catalog())
1353                .to_string();
1354            let schema = reference
1355                .schema()
1356                .map(|s| s.to_string())
1357                .unwrap_or(query_ctx.current_schema());
1358
1359            ensure!(
1360                !schema.is_empty(),
1361                crate::error::SchemaNotFoundSnafu {
1362                    schema_info: &schema
1363                }
1364            );
1365
1366            let table_name = TableName {
1367                catalog_name: catalog,
1368                schema_name: schema,
1369                table_name: reference.table().to_string(),
1370            };
1371            Ok(table_name)
1372        })
1373        .collect::<Result<Vec<_>>>()?;
1374
1375    let eval_interval = create_flow.eval_interval;
1376
1377    let flow_options = stringify_flow_options(create_flow.flow_options)?;
1378    Ok(CreateFlowExpr {
1379        catalog_name: query_ctx.current_catalog().to_string(),
1380        flow_name: sanitize_flow_name(create_flow.flow_name)?,
1381        source_table_names,
1382        sink_table_name: Some(sink_table_name),
1383        or_replace: create_flow.or_replace,
1384        create_if_not_exists: create_flow.if_not_exists,
1385        expire_after: create_flow.expire_after.map(|value| ExpireAfter { value }),
1386        eval_interval: eval_interval.map(|seconds| api::v1::EvalInterval { seconds }),
1387        comment: create_flow.comment.unwrap_or_default(),
1388        sql: create_flow.query.to_string(),
1389        flow_options,
1390    })
1391}
1392
1393fn stringify_flow_options(flow_options: OptionMap) -> Result<HashMap<String, String>> {
1394    let options_len = flow_options.len();
1395    let flow_options = flow_options.into_map();
1396    ensure!(
1397        flow_options.len() == options_len,
1398        InvalidSqlSnafu {
1399            err_msg: "flow options only support scalar string-compatible values".to_string(),
1400        }
1401    );
1402    Ok(flow_options)
1403}
1404
1405/// sanitize the flow name, remove possible quotes
1406fn sanitize_flow_name(mut flow_name: ObjectName) -> Result<String> {
1407    ensure!(
1408        flow_name.0.len() == 1,
1409        InvalidFlowNameSnafu {
1410            name: flow_name.to_string(),
1411        }
1412    );
1413    // safety: we've checked flow_name.0 has exactly one element.
1414    Ok(flow_name.0.swap_remove(0).to_string_unquoted())
1415}
1416
1417#[cfg(test)]
1418mod tests {
1419    use std::collections::HashMap;
1420
1421    use crate::error::Error;
1422    use crate::relational::{MySqlColumn, MySqlColumnType};
1423    use api::v1::{SetDatabaseOptions, UnsetDatabaseOptions};
1424    use datatypes::extension::json::is_json2_extension_type;
1425    use datatypes::json::{JsonSettings, JsonTypeHint};
1426    use datatypes::schema::{FulltextOptions, SkippingIndexOptions};
1427    use datatypes::value::Value;
1428    use session::context::{QueryContext, QueryContextBuilder};
1429    use sql::dialect::GreptimeDbDialect;
1430    use sql::parser::{ParseOptions, ParserContext};
1431    use sql::statements::statement::Statement;
1432    use store_api::region_request::{AlterKind as RegionAlterKind, RegionAlterRequest};
1433    use store_api::storage::ColumnDefaultConstraint;
1434
1435    use super::*;
1436
1437    #[test]
1438    fn test_to_alter_add_json2_column_preserves_extension() {
1439        let sql = "ALTER TABLE monitor ADD COLUMN payload JSON2;";
1440        let stmt =
1441            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1442                .unwrap()
1443                .pop()
1444                .unwrap();
1445        let Statement::AlterTable(alter_table) = stmt else {
1446            unreachable!()
1447        };
1448
1449        let expr = to_alter_table_expr(alter_table, &QueryContext::arc()).unwrap();
1450        let AlterTableKind::AddColumns(AddColumns { add_columns, .. }) = expr.kind.unwrap() else {
1451            unreachable!()
1452        };
1453        let column_def = add_columns[0].column_def.as_ref().unwrap();
1454        let column_schema = try_as_column_schema(column_def).unwrap();
1455        let schema = Schema::new(vec![column_schema]);
1456
1457        assert!(is_json2_extension_type(&schema.arrow_schema().fields()[0]));
1458    }
1459
1460    #[test]
1461    fn test_to_alter_add_json2_column_preserves_settings() {
1462        let sql = "ALTER TABLE monitor ADD COLUMN payload JSON2(max_auto_expanded_paths = 0, service STRING, nested.value BIGINT)";
1463        let stmt =
1464            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1465                .unwrap()
1466                .pop()
1467                .unwrap();
1468        let Statement::AlterTable(alter_table) = stmt else {
1469            unreachable!()
1470        };
1471        let expr = to_alter_table_expr(alter_table, &QueryContext::arc()).unwrap();
1472        let AlterTableKind::AddColumns(AddColumns { add_columns, .. }) = expr.kind.unwrap() else {
1473            unreachable!()
1474        };
1475        let column_schema =
1476            try_as_column_schema(add_columns[0].column_def.as_ref().unwrap()).unwrap();
1477        let metadata: datatypes::extension::json::JsonMetadata =
1478            serde_json::from_str(&column_schema.metadata()["ARROW:extension:metadata"]).unwrap();
1479        let settings = metadata.json_settings();
1480        assert_eq!(Some(0), settings.max_auto_expanded_paths());
1481        assert_eq!(2, settings.type_hints().len());
1482        assert_eq!(vec!["service"], settings.type_hints()[0].path);
1483        assert_eq!(vec!["nested", "value"], settings.type_hints()[1].path);
1484    }
1485
1486    #[test]
1487    fn test_create_flow_tql_expr() {
1488        let sql = r#"
1489CREATE FLOW calc_reqs SINK TO cnt_reqs AS
1490TQL EVAL (0, 15, '5s') count_values("status_code", http_requests);"#;
1491        let stmt =
1492            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
1493
1494        assert!(
1495            stmt.is_err(),
1496            "Expected error for invalid TQL EVAL parameters: {:#?}",
1497            stmt
1498        );
1499
1500        let sql = r#"
1501CREATE FLOW calc_reqs SINK TO cnt_reqs AS
1502TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", http_requests);"#;
1503        let stmt =
1504            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1505                .unwrap()
1506                .pop()
1507                .unwrap();
1508
1509        let Statement::CreateFlow(create_flow) = stmt else {
1510            unreachable!()
1511        };
1512        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1513
1514        let to_dot_sep =
1515            |c: TableName| format!("{}.{}.{}", c.catalog_name, c.schema_name, c.table_name);
1516        assert_eq!("calc_reqs", expr.flow_name);
1517        assert_eq!("greptime", expr.catalog_name);
1518        assert_eq!(
1519            "greptime.public.cnt_reqs",
1520            expr.sink_table_name.map(to_dot_sep).unwrap()
1521        );
1522        assert_eq!(1, expr.source_table_names.len());
1523        assert_eq!(
1524            "greptime.public.http_requests",
1525            to_dot_sep(expr.source_table_names[0].clone())
1526        );
1527        assert_eq!(
1528            r#"TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", http_requests)"#,
1529            expr.sql
1530        );
1531
1532        let sql = r#"
1533CREATE FLOW calc_reqs SINK TO cnt_reqs AS
1534TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", http_requests{__schema__="greptime_private"});"#;
1535        let stmt =
1536            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1537                .unwrap()
1538                .pop()
1539                .unwrap();
1540        let Statement::CreateFlow(create_flow) = stmt else {
1541            unreachable!()
1542        };
1543        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1544        assert_eq!(1, expr.source_table_names.len());
1545        assert_eq!(
1546            "greptime.greptime_private.http_requests",
1547            to_dot_sep(expr.source_table_names[0].clone())
1548        );
1549
1550        let sql = r#"
1551CREATE FLOW calc_reqs SINK TO cnt_reqs AS
1552TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", http_requests{__database__="greptime_private"});"#;
1553        let stmt =
1554            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1555                .unwrap()
1556                .pop()
1557                .unwrap();
1558        let Statement::CreateFlow(create_flow) = stmt else {
1559            unreachable!()
1560        };
1561        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1562        assert_eq!(1, expr.source_table_names.len());
1563        assert_eq!(
1564            "greptime.greptime_private.http_requests",
1565            to_dot_sep(expr.source_table_names[0].clone())
1566        );
1567    }
1568
1569    #[test]
1570    fn test_create_flow_tql_cte_source_tables() {
1571        let sql = r#"
1572CREATE FLOW calc_cte
1573SINK TO metric_cte_sink
1574EVAL INTERVAL '1m'
1575AS
1576WITH tql(ts, the_value) AS (
1577  TQL EVAL (now() - '1m'::interval, now(), '5s') metric_cte
1578)
1579SELECT * FROM tql;
1580"#;
1581
1582        let stmt =
1583            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1584                .unwrap()
1585                .pop()
1586                .unwrap();
1587
1588        let Statement::CreateFlow(create_flow) = stmt else {
1589            unreachable!()
1590        };
1591        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1592
1593        let to_dot_sep =
1594            |c: TableName| format!("{}.{}.{}", c.catalog_name, c.schema_name, c.table_name);
1595        assert_eq!(1, expr.source_table_names.len());
1596        assert_eq!(
1597            "greptime.public.metric_cte",
1598            to_dot_sep(expr.source_table_names[0].clone())
1599        );
1600    }
1601
1602    #[test]
1603    fn test_create_flow_tql_cte_source_tables_quoted_cte_name() {
1604        let sql = r#"
1605CREATE FLOW calc_cte
1606SINK TO metric_cte_sink
1607EVAL INTERVAL '1m'
1608AS
1609WITH "TQL"(ts, the_value) AS (
1610  TQL EVAL (now() - '1m'::interval, now(), '5s') metric_cte
1611)
1612SELECT * FROM "TQL";
1613"#;
1614
1615        let stmt =
1616            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1617                .unwrap()
1618                .pop()
1619                .unwrap();
1620
1621        let Statement::CreateFlow(create_flow) = stmt else {
1622            unreachable!()
1623        };
1624        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1625
1626        let to_dot_sep =
1627            |c: TableName| format!("{}.{}.{}", c.catalog_name, c.schema_name, c.table_name);
1628        assert_eq!(1, expr.source_table_names.len());
1629        assert_eq!(
1630            "greptime.public.metric_cte",
1631            to_dot_sep(expr.source_table_names[0].clone())
1632        );
1633    }
1634
1635    #[test]
1636    fn test_create_flow_tql_cte_source_tables_same_name() {
1637        let sql = r#"
1638CREATE FLOW calc_cte
1639SINK TO metric_cte_sink
1640EVAL INTERVAL '1m'
1641AS
1642WITH tql(ts, the_value) AS (
1643  TQL EVAL (now() - '1m'::interval, now(), '5s') tql
1644)
1645SELECT * FROM tql;
1646"#;
1647
1648        let stmt =
1649            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1650                .unwrap()
1651                .pop()
1652                .unwrap();
1653
1654        let Statement::CreateFlow(create_flow) = stmt else {
1655            unreachable!()
1656        };
1657        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1658
1659        let to_dot_sep =
1660            |c: TableName| format!("{}.{}.{}", c.catalog_name, c.schema_name, c.table_name);
1661        assert_eq!(1, expr.source_table_names.len());
1662        assert_eq!(
1663            "greptime.public.tql",
1664            to_dot_sep(expr.source_table_names[0].clone())
1665        );
1666    }
1667
1668    #[test]
1669    fn test_create_flow_requires_schema_for_unqualified_tables() {
1670        let ctx = QueryContext::arc();
1671        ctx.set_current_schema("");
1672        for (sink, source, valid) in [
1673            ("sink", "public.source", false),
1674            ("public.sink", "source", false),
1675            ("public.sink", "public.source", true),
1676        ] {
1677            let sql = format!("CREATE FLOW test_flow SINK TO {sink} AS SELECT * FROM {source}");
1678            let stmt = ParserContext::create_with_dialect(
1679                &sql,
1680                &GreptimeDbDialect {},
1681                ParseOptions::default(),
1682            )
1683            .unwrap()
1684            .pop()
1685            .unwrap();
1686            let Statement::CreateFlow(flow) = stmt else {
1687                unreachable!()
1688            };
1689            let result = to_create_flow_task_expr(flow, &ctx);
1690            if valid {
1691                assert!(result.is_ok(), "{result:?}");
1692            } else {
1693                assert!(
1694                    matches!(result, Err(crate::error::Error::SchemaNotFound { ref schema_info, .. }) if schema_info.is_empty()),
1695                    "{result:?}"
1696                );
1697            }
1698        }
1699    }
1700
1701    #[test]
1702    fn test_create_flow_expr() {
1703        let sql = r"
1704CREATE FLOW test_distinct_basic SINK TO out_distinct_basic AS
1705SELECT
1706    DISTINCT number as dis
1707FROM
1708    distinct_basic;";
1709        let stmt =
1710            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1711                .unwrap()
1712                .pop()
1713                .unwrap();
1714
1715        let Statement::CreateFlow(create_flow) = stmt else {
1716            unreachable!()
1717        };
1718        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1719
1720        let to_dot_sep =
1721            |c: TableName| format!("{}.{}.{}", c.catalog_name, c.schema_name, c.table_name);
1722        assert_eq!("test_distinct_basic", expr.flow_name);
1723        assert_eq!("greptime", expr.catalog_name);
1724        assert_eq!(
1725            "greptime.public.out_distinct_basic",
1726            expr.sink_table_name.map(to_dot_sep).unwrap()
1727        );
1728        assert_eq!(1, expr.source_table_names.len());
1729        assert_eq!(
1730            "greptime.public.distinct_basic",
1731            to_dot_sep(expr.source_table_names[0].clone())
1732        );
1733        assert_eq!(
1734            r"SELECT
1735    DISTINCT number as dis
1736FROM
1737    distinct_basic",
1738            expr.sql
1739        );
1740
1741        let sql = r"
1742CREATE FLOW `task_2`
1743SINK TO schema_1.table_1
1744AS
1745SELECT max(c1), min(c2) FROM schema_2.table_2;";
1746        let stmt =
1747            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1748                .unwrap()
1749                .pop()
1750                .unwrap();
1751
1752        let Statement::CreateFlow(create_flow) = stmt else {
1753            unreachable!()
1754        };
1755        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1756
1757        let to_dot_sep =
1758            |c: TableName| format!("{}.{}.{}", c.catalog_name, c.schema_name, c.table_name);
1759        assert_eq!("task_2", expr.flow_name);
1760        assert_eq!("greptime", expr.catalog_name);
1761        assert_eq!(
1762            "greptime.schema_1.table_1",
1763            expr.sink_table_name.map(to_dot_sep).unwrap()
1764        );
1765        assert_eq!(1, expr.source_table_names.len());
1766        assert_eq!(
1767            "greptime.schema_2.table_2",
1768            to_dot_sep(expr.source_table_names[0].clone())
1769        );
1770        assert_eq!("SELECT max(c1), min(c2) FROM schema_2.table_2", expr.sql);
1771        assert!(expr.flow_options.is_empty());
1772
1773        let sql = r"
1774CREATE FLOW task_3
1775SINK TO schema_1.table_1
1776WITH (defer_on_missing_source = 'true', foo = 'bar')
1777AS
1778SELECT max(c1), min(c2) FROM schema_2.table_2;";
1779        let stmt =
1780            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1781                .unwrap()
1782                .pop()
1783                .unwrap();
1784
1785        let Statement::CreateFlow(create_flow) = stmt else {
1786            unreachable!()
1787        };
1788        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1789        assert_eq!(
1790            expr.flow_options,
1791            HashMap::from([
1792                ("defer_on_missing_source".to_string(), "true".to_string()),
1793                ("foo".to_string(), "bar".to_string()),
1794            ])
1795        );
1796
1797        let sql = r"
1798CREATE FLOW task_4
1799SINK TO schema_1.table_1
1800WITH (defer_on_missing_source = true)
1801AS
1802SELECT max(c1), min(c2) FROM schema_2.table_2;";
1803        let stmt =
1804            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1805                .unwrap()
1806                .pop()
1807                .unwrap();
1808
1809        let Statement::CreateFlow(create_flow) = stmt else {
1810            unreachable!()
1811        };
1812        let expr = to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
1813        assert_eq!(
1814            expr.flow_options,
1815            HashMap::from([("defer_on_missing_source".to_string(), "true".to_string(),)])
1816        );
1817
1818        let sql = r"
1819CREATE FLOW task_5
1820SINK TO schema_1.table_1
1821WITH (defer_on_missing_source = [true])
1822AS
1823SELECT max(c1), min(c2) FROM schema_2.table_2;";
1824        let stmt =
1825            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1826                .unwrap()
1827                .pop()
1828                .unwrap();
1829
1830        let Statement::CreateFlow(create_flow) = stmt else {
1831            unreachable!()
1832        };
1833        let res = to_create_flow_task_expr(create_flow, &QueryContext::arc());
1834        assert!(res.is_err());
1835        assert!(
1836            res.unwrap_err()
1837                .to_string()
1838                .contains("flow options only support scalar string-compatible values")
1839        );
1840
1841        let sql = r"
1842CREATE FLOW abc.`task_2`
1843SINK TO schema_1.table_1
1844AS
1845SELECT max(c1), min(c2) FROM schema_2.table_2;";
1846        let stmt =
1847            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1848                .unwrap()
1849                .pop()
1850                .unwrap();
1851
1852        let Statement::CreateFlow(create_flow) = stmt else {
1853            unreachable!()
1854        };
1855        let res = to_create_flow_task_expr(create_flow, &QueryContext::arc());
1856
1857        assert!(res.is_err());
1858        assert!(
1859            res.unwrap_err()
1860                .to_string()
1861                .contains("Invalid flow name: abc.`task_2`")
1862        );
1863    }
1864
1865    #[test]
1866    fn test_create_to_expr() {
1867        let sql = "CREATE TABLE monitor (host STRING,ts TIMESTAMP,TIME INDEX (ts),PRIMARY KEY(host)) ENGINE=mito WITH(ttl='3days', write_buffer_size='1024KB');";
1868        let stmt =
1869            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1870                .unwrap()
1871                .pop()
1872                .unwrap();
1873
1874        let Statement::CreateTable(create_table) = stmt else {
1875            unreachable!()
1876        };
1877        let expr = create_to_expr(&create_table, &QueryContext::arc()).unwrap();
1878        assert_eq!("3days", expr.table_options.get("ttl").unwrap());
1879        assert_eq!(
1880            "1.0MiB",
1881            expr.table_options.get("write_buffer_size").unwrap()
1882        );
1883
1884        let sql = "CREATE TABLE monitor (ts TIMESTAMP TIME INDEX) WITH(skip_wal='false');";
1885        let stmt =
1886            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1887                .unwrap()
1888                .pop()
1889                .unwrap();
1890        let Statement::CreateTable(create_table) = stmt else {
1891            unreachable!()
1892        };
1893        let expr = create_to_expr(&create_table, &QueryContext::arc()).unwrap();
1894        assert_eq!(
1895            Some("false"),
1896            expr.table_options
1897                .get(store_api::mito_engine_options::SKIP_WAL_KEY)
1898                .map(String::as_str)
1899        );
1900    }
1901
1902    #[test]
1903    fn test_invalid_create_to_expr() {
1904        let cases = [
1905            // duplicate column declaration
1906            "CREATE TABLE monitor (host STRING primary key, ts TIMESTAMP TIME INDEX, some_column text, some_column string);",
1907            // duplicate primary key
1908            "CREATE TABLE monitor (host STRING, ts TIMESTAMP TIME INDEX, some_column STRING, PRIMARY KEY (some_column, host, some_column));",
1909            // time index is primary key
1910            "CREATE TABLE monitor (host STRING, ts TIMESTAMP TIME INDEX, PRIMARY KEY (host, ts));",
1911        ];
1912
1913        for sql in cases {
1914            let stmt = ParserContext::create_with_dialect(
1915                sql,
1916                &GreptimeDbDialect {},
1917                ParseOptions::default(),
1918            )
1919            .unwrap()
1920            .pop()
1921            .unwrap();
1922            let Statement::CreateTable(create_table) = stmt else {
1923                unreachable!()
1924            };
1925            create_to_expr(&create_table, &QueryContext::arc()).unwrap_err();
1926        }
1927    }
1928
1929    #[test]
1930    fn test_create_to_expr_with_default_timestamp_value() {
1931        let sql = "CREATE TABLE monitor (v double,ts TIMESTAMP default '2024-01-30T00:01:01',TIME INDEX (ts)) engine=mito;";
1932        let stmt =
1933            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1934                .unwrap()
1935                .pop()
1936                .unwrap();
1937
1938        let Statement::CreateTable(create_table) = stmt else {
1939            unreachable!()
1940        };
1941
1942        // query context with system timezone UTC.
1943        let expr = create_to_expr(&create_table, &QueryContext::arc()).unwrap();
1944        let ts_column = &expr.column_defs[1];
1945        let constraint = assert_ts_column(ts_column);
1946        assert!(
1947            matches!(constraint, ColumnDefaultConstraint::Value(Value::Timestamp(ts))
1948                         if ts.to_iso8601_string() == "2024-01-30 00:01:01+0000")
1949        );
1950
1951        // query context with timezone `+08:00`
1952        let ctx = QueryContextBuilder::default()
1953            .timezone(Timezone::from_tz_string("+08:00").unwrap())
1954            .build()
1955            .into();
1956        let expr = create_to_expr(&create_table, &ctx).unwrap();
1957        let ts_column = &expr.column_defs[1];
1958        let constraint = assert_ts_column(ts_column);
1959        assert!(
1960            matches!(constraint, ColumnDefaultConstraint::Value(Value::Timestamp(ts))
1961                         if ts.to_iso8601_string() == "2024-01-29 16:01:01+0000")
1962        );
1963    }
1964
1965    fn assert_ts_column(ts_column: &api::v1::ColumnDef) -> ColumnDefaultConstraint {
1966        assert_eq!("ts", ts_column.name);
1967        assert_eq!(
1968            ColumnDataType::TimestampMillisecond as i32,
1969            ts_column.data_type
1970        );
1971        assert!(!ts_column.default_constraint.is_empty());
1972
1973        ColumnDefaultConstraint::try_from(&ts_column.default_constraint[..]).unwrap()
1974    }
1975
1976    #[test]
1977    fn test_to_alter_expr() {
1978        let sql = "ALTER DATABASE greptime SET key1='value1', key2='value2';";
1979        let stmt =
1980            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1981                .unwrap()
1982                .pop()
1983                .unwrap();
1984
1985        let Statement::AlterDatabase(alter_database) = stmt else {
1986            unreachable!()
1987        };
1988
1989        let expr = to_alter_database_expr(alter_database, &QueryContext::arc()).unwrap();
1990        let kind = expr.kind.unwrap();
1991
1992        let AlterDatabaseKind::SetDatabaseOptions(SetDatabaseOptions {
1993            set_database_options,
1994        }) = kind
1995        else {
1996            unreachable!()
1997        };
1998
1999        assert_eq!(2, set_database_options.len());
2000        assert_eq!("key1", set_database_options[0].key);
2001        assert_eq!("value1", set_database_options[0].value);
2002        assert_eq!("key2", set_database_options[1].key);
2003        assert_eq!("value2", set_database_options[1].value);
2004
2005        let sql = "ALTER DATABASE greptime UNSET key1, key2;";
2006        let stmt =
2007            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2008                .unwrap()
2009                .pop()
2010                .unwrap();
2011
2012        let Statement::AlterDatabase(alter_database) = stmt else {
2013            unreachable!()
2014        };
2015
2016        let expr = to_alter_database_expr(alter_database, &QueryContext::arc()).unwrap();
2017        let kind = expr.kind.unwrap();
2018
2019        let AlterDatabaseKind::UnsetDatabaseOptions(UnsetDatabaseOptions { keys }) = kind else {
2020            unreachable!()
2021        };
2022
2023        assert_eq!(2, keys.len());
2024        assert!(keys.contains(&"key1".to_string()));
2025        assert!(keys.contains(&"key2".to_string()));
2026
2027        let sql = "ALTER TABLE monitor add column ts TIMESTAMP default '2024-01-30T00:01:01';";
2028        let stmt =
2029            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2030                .unwrap()
2031                .pop()
2032                .unwrap();
2033
2034        let Statement::AlterTable(alter_table) = stmt else {
2035            unreachable!()
2036        };
2037
2038        // query context with system timezone UTC.
2039        let expr = to_alter_table_expr(alter_table.clone(), &QueryContext::arc()).unwrap();
2040        let kind = expr.kind.unwrap();
2041
2042        let AlterTableKind::AddColumns(AddColumns { add_columns, .. }) = kind else {
2043            unreachable!()
2044        };
2045
2046        assert_eq!(1, add_columns.len());
2047        let ts_column = add_columns[0].column_def.clone().unwrap();
2048        let constraint = assert_ts_column(&ts_column);
2049        assert!(
2050            matches!(constraint, ColumnDefaultConstraint::Value(Value::Timestamp(ts))
2051                         if ts.to_iso8601_string() == "2024-01-30 00:01:01+0000")
2052        );
2053
2054        //
2055        // query context with timezone `+08:00`
2056        let ctx = QueryContextBuilder::default()
2057            .timezone(Timezone::from_tz_string("+08:00").unwrap())
2058            .build()
2059            .into();
2060        let expr = to_alter_table_expr(alter_table, &ctx).unwrap();
2061        let kind = expr.kind.unwrap();
2062
2063        let AlterTableKind::AddColumns(AddColumns { add_columns, .. }) = kind else {
2064            unreachable!()
2065        };
2066
2067        assert_eq!(1, add_columns.len());
2068        let ts_column = add_columns[0].column_def.clone().unwrap();
2069        let constraint = assert_ts_column(&ts_column);
2070        assert!(
2071            matches!(constraint, ColumnDefaultConstraint::Value(Value::Timestamp(ts))
2072                         if ts.to_iso8601_string() == "2024-01-29 16:01:01+0000")
2073        );
2074    }
2075
2076    #[test]
2077    fn test_to_alter_modify_column_type_expr() {
2078        let sql = "ALTER TABLE monitor MODIFY COLUMN mem_usage STRING;";
2079        let stmt =
2080            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2081                .unwrap()
2082                .pop()
2083                .unwrap();
2084
2085        let Statement::AlterTable(alter_table) = stmt else {
2086            unreachable!()
2087        };
2088
2089        // query context with system timezone UTC.
2090        let expr = to_alter_table_expr(alter_table.clone(), &QueryContext::arc()).unwrap();
2091        let kind = expr.kind.unwrap();
2092
2093        let AlterTableKind::ModifyColumnTypes(ModifyColumnTypes {
2094            modify_column_types,
2095        }) = kind
2096        else {
2097            unreachable!()
2098        };
2099
2100        assert_eq!(1, modify_column_types.len());
2101        let modify_column_type = &modify_column_types[0];
2102
2103        assert_eq!("mem_usage", modify_column_type.column_name);
2104        assert_eq!(
2105            ColumnDataType::String as i32,
2106            modify_column_type.target_type
2107        );
2108        assert!(modify_column_type.target_type_extension.is_none());
2109    }
2110
2111    #[test]
2112    fn test_json_settings_roundtrip() {
2113        let mut cases = vec![JsonSettings::default(), JsonSettings::new_v2()];
2114        for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] {
2115            let options =
2116                FulltextOptions::new(true, FulltextAnalyzer::Chinese, true, backend, 8, 0.05)
2117                    .unwrap();
2118            cases.push(
2119                JsonSettings::try_new(
2120                    vec![
2121                        JsonTypeHint {
2122                            path: vec!["nested".into(), "message".into()],
2123                            data_type: ConcreteDataType::string_datatype(),
2124                            inverted_index: true,
2125                            skipping_index: Some(
2126                                SkippingIndexOptions::new(8, 0.05, SkippingIndexType::BloomFilter)
2127                                    .unwrap(),
2128                            ),
2129                            fulltext_index: Some(options),
2130                        },
2131                        JsonTypeHint {
2132                            path: vec!["count".into()],
2133                            data_type: ConcreteDataType::int64_datatype(),
2134                            inverted_index: false,
2135                            skipping_index: None,
2136                            fulltext_index: None,
2137                        },
2138                    ],
2139                    Some(0),
2140                )
2141                .unwrap(),
2142            );
2143        }
2144        for settings in cases {
2145            let wire = json_settings_to_proto(settings.clone()).unwrap();
2146            let set_settings = api::v1::SetJsonSettings {
2147                column_name: "payload".into(),
2148                settings: Some(wire),
2149            };
2150            let expr = api::v1::AlterTableExpr {
2151                kind: Some(AlterTableKind::SetJsonSettings(set_settings.clone())),
2152                ..Default::default()
2153            };
2154            let request = common_grpc_expr::alter_expr_to_request(1, expr, None).unwrap();
2155            let table::requests::AlterKind::SetJsonSettings { request } = request.alter_kind else {
2156                panic!("expected JSON settings request");
2157            };
2158            assert_eq!(settings, request.settings);
2159            let request = RegionAlterRequest::try_from(api::v1::region::AlterRequest {
2160                kind: Some(api::v1::region::alter_request::Kind::SetJsonSettings(
2161                    set_settings,
2162                )),
2163                ..Default::default()
2164            })
2165            .unwrap();
2166            let RegionAlterKind::SetJsonSettings {
2167                settings: decoded, ..
2168            } = request.kind
2169            else {
2170                panic!("expected JSON settings region request");
2171            };
2172            assert_eq!(settings, decoded);
2173        }
2174    }
2175
2176    #[test]
2177    fn test_to_alter_set_json_settings_expr() {
2178        let sql = "ALTER TABLE monitor MODIFY COLUMN payload JSON2 (service STRING INVERTED INDEX SKIPPING INDEX WITH (granularity='8'), message STRING);";
2179        let stmt =
2180            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2181                .unwrap()
2182                .pop()
2183                .unwrap();
2184
2185        let Statement::AlterTable(alter_table) = stmt else {
2186            unreachable!()
2187        };
2188        let expr = to_alter_table_expr(alter_table, &QueryContext::arc()).unwrap();
2189        let kind = expr.kind.unwrap();
2190
2191        let AlterTableKind::SetJsonSettings(modify) = kind else {
2192            unreachable!()
2193        };
2194        assert_eq!("payload", modify.column_name);
2195        let settings = modify.settings.as_ref().unwrap();
2196        assert_eq!(Some(100), settings.max_auto_expanded_paths);
2197        assert_eq!(2, settings.type_hints.len());
2198        assert_eq!(["service"], &settings.type_hints[0].path[..]);
2199        assert!(settings.type_hints[0].inverted_index);
2200        assert_eq!(
2201            settings.type_hints[0]
2202                .skipping_index
2203                .as_ref()
2204                .unwrap()
2205                .granularity,
2206            8
2207        );
2208        assert!(!settings.type_hints[1].inverted_index);
2209
2210        let sql = "ALTER TABLE monitor MODIFY COLUMN payload JSON2;";
2211        let stmt =
2212            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2213                .unwrap()
2214                .pop()
2215                .unwrap();
2216
2217        let Statement::AlterTable(alter_table) = stmt else {
2218            unreachable!()
2219        };
2220        let expr = to_alter_table_expr(alter_table, &QueryContext::arc()).unwrap();
2221        let kind = expr.kind.unwrap();
2222
2223        let AlterTableKind::SetJsonSettings(modify) = kind else {
2224            unreachable!()
2225        };
2226        let settings = modify.settings.as_ref().unwrap();
2227        assert_eq!(Some(100), settings.max_auto_expanded_paths);
2228        assert!(settings.type_hints.is_empty());
2229    }
2230
2231    #[test]
2232    fn test_to_repartition_request() {
2233        let sql = r#"
2234ALTER TABLE metrics REPARTITION (
2235  device_id < 100
2236) INTO (
2237  device_id < 100 AND area < 'South',
2238  device_id < 100 AND area >= 'South'
2239);"#;
2240        let stmt =
2241            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2242                .unwrap()
2243                .pop()
2244                .unwrap();
2245
2246        let Statement::AlterTable(alter_table) = stmt else {
2247            unreachable!()
2248        };
2249
2250        let request = to_repartition_request(alter_table, &QueryContext::arc()).unwrap();
2251        assert_eq!("greptime", request.catalog_name);
2252        assert_eq!("public", request.schema_name);
2253        assert_eq!("metrics", request.table_name);
2254        let RepartitionSource::Partitions {
2255            from_exprs,
2256            target_partition_columns,
2257        } = request.source
2258        else {
2259            unreachable!()
2260        };
2261        assert!(target_partition_columns.is_none());
2262        assert_eq!(
2263            from_exprs
2264                .into_iter()
2265                .map(|x| x.to_string())
2266                .collect::<Vec<_>>(),
2267            vec!["device_id < 100".to_string()]
2268        );
2269        assert_eq!(
2270            request
2271                .into_exprs
2272                .into_iter()
2273                .map(|x| x.to_string())
2274                .collect::<Vec<_>>(),
2275            vec![
2276                "device_id < 100 AND area < 'South'".to_string(),
2277                "device_id < 100 AND area >= 'South'".to_string()
2278            ]
2279        );
2280    }
2281
2282    #[test]
2283    fn test_to_repartition_request_with_target_partition_columns() {
2284        let sql = r#"
2285ALTER TABLE metrics REPARTITION (
2286  device_id < 100
2287) ON COLUMNS (device_id, area) INTO (
2288  device_id < 100 AND area < 'South',
2289  device_id < 100 AND area >= 'South'
2290);"#;
2291        let stmt =
2292            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2293                .unwrap()
2294                .pop()
2295                .unwrap();
2296
2297        let Statement::AlterTable(alter_table) = stmt else {
2298            unreachable!()
2299        };
2300
2301        let request = to_repartition_request(alter_table, &QueryContext::arc()).unwrap();
2302        let RepartitionSource::Partitions {
2303            target_partition_columns,
2304            ..
2305        } = request.source
2306        else {
2307            unreachable!()
2308        };
2309
2310        assert_eq!(
2311            target_partition_columns,
2312            Some(vec!["device_id".to_string(), "area".to_string()])
2313        );
2314    }
2315
2316    #[test]
2317    fn test_to_repartition_request_with_unpartitioned_source() {
2318        let sql = r#"
2319ALTER TABLE metrics PARTITION ON COLUMNS (device_id, area) (
2320  device_id < 100 AND area < 'South',
2321  device_id < 100 AND area >= 'South'
2322);"#;
2323        let stmt =
2324            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2325                .unwrap()
2326                .pop()
2327                .unwrap();
2328
2329        let Statement::AlterTable(alter_table) = stmt else {
2330            unreachable!()
2331        };
2332
2333        let request = to_repartition_request(alter_table, &QueryContext::arc()).unwrap();
2334        assert_eq!("greptime", request.catalog_name);
2335        assert_eq!("public", request.schema_name);
2336        assert_eq!("metrics", request.table_name);
2337        let RepartitionSource::Unpartitioned { partition_columns } = request.source else {
2338            unreachable!()
2339        };
2340        assert_eq!(partition_columns, vec!["device_id", "area"]);
2341        assert_eq!(
2342            request
2343                .into_exprs
2344                .into_iter()
2345                .map(|x| x.to_string())
2346                .collect::<Vec<_>>(),
2347            vec![
2348                "device_id < 100 AND area < 'South'".to_string(),
2349                "device_id < 100 AND area >= 'South'".to_string()
2350            ]
2351        );
2352    }
2353
2354    fn new_test_table_names() -> Vec<TableName> {
2355        vec![
2356            TableName {
2357                catalog_name: "greptime".to_string(),
2358                schema_name: "public".to_string(),
2359                table_name: "a_table".to_string(),
2360            },
2361            TableName {
2362                catalog_name: "greptime".to_string(),
2363                schema_name: "public".to_string(),
2364                table_name: "b_table".to_string(),
2365            },
2366        ]
2367    }
2368
2369    #[test]
2370    fn test_to_create_view_expr() {
2371        let sql = "CREATE VIEW test AS SELECT * FROM NUMBERS";
2372        let stmt =
2373            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2374                .unwrap()
2375                .pop()
2376                .unwrap();
2377
2378        let Statement::CreateView(stmt) = stmt else {
2379            unreachable!()
2380        };
2381
2382        let logical_plan = vec![1, 2, 3];
2383        let table_names = new_test_table_names();
2384        let columns = vec!["a".to_string()];
2385        let plan_columns = vec!["number".to_string()];
2386
2387        let expr = to_create_view_expr(
2388            stmt,
2389            logical_plan.clone(),
2390            table_names.clone(),
2391            columns.clone(),
2392            plan_columns.clone(),
2393            sql.to_string(),
2394            QueryContext::arc(),
2395        )
2396        .unwrap();
2397
2398        assert_eq!("greptime", expr.catalog_name);
2399        assert_eq!("public", expr.schema_name);
2400        assert_eq!("test", expr.view_name);
2401        assert!(!expr.create_if_not_exists);
2402        assert!(!expr.or_replace);
2403        assert_eq!(logical_plan, expr.logical_plan);
2404        assert_eq!(table_names, expr.table_names);
2405        assert_eq!(sql, expr.definition);
2406        assert_eq!(columns, expr.columns);
2407        assert_eq!(plan_columns, expr.plan_columns);
2408    }
2409
2410    #[test]
2411    fn test_to_create_view_expr_complex() {
2412        let sql = "CREATE OR REPLACE VIEW IF NOT EXISTS test.test_view AS SELECT * FROM NUMBERS";
2413        let stmt =
2414            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2415                .unwrap()
2416                .pop()
2417                .unwrap();
2418
2419        let Statement::CreateView(stmt) = stmt else {
2420            unreachable!()
2421        };
2422
2423        let logical_plan = vec![1, 2, 3];
2424        let table_names = new_test_table_names();
2425        let columns = vec!["a".to_string()];
2426        let plan_columns = vec!["number".to_string()];
2427
2428        let expr = to_create_view_expr(
2429            stmt,
2430            logical_plan.clone(),
2431            table_names.clone(),
2432            columns.clone(),
2433            plan_columns.clone(),
2434            sql.to_string(),
2435            QueryContext::arc(),
2436        )
2437        .unwrap();
2438
2439        assert_eq!("greptime", expr.catalog_name);
2440        assert_eq!("test", expr.schema_name);
2441        assert_eq!("test_view", expr.view_name);
2442        assert!(expr.create_if_not_exists);
2443        assert!(expr.or_replace);
2444        assert_eq!(logical_plan, expr.logical_plan);
2445        assert_eq!(table_names, expr.table_names);
2446        assert_eq!(sql, expr.definition);
2447        assert_eq!(columns, expr.columns);
2448        assert_eq!(plan_columns, expr.plan_columns);
2449    }
2450
2451    #[test]
2452    fn test_expr_to_create() {
2453        let sql = r#"CREATE TABLE IF NOT EXISTS `tt` (
2454  `timestamp` TIMESTAMP(9) NOT NULL,
2455  `ip_address` STRING NULL SKIPPING INDEX WITH(false_positive_rate = '0.01', granularity = '10240', type = 'BLOOM'),
2456  `username` STRING NULL,
2457  `http_method` STRING NULL INVERTED INDEX,
2458  `request_line` STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', false_positive_rate = '0.01', granularity = '10240'),
2459  `protocol` STRING NULL,
2460  `status_code` INT NULL INVERTED INDEX,
2461  `response_size` BIGINT NULL,
2462  `message` STRING NULL COMPRESSION WITH(level = '3', page_size = '64KiB', type = 'zstd'),
2463  TIME INDEX (`timestamp`),
2464  PRIMARY KEY (`username`, `status_code`)
2465)
2466ENGINE=mito
2467WITH(
2468  append_mode = 'true'
2469)"#;
2470        let stmt =
2471            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2472                .unwrap()
2473                .pop()
2474                .unwrap();
2475
2476        let Statement::CreateTable(original_create) = stmt else {
2477            unreachable!()
2478        };
2479
2480        // Convert CreateTable -> CreateTableExpr -> CreateTable
2481        let expr = create_to_expr(&original_create, &QueryContext::arc()).unwrap();
2482
2483        let create_table = expr_to_create(&expr, Some('`')).unwrap();
2484        let new_sql = format!("{:#}", create_table);
2485        assert_eq!(sql, new_sql);
2486    }
2487
2488    fn build_relational_expr_from_sql(
2489        sql: &str,
2490        remote_columns: &[MySqlColumn],
2491    ) -> Result<CreateTableExpr> {
2492        let stmt =
2493            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
2494                .unwrap()
2495                .pop()
2496                .unwrap();
2497        let Statement::CreateExternalTable(create) = stmt else {
2498            unreachable!()
2499        };
2500        build_relational_expr(
2501            create,
2502            &QueryContext::arc(),
2503            "greptime".to_string(),
2504            "public".to_string(),
2505            "external_t".to_string(),
2506            RelationalOptions {
2507                connection: "mysql://root:secret@127.0.0.1:3306/testdb".to_string(),
2508                remote_table: "testdb.sample".to_string(),
2509            },
2510            remote_columns,
2511        )
2512    }
2513
2514    #[test]
2515    fn test_build_relational_expr_inferred() {
2516        let sql = "CREATE EXTERNAL TABLE external_t ENGINE=relational WITH (connection='mysql://root:secret@127.0.0.1:3306/testdb', remote_table='testdb.sample')";
2517        let remote_columns = vec![
2518            MySqlColumn {
2519                name: "id".into(),
2520                column_type: MySqlColumnType::new("int"),
2521            },
2522            MySqlColumn {
2523                name: "name".into(),
2524                column_type: MySqlColumnType::new("varchar"),
2525            },
2526        ];
2527        let expr = build_relational_expr_from_sql(sql, &remote_columns).unwrap();
2528        let names: Vec<&str> = expr
2529            .column_defs
2530            .iter()
2531            .map(|column| column.name.as_str())
2532            .collect();
2533        assert_eq!(names, ["id", "name", "greptime_timestamp"]);
2534        assert_eq!(expr.time_index, "greptime_timestamp");
2535        assert!(expr.primary_keys.is_empty());
2536    }
2537
2538    #[test]
2539    fn test_build_relational_expr_inferred_reserved_timestamp() {
2540        let sql = "CREATE EXTERNAL TABLE external_t ENGINE=relational WITH (connection='mysql://root:secret@127.0.0.1:3306/testdb', remote_table='testdb.sample')";
2541        let remote_columns = vec![
2542            MySqlColumn {
2543                name: "id".into(),
2544                column_type: MySqlColumnType::new("int"),
2545            },
2546            MySqlColumn {
2547                name: "greptime_timestamp".into(),
2548                column_type: MySqlColumnType::new("timestamp"),
2549            },
2550        ];
2551        let err = build_relational_expr_from_sql(sql, &remote_columns).unwrap_err();
2552        assert!(matches!(
2553            err,
2554            Error::ReservedTimeIndexColumn { ref name, .. } if name.as_str() == "greptime_timestamp"
2555        ));
2556    }
2557
2558    #[test]
2559    fn test_build_relational_expr_declared() {
2560        let sql = "CREATE EXTERNAL TABLE external_t (host INT, ts TIMESTAMP, TIME INDEX(ts)) ENGINE=relational WITH (connection='mysql://root:secret@127.0.0.1:3306/testdb', remote_table='testdb.sample')";
2561        let remote_columns = vec![
2562            MySqlColumn {
2563                name: "host".into(),
2564                column_type: MySqlColumnType::new("int"),
2565            },
2566            MySqlColumn {
2567                name: "ts".into(),
2568                column_type: MySqlColumnType::new("timestamp").with_fsp(3),
2569            },
2570            MySqlColumn {
2571                name: "name".into(),
2572                column_type: MySqlColumnType::new("varchar"),
2573            },
2574        ];
2575        let expr = build_relational_expr_from_sql(sql, &remote_columns).unwrap();
2576        let names: Vec<&str> = expr
2577            .column_defs
2578            .iter()
2579            .map(|column| column.name.as_str())
2580            .collect();
2581        assert_eq!(names, ["host", "ts"]);
2582        assert_eq!(expr.time_index, "ts");
2583        assert!(expr.primary_keys.is_empty());
2584    }
2585
2586    #[test]
2587    fn test_build_relational_expr_declared_missing_column() {
2588        let sql = "CREATE EXTERNAL TABLE external_t (host INT, missing INT, ts TIMESTAMP, TIME INDEX(ts)) ENGINE=relational WITH (connection='mysql://root:secret@127.0.0.1:3306/testdb', remote_table='testdb.sample')";
2589        let remote_columns = vec![
2590            MySqlColumn {
2591                name: "host".into(),
2592                column_type: MySqlColumnType::new("int"),
2593            },
2594            MySqlColumn {
2595                name: "ts".into(),
2596                column_type: MySqlColumnType::new("timestamp").with_fsp(3),
2597            },
2598        ];
2599        let err = build_relational_expr_from_sql(sql, &remote_columns).unwrap_err();
2600        assert!(matches!(err, Error::InvalidSql { .. }));
2601    }
2602
2603    #[test]
2604    fn test_build_relational_expr_declared_synthetic_time_index() {
2605        let sql = "CREATE EXTERNAL TABLE external_t (host INT, greptime_timestamp TIMESTAMP DEFAULT '1970-01-01 00:00:00+0000', TIME INDEX(greptime_timestamp)) ENGINE=relational WITH (connection='mysql://root:secret@127.0.0.1:3306/testdb', remote_table='testdb.sample')";
2606        let remote_columns = vec![MySqlColumn {
2607            name: "host".into(),
2608            column_type: MySqlColumnType::new("int"),
2609        }];
2610        let expr = build_relational_expr_from_sql(sql, &remote_columns).unwrap();
2611        let names: Vec<&str> = expr
2612            .column_defs
2613            .iter()
2614            .map(|column| column.name.as_str())
2615            .collect();
2616        assert_eq!(names, ["host", "greptime_timestamp"]);
2617        assert_eq!(expr.time_index, "greptime_timestamp");
2618    }
2619}