Skip to main content

operator/statement/
ddl.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
15use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17use std::time::Duration;
18
19use api::helper::ColumnDataTypeWrapper;
20use api::v1::alter_table_expr::Kind;
21use api::v1::meta::CreateFlowTask as PbCreateFlowTask;
22use api::v1::repartition::Source;
23use api::v1::{
24    AlterDatabaseExpr, AlterTableExpr, CreateFlowExpr, CreateTableExpr, CreateViewExpr,
25    PartitionedSource, Repartition, TargetPartitionColumns, UnpartitionedSource, column_def,
26};
27#[cfg(feature = "enterprise")]
28use api::v1::{
29    CreateTriggerExpr as PbCreateTriggerExpr, meta::CreateTriggerTask as PbCreateTriggerTask,
30};
31use catalog::CatalogManagerRef;
32use chrono::Utc;
33use common_base::regex_pattern::NAME_PATTERN_REG;
34use common_catalog::consts::{
35    DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, is_ddl_reserved_table, is_readonly_schema,
36    is_readonly_table,
37};
38use common_catalog::{format_full_flow_name, format_full_table_name};
39use common_error::ext::BoxedError;
40#[cfg(feature = "enterprise")]
41use common_meta::cache_invalidator::CacheInvalidatorRef;
42use common_meta::cache_invalidator::Context;
43use common_meta::ddl::create_flow::{
44    DEFER_ON_MISSING_SOURCE_KEY, FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY, FlowType,
45    INTERNAL_EVAL_OFFSET_KEY, INTERNAL_EVAL_SCHEDULE_KEY,
46};
47use common_meta::instruction::CacheIdent;
48#[cfg(feature = "enterprise")]
49use common_meta::key::TableMetadataManagerRef;
50use common_meta::key::schema_name::{SchemaName, SchemaNameKey};
51#[cfg(feature = "enterprise")]
52use common_meta::procedure_executor::ProcedureExecutorRef;
53#[cfg(feature = "enterprise")]
54use common_meta::rpc::ddl::trigger::CreateTriggerTask;
55#[cfg(feature = "enterprise")]
56use common_meta::rpc::ddl::trigger::DropTriggerTask;
57use common_meta::rpc::ddl::{
58    ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY, CreateFlowTask, CreatorGrantIntent, DdlTask,
59    DropFlowTask, DropViewTask, SubmitDdlTaskRequest, SubmitDdlTaskResponse, TriggerReason,
60};
61use common_query::Output;
62use common_recordbatch::{RecordBatch, RecordBatches};
63use common_sql::convert::sql_value_to_value;
64use common_telemetry::{debug, info, tracing, warn};
65use common_time::{TimeToLive, Timestamp, Timezone};
66use datafusion_common::tree_node::TreeNodeVisitor;
67use datafusion_expr::LogicalPlan;
68use datafusion_expr::logical_plan::Distinct;
69use datatypes::prelude::ConcreteDataType;
70use datatypes::schema::{ColumnSchema, Schema};
71use datatypes::value::Value;
72use datatypes::vectors::{StringVector, VectorRef};
73use humantime::parse_duration;
74use partition::expr::{Operand, PartitionExpr, RestrictedOp};
75use partition::function::IcebergHash;
76use partition::multi_dim::MultiDimPartitionRule;
77use query::parser::QueryStatement;
78use query::plan::extract_and_rewrite_full_table_names;
79use query::promql::planner::NATIVE_PROMQL_EXTENSION_KEY;
80use query::query_engine::DefaultSerializer;
81use query::sql::create_table_stmt;
82use session::context::QueryContextRef;
83use session::table_name::table_idents_to_full_name;
84use snafu::{OptionExt, ResultExt, ensure};
85use sql::parser::{ParseOptions, ParserContext};
86use sql::parsers::utils::is_tql;
87use sql::statements::OptionMap;
88#[cfg(feature = "enterprise")]
89use sql::statements::alter::trigger::AlterTrigger;
90use sql::statements::alter::{AlterDatabase, AlterTable, AlterTableOperation};
91#[cfg(feature = "enterprise")]
92use sql::statements::create::trigger::CreateTrigger;
93use sql::statements::create::{
94    CreateExternalTable, CreateFlow, CreateTable, CreateTableLike, CreateView, Partitions,
95};
96use sql::statements::statement::Statement;
97use sqlparser::ast::{
98    Expr, Function, FunctionArg, FunctionArgExpr, FunctionArguments, Ident, UnaryOperator,
99    Value as ParserValue,
100};
101use store_api::metric_engine_consts::{
102    LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
103};
104use store_api::mito_engine_options::TTL_KEY;
105use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan};
106use table::TableRef;
107use table::dist_table::DistTable;
108use table::metadata::{self, TableId, TableInfo, TableMeta, TableType};
109use table::requests::{
110    AlterKind, AlterTableRequest, COMMENT_KEY, DDL_TIMEOUT, DDL_WAIT, INGEST_ROWS_RATE_LIMIT_KEY,
111    TableOptions, validate_and_normalize_annotation_options,
112};
113use table::table_name::TableName;
114use table::table_reference::TableReference;
115
116use crate::error::{
117    self, AlterExprToRequestSnafu, BuildDfLogicalPlanSnafu, CatalogSnafu, ColumnDataTypeSnafu,
118    ColumnNotFoundSnafu, ConvertSchemaSnafu, CreateLogicalTablesSnafu,
119    DeserializePartitionExprSnafu, EmptyDdlExprSnafu, ExternalSnafu, ExtractTableNamesSnafu,
120    FlowNotFoundSnafu, InvalidPartitionRuleSnafu, InvalidPartitionSnafu, InvalidSqlSnafu,
121    InvalidTableNameSnafu, InvalidViewNameSnafu, InvalidViewStmtSnafu, NotSupportedSnafu,
122    PartitionExprToPbSnafu, Result, RetentionTtlOnLogicalTableSnafu, SchemaInUseSnafu,
123    SchemaNotFoundSnafu, SchemaReadOnlySnafu, SerializePartitionExprSnafu, SubstraitCodecSnafu,
124    TableAlreadyExistsSnafu, TableDdlReservedSnafu, TableMetadataManagerSnafu, TableNotFoundSnafu,
125    TableReadOnlySnafu, UnrecognizedTableOptionSnafu, ViewAlreadyExistsSnafu,
126};
127use crate::expr_helper::{self, RepartitionRequest, RepartitionSource};
128use crate::statement::StatementExecutor;
129use crate::statement::show::create_partitions_stmt;
130use crate::utils::{to_executor_context, to_executor_context_with_origin_frontend};
131
132/// Options shared by SQL DDL submission paths.
133#[derive(Debug, Clone, Copy)]
134pub(crate) struct DdlSubmitOptions {
135    wait: bool,
136    timeout: Duration,
137}
138
139impl Default for DdlSubmitOptions {
140    fn default() -> Self {
141        Self {
142            wait: SubmitDdlTaskRequest::default_wait(),
143            timeout: SubmitDdlTaskRequest::default_timeout(),
144        }
145    }
146}
147
148#[cfg(not(feature = "enterprise"))]
149const ALLOWED_FLOW_OPTIONS: [&str; 2] = [
150    DEFER_ON_MISSING_SOURCE_KEY,
151    FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY,
152];
153
154fn build_procedure_id_output(procedure_id: &str) -> Result<Output> {
155    let vector: VectorRef = Arc::new(StringVector::from(vec![procedure_id]));
156    let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
157        "Procedure ID",
158        vector.data_type(),
159        false,
160    )]));
161    let batch =
162        RecordBatch::new(schema.clone(), vec![vector]).context(error::BuildRecordBatchSnafu)?;
163    let batches =
164        RecordBatches::try_new(schema, vec![batch]).context(error::BuildRecordBatchSnafu)?;
165    Ok(Output::new_with_record_batches(batches))
166}
167
168/// Parses DDL submission options using the existing request defaults.
169pub(crate) fn parse_ddl_options(options: &OptionMap) -> Result<DdlSubmitOptions> {
170    let defaults = DdlSubmitOptions::default();
171    let wait = match options.get(DDL_WAIT) {
172        Some(value) => value.parse::<bool>().map_err(|_| {
173            InvalidSqlSnafu {
174                err_msg: format!("invalid DDL option '{DDL_WAIT}': '{value}'"),
175            }
176            .build()
177        })?,
178        None => defaults.wait,
179    };
180
181    let timeout = match options.get(DDL_TIMEOUT) {
182        Some(value) => parse_duration(value).map_err(|err| {
183            InvalidSqlSnafu {
184                err_msg: format!("invalid DDL option '{DDL_TIMEOUT}': '{value}': {err}"),
185            }
186            .build()
187        })?,
188        None => defaults.timeout,
189    };
190
191    Ok(DdlSubmitOptions { wait, timeout })
192}
193
194#[cfg(not(feature = "enterprise"))]
195fn supported_flow_options() -> String {
196    ALLOWED_FLOW_OPTIONS.join(", ")
197}
198
199fn normalize_flow_bool_option(key: &str, value: &str) -> Result<String> {
200    value
201        .trim()
202        .to_ascii_lowercase()
203        .parse::<bool>()
204        .map(|value| value.to_string())
205        .map_err(|_| {
206            InvalidSqlSnafu {
207                err_msg: format!("invalid flow option '{key}': '{value}'"),
208            }
209            .build()
210        })
211}
212
213fn validate_and_normalize_flow_options(
214    options: HashMap<String, String>,
215    eval_interval: Option<i64>,
216) -> Result<HashMap<String, String>> {
217    // Reject non-positive eval_interval (zero or negative).
218    if let Some(secs) = eval_interval
219        && secs <= 0
220    {
221        return InvalidSqlSnafu {
222            err_msg: format!("EVAL INTERVAL must be positive, got {secs} seconds"),
223        }
224        .fail();
225    }
226
227    options
228        .into_iter()
229        .map(|(key, value)| {
230            if matches!(
231                key.as_str(),
232                FlowType::FLOW_TYPE_KEY | INTERNAL_EVAL_OFFSET_KEY | INTERNAL_EVAL_SCHEDULE_KEY
233            ) {
234                return InvalidSqlSnafu {
235                    err_msg: format!("flow option '{key}' is reserved for internal use"),
236                }
237                .fail();
238            }
239
240            let normalized_value = match key.as_str() {
241                DEFER_ON_MISSING_SOURCE_KEY | FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY => {
242                    normalize_flow_bool_option(&key, &value)?
243                }
244                #[cfg(feature = "enterprise")]
245                _ => value,
246                #[cfg(not(feature = "enterprise"))]
247                _ => {
248                    return InvalidSqlSnafu {
249                        err_msg: format!(
250                            "unknown flow option '{key}', supported options: {}",
251                            supported_flow_options()
252                        ),
253                    }
254                    .fail();
255                }
256            };
257
258            Ok((key, normalized_value))
259        })
260        .collect()
261}
262
263/// Validates `EVAL OFFSET` semantics at the operator boundary: an offset is
264/// only legal together with `EVAL INTERVAL` and must lie in
265/// `[0, eval_interval)`. Never modulo-normalized.
266fn validate_eval_offset(
267    eval_offset_secs: Option<i64>,
268    eval_interval_secs: Option<i64>,
269) -> Result<()> {
270    if let Some(offset_secs) = eval_offset_secs {
271        let Some(eval_interval_secs) = eval_interval_secs else {
272            return InvalidSqlSnafu {
273                err_msg: "EVAL OFFSET requires EVAL INTERVAL to be specified".to_string(),
274            }
275            .fail();
276        };
277        if !(0..eval_interval_secs).contains(&offset_secs) {
278            return InvalidSqlSnafu {
279                err_msg: format!(
280                    "EVAL OFFSET must be in range [0, EVAL INTERVAL), got {offset_secs} seconds with EVAL INTERVAL {eval_interval_secs} seconds"
281                ),
282            }
283            .fail();
284        }
285    }
286    Ok(())
287}
288
289fn determine_flow_type_for_source_state(
290    flow_name: &str,
291    flow_options: &HashMap<String, String>,
292    has_missing_source_table: bool,
293    has_instant_ttl_source_table: bool,
294    force_batching: bool,
295) -> Result<Option<FlowType>> {
296    if has_instant_ttl_source_table && force_batching {
297        // The batching scheduler cannot read instant-TTL source tables, so
298        // reject this combination even when another source table is missing.
299        return InvalidSqlSnafu {
300            err_msg: format!(
301                "flow '{}' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode; use a TTL longer than the flush interval",
302                flow_name
303            ),
304        }
305        .fail();
306    }
307
308    if has_missing_source_table {
309        let defer_on_missing_source = flow_options
310            .get(DEFER_ON_MISSING_SOURCE_KEY)
311            .is_some_and(|value| value == "true");
312        ensure!(
313            defer_on_missing_source,
314            InvalidSqlSnafu {
315                err_msg: format!(
316                    "missing source tables for flow '{}'; use WITH ({DEFER_ON_MISSING_SOURCE_KEY} = true) to create a pending flow",
317                    flow_name
318                )
319            }
320        );
321        info!(
322            "Flow `{}` is created as a pending batching flow because source tables are missing and defer_on_missing_source=true",
323            flow_name
324        );
325        return Ok(Some(FlowType::Batching));
326    }
327
328    Ok(None)
329}
330
331/// The stateless streaming runtime accepts only a single source scan wrapped by
332/// projections and filters. Keep this check local to the operator: the flow
333/// validator is intentionally private to the flow crate.
334fn is_stateless_flow_plan(plan: &LogicalPlan) -> bool {
335    let mut scans = 0;
336    let mut supported_nodes = true;
337    let result = plan.apply_with_subqueries(|node| {
338        match node {
339            LogicalPlan::TableScan(_) => scans += 1,
340            LogicalPlan::Projection(_) | LogicalPlan::Filter(_) => {}
341            LogicalPlan::Distinct(Distinct::All(_)) => {}
342            _ => supported_nodes = false,
343        }
344        Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
345    });
346
347    result.is_ok() && supported_nodes && scans == 1
348}
349
350const INSTANT_TTL_FLOW_QUERY_ERROR: &str = "instant-TTL flow sources support only stateless projection/filter queries over one source; non-stateless queries require a persisted source";
351
352const STATELESS_FLOW_QUERY_ERROR: &str =
353    "flow streaming supports only stateless projection/filter queries over one source";
354
355impl StatementExecutor {
356    pub fn catalog_manager(&self) -> CatalogManagerRef {
357        self.catalog_manager.clone()
358    }
359
360    #[tracing::instrument(skip_all)]
361    pub async fn create_table(&self, stmt: CreateTable, ctx: QueryContextRef) -> Result<TableRef> {
362        let mut create_expr = self.prepare_create_table(&stmt, &ctx).await?;
363        self.create_table_inner(
364            &mut create_expr,
365            stmt.partitions,
366            ctx,
367            TriggerReason::Manual,
368        )
369        .await
370    }
371
372    async fn prepare_create_table(
373        &self,
374        stmt: &CreateTable,
375        ctx: &QueryContextRef,
376    ) -> Result<CreateTableExpr> {
377        let (catalog, schema, _table) = table_idents_to_full_name(&stmt.name, ctx)
378            .map_err(BoxedError::new)
379            .context(error::ExternalSnafu)?;
380
381        let schema_options = self
382            .table_metadata_manager
383            .schema_manager()
384            .get(SchemaNameKey {
385                catalog: &catalog,
386                schema: &schema,
387            })
388            .await
389            .context(TableMetadataManagerSnafu)?
390            .map(|v| v.into_inner());
391
392        let mut create_expr = expr_helper::create_to_expr(stmt, ctx)?;
393        // TTL and compaction options are handled separately; ingestion quota is database-only.
394        if let Some(schema_options) = schema_options {
395            for (key, value) in schema_options.extra_options.iter() {
396                if key == INGEST_ROWS_RATE_LIMIT_KEY || key.starts_with("compaction.") {
397                    continue;
398                }
399                create_expr
400                    .table_options
401                    .entry(key.clone())
402                    .or_insert(value.clone());
403            }
404        }
405
406        Ok(create_expr)
407    }
408
409    /// Prepares every explicit logical CREATE before submitting one batch procedure.
410    pub async fn batch_create_logical_tables(
411        &self,
412        statements: Vec<CreateTable>,
413        ctx: QueryContextRef,
414    ) -> Result<()> {
415        let mut expressions = Vec::with_capacity(statements.len());
416        let mut targets = std::collections::HashSet::new();
417        let mut group = None;
418        for statement in statements {
419            ensure!(
420                statement.engine == METRIC_ENGINE_NAME
421                    && statement.options.get(LOGICAL_TABLE_METADATA_KEY).is_some()
422                    && statement
423                        .options
424                        .value(PHYSICAL_TABLE_METADATA_KEY)
425                        .is_none(),
426                InvalidSqlSnafu {
427                    err_msg: "batch requires explicit Metric logical CREATE TABLE statements"
428                }
429            );
430            let expr = self.prepare_create_table(&statement, &ctx).await?;
431            let key = (
432                expr.catalog_name.clone(),
433                expr.schema_name.clone(),
434                expr.table_options.get(LOGICAL_TABLE_METADATA_KEY).cloned(),
435            );
436            ensure!(
437                group.as_ref().is_none_or(|group| group == &key),
438                InvalidSqlSnafu {
439                    err_msg: "batch must share catalog, schema and literal on_physical_table"
440                }
441            );
442            group = Some(key);
443            ensure!(
444                targets.insert(expr.table_name.clone()),
445                InvalidSqlSnafu {
446                    err_msg: "duplicate target in logical-table batch"
447                }
448            );
449            self.validate_logical_create(&expr, statement.partitions.as_ref(), &ctx)
450                .await?;
451            expressions.push(expr);
452        }
453        self.create_logical_tables(&expressions, ctx, TriggerReason::Manual)
454            .await?;
455        Ok(())
456    }
457
458    async fn validate_logical_create(
459        &self,
460        expr: &CreateTableExpr,
461        partitions: Option<&Partitions>,
462        ctx: &QueryContextRef,
463    ) -> Result<()> {
464        ensure_table_definition_writable(&expr.schema_name, &expr.table_name)?;
465        if let Some(partitions) = partitions
466            && !partitions.exprs.is_empty()
467        {
468            self.validate_logical_table_partition_rule(expr, partitions, ctx)
469                .await?;
470        }
471        Ok(())
472    }
473
474    #[tracing::instrument(skip_all)]
475    pub async fn create_table_like(
476        &self,
477        stmt: CreateTableLike,
478        ctx: QueryContextRef,
479    ) -> Result<TableRef> {
480        let (catalog, schema, table) = table_idents_to_full_name(&stmt.source_name, &ctx)
481            .map_err(BoxedError::new)
482            .context(error::ExternalSnafu)?;
483        let table_ref = self
484            .catalog_manager
485            .table(&catalog, &schema, &table, Some(&ctx))
486            .await
487            .context(CatalogSnafu)?
488            .context(TableNotFoundSnafu { table_name: &table })?;
489        let partition_info = self
490            .partition_manager
491            .find_physical_partition_info(table_ref.table_info().table_id())
492            .await
493            .context(error::FindTablePartitionRuleSnafu { table_name: table })?;
494
495        // CREATE TABLE LIKE also inherits database level options.
496        let schema_options = self
497            .table_metadata_manager
498            .schema_manager()
499            .get(SchemaNameKey {
500                catalog: &catalog,
501                schema: &schema,
502            })
503            .await
504            .context(TableMetadataManagerSnafu)?
505            .map(|v| v.into_inner());
506
507        let quote_style = ctx.quote_style();
508        let mut create_stmt =
509            create_table_stmt(&table_ref.table_info(), schema_options, quote_style)
510                .context(error::ParseQuerySnafu)?;
511        create_stmt.name = stmt.table_name;
512        create_stmt.if_not_exists = false;
513
514        let table_info = table_ref.table_info();
515        let partitions = create_partitions_stmt(&table_info, &partition_info.partitions)?.and_then(
516            |mut partitions| {
517                if !partitions.column_list.is_empty() {
518                    partitions.set_quote(quote_style);
519                    Some(partitions)
520                } else {
521                    None
522                }
523            },
524        );
525
526        let create_expr = &mut expr_helper::create_to_expr(&create_stmt, &ctx)?;
527        self.create_table_inner(create_expr, partitions, ctx, TriggerReason::Manual)
528            .await
529    }
530
531    #[tracing::instrument(skip_all)]
532    pub async fn create_external_table(
533        &self,
534        create_expr: CreateExternalTable,
535        ctx: QueryContextRef,
536    ) -> Result<TableRef> {
537        if create_expr.if_not_exists {
538            let (catalog_name, schema_name, table_name) =
539                table_idents_to_full_name(&create_expr.name, &ctx)
540                    .map_err(BoxedError::new)
541                    .context(ExternalSnafu)?;
542            if let Some(table) = self
543                .catalog_manager
544                .table(&catalog_name, &schema_name, &table_name, Some(&ctx))
545                .await
546                .context(CatalogSnafu)?
547            {
548                return Ok(table);
549            }
550        }
551
552        let create_expr = &mut expr_helper::create_external_expr(
553            create_expr,
554            &ctx,
555            &self.local_file_access,
556            &self.remote_storage_access,
557        )
558        .await?;
559        self.create_table_inner(create_expr, None, ctx, TriggerReason::Manual)
560            .await
561    }
562
563    /// Creates the declared-edge table with its canonical schema, entering
564    /// below the user-DDL guard ([`ensure_table_definition_writable`]).
565    /// `create_if_not_exists` makes concurrent first inserts race safely.
566    pub async fn create_declared_relationships_table(
567        &self,
568        catalog: &str,
569        query_ctx: QueryContextRef,
570    ) -> Result<TableRef> {
571        let mut expr = super::semantic_graph::build_declared_relationships_expr(catalog);
572        self.create_non_logic_table(&mut expr, None, query_ctx, TriggerReason::AutoCreate)
573            .await
574    }
575
576    #[tracing::instrument(skip_all)]
577    pub async fn create_table_inner(
578        &self,
579        create_table: &mut CreateTableExpr,
580        partitions: Option<Partitions>,
581        query_ctx: QueryContextRef,
582        trigger_reason: TriggerReason,
583    ) -> Result<TableRef> {
584        ensure_table_definition_writable(&create_table.schema_name, &create_table.table_name)?;
585
586        if create_table.engine == METRIC_ENGINE_NAME
587            && create_table
588                .table_options
589                .contains_key(LOGICAL_TABLE_METADATA_KEY)
590        {
591            self.validate_logical_create(create_table, partitions.as_ref(), &query_ctx)
592                .await?;
593            // Create logical tables
594            self.create_logical_tables(
595                std::slice::from_ref(create_table),
596                query_ctx,
597                trigger_reason,
598            )
599            .await?
600            .into_iter()
601            .next()
602            .context(error::UnexpectedSnafu {
603                violated: "expected to create logical tables",
604            })
605        } else {
606            // Create other normal table
607            self.create_non_logic_table(create_table, partitions, query_ctx, trigger_reason)
608                .await
609        }
610    }
611
612    #[tracing::instrument(skip_all)]
613    pub async fn create_non_logic_table(
614        &self,
615        create_table: &mut CreateTableExpr,
616        partitions: Option<Partitions>,
617        query_ctx: QueryContextRef,
618        trigger_reason: TriggerReason,
619    ) -> Result<TableRef> {
620        let _timer = crate::metrics::DIST_CREATE_TABLE.start_timer();
621
622        // Check if schema exists
623        let schema = self
624            .table_metadata_manager
625            .schema_manager()
626            .get(SchemaNameKey::new(
627                &create_table.catalog_name,
628                &create_table.schema_name,
629            ))
630            .await
631            .context(TableMetadataManagerSnafu)?;
632        ensure!(
633            schema.is_some(),
634            SchemaNotFoundSnafu {
635                schema_info: &create_table.schema_name,
636            }
637        );
638
639        // if table exists.
640        if let Some(table) = self
641            .catalog_manager
642            .table(
643                &create_table.catalog_name,
644                &create_table.schema_name,
645                &create_table.table_name,
646                Some(&query_ctx),
647            )
648            .await
649            .context(CatalogSnafu)?
650        {
651            return if create_table.create_if_not_exists {
652                Ok(table)
653            } else {
654                TableAlreadyExistsSnafu {
655                    table: format_full_table_name(
656                        &create_table.catalog_name,
657                        &create_table.schema_name,
658                        &create_table.table_name,
659                    ),
660                }
661                .fail()
662            };
663        }
664
665        ensure!(
666            NAME_PATTERN_REG.is_match(&create_table.table_name),
667            InvalidTableNameSnafu {
668                table_name: &create_table.table_name,
669            }
670        );
671
672        let table_name = TableName::new(
673            &create_table.catalog_name,
674            &create_table.schema_name,
675            &create_table.table_name,
676        );
677
678        let (partitions, partition_cols) = parse_partitions(create_table, partitions, &query_ctx)?;
679        let mut table_info = create_table_info(create_table, partition_cols)?;
680
681        let resp = self
682            .create_table_procedure(
683                create_table.clone(),
684                partitions,
685                table_info.clone(),
686                query_ctx,
687                trigger_reason,
688            )
689            .await?;
690
691        let table_id = resp
692            .table_ids
693            .into_iter()
694            .next()
695            .context(error::UnexpectedSnafu {
696                violated: "expected table_id",
697            })?;
698        info!("Successfully created table '{table_name}' with table id {table_id}");
699
700        table_info.ident.table_id = table_id;
701
702        let table_info = Arc::new(table_info);
703        create_table.table_id = Some(api::v1::TableId { id: table_id });
704
705        let table = DistTable::table(table_info);
706
707        Ok(table)
708    }
709
710    #[tracing::instrument(skip_all)]
711    pub async fn create_logical_tables(
712        &self,
713        create_table_exprs: &[CreateTableExpr],
714        query_context: QueryContextRef,
715        trigger_reason: TriggerReason,
716    ) -> Result<Vec<TableRef>> {
717        let _timer = crate::metrics::DIST_CREATE_TABLES.start_timer();
718        ensure!(
719            !create_table_exprs.is_empty(),
720            EmptyDdlExprSnafu {
721                name: "create logic tables"
722            }
723        );
724
725        // Retention is enforced on the physical table only. Drop it from logical
726        // creates (ingest hints, DDL exported by older versions), but keep
727        // `ttl=instant`: the inserter reads it from the logical table to forward
728        // rows to flows without persisting them.
729        let create_table_exprs = create_table_exprs
730            .iter()
731            .cloned()
732            .map(|mut create| {
733                if create
734                    .table_options
735                    .get(TTL_KEY)
736                    .is_some_and(|ttl| is_retention_ttl(ttl))
737                {
738                    create.table_options.remove(TTL_KEY);
739                }
740                create
741            })
742            .collect::<Vec<_>>();
743
744        // Check table names
745        for create_table in &create_table_exprs {
746            ensure!(
747                NAME_PATTERN_REG.is_match(&create_table.table_name),
748                InvalidTableNameSnafu {
749                    table_name: &create_table.table_name,
750                }
751            );
752        }
753
754        let raw_tables_info = create_table_exprs
755            .iter()
756            .map(|create| create_table_info(create, vec![]))
757            .collect::<Result<Vec<_>>>()?;
758        let tables_data = create_table_exprs
759            .iter()
760            .cloned()
761            .zip(raw_tables_info.iter().cloned())
762            .collect::<Vec<_>>();
763
764        let resp = self
765            .create_logical_tables_procedure(tables_data, query_context.clone(), trigger_reason)
766            .await?;
767
768        let table_ids = resp.table_ids;
769        ensure!(
770            table_ids.len() == raw_tables_info.len(),
771            CreateLogicalTablesSnafu {
772                reason: format!(
773                    "The number of tables is inconsistent with the expected number to be created, expected: {}, actual: {}",
774                    raw_tables_info.len(),
775                    table_ids.len()
776                )
777            }
778        );
779        info!("Successfully created logical tables: {:?}", table_ids);
780
781        // Reacquire table infos from catalog so logical tables inherit the latest partition
782        // metadata (e.g. partition_key_indices) from their physical tables.
783        // And the returned table info also included extra partition columns that are in physical table but not in logical table's create table expr
784        let mut tables_info = Vec::with_capacity(table_ids.len());
785        for (table_id, create_table) in table_ids.iter().zip(create_table_exprs.iter()) {
786            let table = self
787                .catalog_manager
788                .table(
789                    &create_table.catalog_name,
790                    &create_table.schema_name,
791                    &create_table.table_name,
792                    Some(&query_context),
793                )
794                .await
795                .context(CatalogSnafu)?
796                .with_context(|| TableNotFoundSnafu {
797                    table_name: format_full_table_name(
798                        &create_table.catalog_name,
799                        &create_table.schema_name,
800                        &create_table.table_name,
801                    ),
802                })?;
803
804            let table_info = table.table_info();
805            // Safety check: ensure we are returning the table info that matches the newly created table id.
806            ensure!(
807                table_info.table_id() == *table_id,
808                CreateLogicalTablesSnafu {
809                    reason: format!(
810                        "Table id mismatch after creation, expected {}, got {} for table {}",
811                        table_id,
812                        table_info.table_id(),
813                        format_full_table_name(
814                            &create_table.catalog_name,
815                            &create_table.schema_name,
816                            &create_table.table_name
817                        )
818                    )
819                }
820            );
821
822            tables_info.push(table_info);
823        }
824
825        Ok(tables_info.into_iter().map(DistTable::table).collect())
826    }
827
828    async fn validate_logical_table_partition_rule(
829        &self,
830        create_table: &CreateTableExpr,
831        partitions: &Partitions,
832        query_ctx: &QueryContextRef,
833    ) -> Result<()> {
834        let (_, mut logical_partition_exprs) =
835            parse_partitions_for_logical_validation(create_table, partitions, query_ctx)?;
836
837        let physical_table_name = create_table
838            .table_options
839            .get(LOGICAL_TABLE_METADATA_KEY)
840            .with_context(|| CreateLogicalTablesSnafu {
841                reason: format!(
842                    "expect `{LOGICAL_TABLE_METADATA_KEY}` option on creating logical table"
843                ),
844            })?;
845
846        let physical_table = self
847            .catalog_manager
848            .table(
849                &create_table.catalog_name,
850                &create_table.schema_name,
851                physical_table_name,
852                Some(query_ctx),
853            )
854            .await
855            .context(CatalogSnafu)?
856            .context(TableNotFoundSnafu {
857                table_name: physical_table_name.clone(),
858            })?;
859
860        let physical_table_info = physical_table.table_info();
861        let (partition_rule, _) = self
862            .partition_manager
863            .find_table_partition_rule(&physical_table_info)
864            .await
865            .context(error::FindTablePartitionRuleSnafu {
866                table_name: physical_table_name.clone(),
867            })?;
868
869        let multi_dim_rule = partition_rule
870            .as_ref()
871            .as_any()
872            .downcast_ref::<MultiDimPartitionRule>()
873            .context(InvalidPartitionRuleSnafu {
874                reason: "physical table partition rule is not range-based",
875            })?;
876
877        // TODO(ruihang): project physical partition exprs to logical partition column
878        let mut physical_partition_exprs = multi_dim_rule.exprs().to_vec();
879        logical_partition_exprs.sort_unstable();
880        physical_partition_exprs.sort_unstable();
881
882        ensure!(
883            physical_partition_exprs == logical_partition_exprs,
884            InvalidPartitionRuleSnafu {
885                reason: format!(
886                    "logical table partition rule must match the corresponding physical table's\n logical table partition exprs:\t\t {:?}\n physical table partition exprs:\t {:?}",
887                    logical_partition_exprs, physical_partition_exprs
888                ),
889            }
890        );
891
892        Ok(())
893    }
894
895    #[cfg(feature = "enterprise")]
896    #[tracing::instrument(skip_all)]
897    pub async fn create_trigger(
898        &self,
899        stmt: CreateTrigger,
900        query_context: QueryContextRef,
901    ) -> Result<Output> {
902        let expr = expr_helper::to_create_trigger_task_expr(stmt, &query_context)?;
903        self.create_trigger_inner(expr, query_context).await
904    }
905
906    #[cfg(feature = "enterprise")]
907    pub async fn create_trigger_inner(
908        &self,
909        expr: PbCreateTriggerExpr,
910        query_context: QueryContextRef,
911    ) -> Result<Output> {
912        self.create_trigger_procedure(expr, query_context).await?;
913        Ok(Output::new_with_affected_rows(0))
914    }
915
916    #[cfg(feature = "enterprise")]
917    async fn create_trigger_procedure(
918        &self,
919        expr: PbCreateTriggerExpr,
920        query_context: QueryContextRef,
921    ) -> Result<SubmitDdlTaskResponse> {
922        let task = CreateTriggerTask::try_from(PbCreateTriggerTask {
923            create_trigger: Some(expr),
924        })
925        .context(error::InvalidExprSnafu)?;
926
927        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
928        let request = SubmitDdlTaskRequest::new(DdlTask::new_create_trigger(task));
929
930        self.procedure_executor
931            .submit_ddl_task(executor_context, request)
932            .await
933            .context(error::ExecuteDdlSnafu)
934    }
935
936    #[tracing::instrument(skip_all)]
937    pub async fn create_flow(
938        &self,
939        stmt: CreateFlow,
940        query_context: QueryContextRef,
941    ) -> Result<Output> {
942        // TODO(ruihang): do some verification
943        let eval_offset_secs = stmt.eval_offset;
944        let expr = expr_helper::to_create_flow_task_expr(stmt, &query_context)?;
945
946        // The typed `EVAL OFFSET` comes straight from the parsed SQL AST; it is
947        // the only trusted source of the offset at this boundary.
948        self.create_flow_procedure(expr, eval_offset_secs, query_context)
949            .await?;
950        Ok(Output::new_with_affected_rows(0))
951    }
952
953    /// Direct gRPC entry point for `CREATE FLOW`.
954    pub async fn create_flow_inner(
955        &self,
956        expr: CreateFlowExpr,
957        query_context: QueryContextRef,
958    ) -> Result<Output> {
959        self.create_flow_procedure(expr, None, query_context)
960            .await?;
961        Ok(Output::new_with_affected_rows(0))
962    }
963
964    async fn create_flow_procedure(
965        &self,
966        mut expr: CreateFlowExpr,
967        eval_offset_secs: Option<i64>,
968        query_context: QueryContextRef,
969    ) -> Result<SubmitDdlTaskResponse> {
970        let eval_interval_secs = expr.eval_interval.as_ref().map(|e| e.seconds);
971
972        // Reject non-positive eval_interval (zero or negative).
973        if let Some(secs) = eval_interval_secs
974            && secs <= 0
975        {
976            return InvalidSqlSnafu {
977                err_msg: format!("EVAL INTERVAL must be positive, got {secs} seconds"),
978            }
979            .fail();
980        }
981
982        // Validate EVAL OFFSET semantics at the operator boundary (defense in
983        // depth; the parser already enforces them deterministically). The
984        // offset arrives as a typed parameter, never from `flow_options`.
985        validate_eval_offset(eval_offset_secs, eval_interval_secs)?;
986
987        // Validate user options. `validate_and_normalize_flow_options` also
988        // rejects the internal transport keys, so a spoofed key smuggled into
989        // the expr can never be honored here.
990        expr.flow_options =
991            validate_and_normalize_flow_options(expr.flow_options, eval_interval_secs)?;
992
993        let flow_type = self
994            .determine_flow_type(&expr, query_context.clone())
995            .await?;
996        info!("determined flow={} type: {:#?}", expr.flow_name, flow_type);
997
998        expr.flow_options
999            .insert(FlowType::FLOW_TYPE_KEY.to_string(), flow_type.to_string());
1000
1001        let mut task = CreateFlowTask::try_from(PbCreateFlowTask {
1002            create_flow: Some(expr),
1003        })
1004        .context(error::InvalidExprSnafu)?;
1005        task.eval_offset_secs = eval_offset_secs;
1006        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
1007        let request = SubmitDdlTaskRequest::new(DdlTask::new_create_flow(task));
1008
1009        self.procedure_executor
1010            .submit_ddl_task(executor_context, request)
1011            .await
1012            .context(error::ExecuteDdlSnafu)
1013    }
1014
1015    /// Determines the flow type from source-table state, schedule requirements,
1016    /// and SQL shape.
1017    ///
1018    /// Aggregates and persisted-source DISTINCT use batching. Plain DISTINCT is request-local only
1019    /// for instant-TTL sources, where it retains the legacy streaming compatibility behavior.
1020    async fn determine_flow_type(
1021        &self,
1022        expr: &CreateFlowExpr,
1023        query_ctx: QueryContextRef,
1024    ) -> Result<FlowType> {
1025        let has_eval_interval = expr.eval_interval.is_some();
1026
1027        let mut has_missing_source_table = false;
1028        let mut has_instant_ttl_source_table = false;
1029
1030        for src_table_name in &expr.source_table_names {
1031            let table = self
1032                .catalog_manager()
1033                .table(
1034                    &src_table_name.catalog_name,
1035                    &src_table_name.schema_name,
1036                    &src_table_name.table_name,
1037                    Some(&query_ctx),
1038                )
1039                .await
1040                .map_err(BoxedError::new)
1041                .context(ExternalSnafu)?;
1042
1043            let Some(table) = table else {
1044                has_missing_source_table = true;
1045                continue;
1046            };
1047
1048            if table.table_info().meta.options.ttl == Some(common_time::TimeToLive::Instant) {
1049                warn!(
1050                    "Source table `{}` for flow `{}`'s ttl=instant, {}",
1051                    format_full_table_name(
1052                        &src_table_name.catalog_name,
1053                        &src_table_name.schema_name,
1054                        &src_table_name.table_name
1055                    ),
1056                    expr.flow_name,
1057                    if has_eval_interval {
1058                        "rejecting flow because EVAL INTERVAL requires the batching scheduler which does not support instant TTL"
1059                    } else {
1060                        "fallback to streaming mode"
1061                    }
1062                );
1063                has_instant_ttl_source_table = true;
1064            }
1065        }
1066
1067        if let Some(flow_type) = determine_flow_type_for_source_state(
1068            &expr.flow_name,
1069            &expr.flow_options,
1070            has_missing_source_table,
1071            has_instant_ttl_source_table,
1072            has_eval_interval,
1073        )? {
1074            return Ok(flow_type);
1075        }
1076
1077        // A flow with `EVAL INTERVAL` (and therefore possibly `EVAL OFFSET`)
1078        // always uses the batching scheduler: the fixed epoch-phase schedule is
1079        // only honored by the batching scheduler, regardless of the SQL shape.
1080        // Non-aggregate SQL is supported as an explicit full-query flow (the
1081        // batching engine requires a time-window expression or EVAL INTERVAL).
1082        if has_eval_interval {
1083            return Ok(FlowType::Batching);
1084        }
1085
1086        let engine = &self.query_engine;
1087        let stmts = ParserContext::create_with_dialect(
1088            &expr.sql,
1089            query_ctx.sql_dialect(),
1090            ParseOptions::default(),
1091        )
1092        .map_err(BoxedError::new)
1093        .context(ExternalSnafu)?;
1094
1095        ensure!(
1096            stmts.len() == 1,
1097            InvalidSqlSnafu {
1098                err_msg: format!("Expect only one statement, found {}", stmts.len())
1099            }
1100        );
1101        let stmt = &stmts[0];
1102
1103        let is_tql_query = is_tql(query_ctx.sql_dialect(), &expr.sql)
1104            .map_err(BoxedError::new)
1105            .context(ExternalSnafu)?;
1106        if is_tql_query {
1107            if has_instant_ttl_source_table {
1108                return InvalidSqlSnafu {
1109                    err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(),
1110                }
1111                .fail();
1112            }
1113            return Ok(FlowType::Batching);
1114        }
1115
1116        // Plan before selecting a mode. In particular, instant-TTL sources
1117        // must not bypass validation of the stateless streaming subset.
1118        let plan = match stmt {
1119            Statement::Tql(_) => {
1120                if has_instant_ttl_source_table {
1121                    return InvalidSqlSnafu {
1122                        err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(),
1123                    }
1124                    .fail();
1125                }
1126                return Ok(FlowType::Batching);
1127            }
1128            _ => engine
1129                .planner()
1130                .plan(&QueryStatement::Sql(stmt.clone()), query_ctx)
1131                .await
1132                .map_err(BoxedError::new)
1133                .context(ExternalSnafu)?,
1134        };
1135
1136        /// Visitor to classify aggregation and DISTINCT separately. Plain DISTINCT is request
1137        /// local only for instant-TTL sources; persisted-source DISTINCT keeps batching semantics.
1138        struct FindQueryShape {
1139            is_aggr: bool,
1140            is_distinct: bool,
1141            has_distinct_on: bool,
1142        }
1143
1144        impl TreeNodeVisitor<'_> for FindQueryShape {
1145            type Node = LogicalPlan;
1146            fn f_down(
1147                &mut self,
1148                node: &Self::Node,
1149            ) -> datafusion_common::Result<datafusion_common::tree_node::TreeNodeRecursion>
1150            {
1151                match node {
1152                    LogicalPlan::Aggregate(_) => self.is_aggr = true,
1153                    LogicalPlan::Distinct(Distinct::All(_)) => self.is_distinct = true,
1154                    LogicalPlan::Distinct(Distinct::On(_)) => self.has_distinct_on = true,
1155                    _ => (),
1156                }
1157                Ok(datafusion_common::tree_node::TreeNodeRecursion::Continue)
1158            }
1159        }
1160
1161        let mut query_shape = FindQueryShape {
1162            is_aggr: false,
1163            is_distinct: false,
1164            has_distinct_on: false,
1165        };
1166
1167        plan.visit_with_subqueries(&mut query_shape)
1168            .context(BuildDfLogicalPlanSnafu)?;
1169        if query_shape.has_distinct_on {
1170            return InvalidSqlSnafu {
1171                err_msg: if has_instant_ttl_source_table {
1172                    INSTANT_TTL_FLOW_QUERY_ERROR.to_string()
1173                } else {
1174                    STATELESS_FLOW_QUERY_ERROR.to_string()
1175                },
1176            }
1177            .fail();
1178        }
1179        if query_shape.is_aggr {
1180            return if has_instant_ttl_source_table {
1181                InvalidSqlSnafu {
1182                    err_msg: INSTANT_TTL_FLOW_QUERY_ERROR.to_string(),
1183                }
1184                .fail()
1185            } else {
1186                Ok(FlowType::Batching)
1187            };
1188        }
1189        if query_shape.is_distinct && !has_instant_ttl_source_table {
1190            return Ok(FlowType::Batching);
1191        }
1192
1193        ensure!(
1194            is_stateless_flow_plan(&plan),
1195            InvalidSqlSnafu {
1196                err_msg: if has_instant_ttl_source_table {
1197                    INSTANT_TTL_FLOW_QUERY_ERROR.to_string()
1198                } else {
1199                    STATELESS_FLOW_QUERY_ERROR.to_string()
1200                },
1201            }
1202        );
1203        Ok(FlowType::Streaming)
1204    }
1205
1206    #[tracing::instrument(skip_all)]
1207    pub async fn create_view(
1208        &self,
1209        create_view: CreateView,
1210        ctx: QueryContextRef,
1211    ) -> Result<TableRef> {
1212        // convert input into logical plan
1213        let logical_plan = match &*create_view.query {
1214            Statement::Query(query) => {
1215                self.plan(
1216                    &QueryStatement::Sql(Statement::Query(query.clone())),
1217                    ctx.clone(),
1218                )
1219                .await?
1220            }
1221            Statement::Tql(query) => {
1222                // The serialized view plan must not depend on the native execution extension.
1223                let mut view_ctx = ctx.as_ref().clone();
1224                view_ctx.set_extension(NATIVE_PROMQL_EXTENSION_KEY, "false");
1225                self.plan_tql(query.clone(), &Arc::new(view_ctx)).await?
1226            }
1227            _ => {
1228                return InvalidViewStmtSnafu {}.fail();
1229            }
1230        };
1231        // Save the definition for `show create view`.
1232        let definition = create_view.to_string();
1233
1234        // Save the columns in plan, it may changed when the schemas of tables in plan
1235        // are altered.
1236        let schema: Schema = logical_plan
1237            .schema()
1238            .clone()
1239            .try_into()
1240            .context(ConvertSchemaSnafu)?;
1241        let plan_columns: Vec<_> = schema
1242            .column_schemas()
1243            .iter()
1244            .map(|c| c.name.clone())
1245            .collect();
1246
1247        let columns: Vec<_> = create_view
1248            .columns
1249            .iter()
1250            .map(|ident| ident.to_string())
1251            .collect();
1252
1253        // Validate columns
1254        if !columns.is_empty() {
1255            ensure!(
1256                columns.len() == plan_columns.len(),
1257                error::ViewColumnsMismatchSnafu {
1258                    view_name: create_view.name.to_string(),
1259                    expected: plan_columns.len(),
1260                    actual: columns.len(),
1261                }
1262            );
1263        }
1264
1265        // Extract the table names from the original plan
1266        // and rewrite them as fully qualified names.
1267        let (table_names, plan) = extract_and_rewrite_full_table_names(logical_plan, ctx.clone())
1268            .context(ExtractTableNamesSnafu)?;
1269
1270        let table_names = table_names.into_iter().map(|t| t.into()).collect();
1271
1272        // TODO(dennis): we don't save the optimized plan yet,
1273        // because there are some serialization issue with our own defined plan node (such as `MergeScanLogicalPlan`).
1274        // When the issues are fixed, we can use the `optimized_plan` instead.
1275        // let optimized_plan = self.optimize_logical_plan(logical_plan)?.unwrap_df_plan();
1276
1277        // encode logical plan
1278        let encoded_plan = DFLogicalSubstraitConvertor
1279            .encode(&plan, DefaultSerializer)
1280            .context(SubstraitCodecSnafu)?;
1281
1282        let expr = expr_helper::to_create_view_expr(
1283            create_view,
1284            encoded_plan.to_vec(),
1285            table_names,
1286            columns,
1287            plan_columns,
1288            definition,
1289            ctx.clone(),
1290        )?;
1291
1292        // TODO(dennis): validate the logical plan
1293        self.create_view_by_expr(expr, ctx).await
1294    }
1295
1296    pub async fn create_view_by_expr(
1297        &self,
1298        expr: CreateViewExpr,
1299        ctx: QueryContextRef,
1300    ) -> Result<TableRef> {
1301        // A view could otherwise squat a reserved name and block the canonical
1302        // table's first-write creation.
1303        ensure_table_definition_writable(&expr.schema_name, &expr.view_name)?;
1304        ensure! {
1305            !(expr.create_if_not_exists & expr.or_replace),
1306            InvalidSqlSnafu {
1307                err_msg: "syntax error Create Or Replace and If Not Exist cannot be used together",
1308            }
1309        };
1310        let _timer = crate::metrics::DIST_CREATE_VIEW.start_timer();
1311
1312        let schema_exists = self
1313            .table_metadata_manager
1314            .schema_manager()
1315            .exists(SchemaNameKey::new(&expr.catalog_name, &expr.schema_name))
1316            .await
1317            .context(TableMetadataManagerSnafu)?;
1318
1319        ensure!(
1320            schema_exists,
1321            SchemaNotFoundSnafu {
1322                schema_info: &expr.schema_name,
1323            }
1324        );
1325
1326        // if view or table exists.
1327        if let Some(table) = self
1328            .catalog_manager
1329            .table(
1330                &expr.catalog_name,
1331                &expr.schema_name,
1332                &expr.view_name,
1333                Some(&ctx),
1334            )
1335            .await
1336            .context(CatalogSnafu)?
1337        {
1338            let table_type = table.table_info().table_type;
1339
1340            match (table_type, expr.create_if_not_exists, expr.or_replace) {
1341                (TableType::View, true, false) => {
1342                    return Ok(table);
1343                }
1344                (TableType::View, false, false) => {
1345                    return ViewAlreadyExistsSnafu {
1346                        name: format_full_table_name(
1347                            &expr.catalog_name,
1348                            &expr.schema_name,
1349                            &expr.view_name,
1350                        ),
1351                    }
1352                    .fail();
1353                }
1354                (TableType::View, _, true) => {
1355                    // Try to replace an exists view
1356                }
1357                _ => {
1358                    return TableAlreadyExistsSnafu {
1359                        table: format_full_table_name(
1360                            &expr.catalog_name,
1361                            &expr.schema_name,
1362                            &expr.view_name,
1363                        ),
1364                    }
1365                    .fail();
1366                }
1367            }
1368        }
1369
1370        ensure!(
1371            NAME_PATTERN_REG.is_match(&expr.view_name),
1372            InvalidViewNameSnafu {
1373                name: expr.view_name.clone(),
1374            }
1375        );
1376
1377        let view_name = TableName::new(&expr.catalog_name, &expr.schema_name, &expr.view_name);
1378
1379        let mut view_info = TableInfo {
1380            ident: metadata::TableIdent {
1381                // The view id of distributed table is assigned by Meta, set "0" here as a placeholder.
1382                table_id: 0,
1383                version: 0,
1384            },
1385            name: expr.view_name.clone(),
1386            desc: None,
1387            catalog_name: expr.catalog_name.clone(),
1388            schema_name: expr.schema_name.clone(),
1389            // The meta doesn't make sense for views, so using a default one.
1390            meta: TableMeta::empty(),
1391            table_type: TableType::View,
1392        };
1393
1394        let executor_context = to_executor_context(ctx, TriggerReason::Manual);
1395        let request = SubmitDdlTaskRequest::new(DdlTask::new_create_view(expr, view_info.clone()));
1396
1397        let resp = self
1398            .procedure_executor
1399            .submit_ddl_task(executor_context, request)
1400            .await
1401            .context(error::ExecuteDdlSnafu)?;
1402
1403        debug!(
1404            "Submit creating view '{view_name}' task response: {:?}",
1405            resp
1406        );
1407
1408        let view_id = resp
1409            .table_ids
1410            .into_iter()
1411            .next()
1412            .context(error::UnexpectedSnafu {
1413                violated: "expected table_id",
1414            })?;
1415        info!("Successfully created view '{view_name}' with view id {view_id}");
1416
1417        view_info.ident.table_id = view_id;
1418
1419        let view_info = Arc::new(view_info);
1420
1421        let table = DistTable::table(view_info);
1422
1423        // Invalidates local cache ASAP.
1424        self.cache_invalidator
1425            .invalidate(
1426                &Context::default(),
1427                &[
1428                    CacheIdent::TableId(view_id),
1429                    CacheIdent::TableName(view_name.clone()),
1430                ],
1431            )
1432            .await
1433            .context(error::InvalidateTableCacheSnafu)?;
1434
1435        Ok(table)
1436    }
1437
1438    #[tracing::instrument(skip_all)]
1439    pub async fn drop_flow(
1440        &self,
1441        catalog_name: String,
1442        flow_name: String,
1443        drop_if_exists: bool,
1444        query_context: QueryContextRef,
1445    ) -> Result<Output> {
1446        if let Some(flow) = self
1447            .flow_metadata_manager
1448            .flow_name_manager()
1449            .get(&catalog_name, &flow_name)
1450            .await
1451            .context(error::TableMetadataManagerSnafu)?
1452        {
1453            let flow_id = flow.flow_id();
1454            let task = DropFlowTask {
1455                catalog_name,
1456                flow_name,
1457                flow_id,
1458                drop_if_exists,
1459            };
1460            self.drop_flow_procedure(task, query_context).await?;
1461
1462            Ok(Output::new_with_affected_rows(0))
1463        } else if drop_if_exists {
1464            Ok(Output::new_with_affected_rows(0))
1465        } else {
1466            FlowNotFoundSnafu {
1467                flow_name: format_full_flow_name(&catalog_name, &flow_name),
1468            }
1469            .fail()
1470        }
1471    }
1472
1473    async fn drop_flow_procedure(
1474        &self,
1475        expr: DropFlowTask,
1476        query_context: QueryContextRef,
1477    ) -> Result<SubmitDdlTaskResponse> {
1478        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
1479        let request = SubmitDdlTaskRequest::new(DdlTask::new_drop_flow(expr));
1480
1481        self.procedure_executor
1482            .submit_ddl_task(executor_context, request)
1483            .await
1484            .context(error::ExecuteDdlSnafu)
1485    }
1486
1487    #[cfg(feature = "enterprise")]
1488    #[tracing::instrument(skip_all)]
1489    pub(super) async fn drop_trigger(
1490        &self,
1491        catalog_name: String,
1492        trigger_name: String,
1493        drop_if_exists: bool,
1494        query_context: QueryContextRef,
1495    ) -> Result<Output> {
1496        let task = DropTriggerTask {
1497            catalog_name,
1498            trigger_name,
1499            drop_if_exists,
1500        };
1501        self.drop_trigger_procedure(task, query_context).await?;
1502        Ok(Output::new_with_affected_rows(0))
1503    }
1504
1505    #[cfg(feature = "enterprise")]
1506    async fn drop_trigger_procedure(
1507        &self,
1508        expr: DropTriggerTask,
1509        query_context: QueryContextRef,
1510    ) -> Result<SubmitDdlTaskResponse> {
1511        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
1512        let request = SubmitDdlTaskRequest::new(DdlTask::new_drop_trigger(expr));
1513
1514        self.procedure_executor
1515            .submit_ddl_task(executor_context, request)
1516            .await
1517            .context(error::ExecuteDdlSnafu)
1518    }
1519
1520    /// Drop a view
1521    #[tracing::instrument(skip_all)]
1522    pub async fn drop_view(
1523        &self,
1524        catalog: String,
1525        schema: String,
1526        view: String,
1527        drop_if_exists: bool,
1528        query_context: QueryContextRef,
1529    ) -> Result<Output> {
1530        let view_info = if let Some(view) = self
1531            .catalog_manager
1532            .table(&catalog, &schema, &view, None)
1533            .await
1534            .context(CatalogSnafu)?
1535        {
1536            view.table_info()
1537        } else if drop_if_exists {
1538            // DROP VIEW IF EXISTS meets view not found - ignored
1539            return Ok(Output::new_with_affected_rows(0));
1540        } else {
1541            return TableNotFoundSnafu {
1542                table_name: format_full_table_name(&catalog, &schema, &view),
1543            }
1544            .fail();
1545        };
1546
1547        // Ensure the exists one is view, we can't drop other table types
1548        ensure!(
1549            view_info.table_type == TableType::View,
1550            error::InvalidViewSnafu {
1551                msg: "not a view",
1552                view_name: format_full_table_name(&catalog, &schema, &view),
1553            }
1554        );
1555
1556        let view_id = view_info.table_id();
1557        let view_name = TableName::new(&catalog, &schema, &view);
1558
1559        let task = DropViewTask {
1560            catalog,
1561            schema,
1562            view,
1563            view_id,
1564            drop_if_exists,
1565        };
1566
1567        self.drop_view_procedure(task, query_context).await?;
1568
1569        // Invalidates local cache ASAP.
1570        self.cache_invalidator
1571            .invalidate(
1572                &Context::default(),
1573                &[
1574                    CacheIdent::TableId(view_id),
1575                    CacheIdent::TableName(view_name),
1576                ],
1577            )
1578            .await
1579            .context(error::InvalidateTableCacheSnafu)?;
1580
1581        Ok(Output::new_with_affected_rows(0))
1582    }
1583
1584    /// Submit [DropViewTask] to procedure executor.
1585    async fn drop_view_procedure(
1586        &self,
1587        expr: DropViewTask,
1588        query_context: QueryContextRef,
1589    ) -> Result<SubmitDdlTaskResponse> {
1590        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
1591        let request = SubmitDdlTaskRequest::new(DdlTask::new_drop_view(expr));
1592
1593        self.procedure_executor
1594            .submit_ddl_task(executor_context, request)
1595            .await
1596            .context(error::ExecuteDdlSnafu)
1597    }
1598
1599    #[tracing::instrument(skip_all)]
1600    pub async fn alter_logical_tables(
1601        &self,
1602        alter_table_exprs: Vec<AlterTableExpr>,
1603        query_context: QueryContextRef,
1604        trigger_reason: TriggerReason,
1605    ) -> Result<Output> {
1606        let mut tables = Vec::with_capacity(alter_table_exprs.len());
1607        for expr in alter_table_exprs {
1608            // Get table_id from catalog_manager
1609            let catalog = if expr.catalog_name.is_empty() {
1610                query_context.current_catalog()
1611            } else {
1612                &expr.catalog_name
1613            };
1614            let schema = if expr.schema_name.is_empty() {
1615                query_context.current_schema()
1616            } else {
1617                expr.schema_name.clone()
1618            };
1619            let table_name = &expr.table_name;
1620            let table = self
1621                .catalog_manager
1622                .table(catalog, &schema, table_name, Some(&query_context))
1623                .await
1624                .context(CatalogSnafu)?
1625                .with_context(|| TableNotFoundSnafu {
1626                    table_name: format_full_table_name(catalog, &schema, table_name),
1627                })?;
1628            let table_id = table.table_info().ident.table_id;
1629            tables.push((table_id, expr));
1630        }
1631        self.alter_logical_tables_with_ids(tables, query_context, trigger_reason)
1632            .await
1633    }
1634
1635    /// Alters the captured table generations, rejecting concurrent drop/recreate under DDL locks.
1636    pub(crate) async fn alter_logical_tables_with_ids(
1637        &self,
1638        tables: Vec<(TableId, AlterTableExpr)>,
1639        query_context: QueryContextRef,
1640        trigger_reason: TriggerReason,
1641    ) -> Result<Output> {
1642        let _timer = crate::metrics::DIST_ALTER_TABLES.start_timer();
1643        ensure!(
1644            !tables.is_empty(),
1645            EmptyDdlExprSnafu {
1646                name: "alter logical tables"
1647            }
1648        );
1649        let mut groups: HashMap<TableId, Vec<(TableId, AlterTableExpr)>> = HashMap::new();
1650        for (table_id, expr) in tables {
1651            let physical_table_id = self
1652                .table_metadata_manager
1653                .table_route_manager()
1654                .get_physical_table_id(table_id)
1655                .await
1656                .context(TableMetadataManagerSnafu)?;
1657            groups
1658                .entry(physical_table_id)
1659                .or_default()
1660                .push((table_id, expr));
1661        }
1662
1663        // Submit procedure for each physical table
1664        let mut handles = Vec::with_capacity(groups.len());
1665        for (physical_table_id, exprs) in groups {
1666            let fut = self.alter_logical_tables_procedure(
1667                physical_table_id,
1668                exprs,
1669                query_context.clone(),
1670                trigger_reason,
1671            );
1672            handles.push(fut);
1673        }
1674        let _results = futures::future::try_join_all(handles).await?;
1675
1676        Ok(Output::new_with_affected_rows(0))
1677    }
1678
1679    #[tracing::instrument(skip_all)]
1680    pub async fn drop_table(
1681        &self,
1682        table_name: TableName,
1683        drop_if_exists: bool,
1684        query_context: QueryContextRef,
1685    ) -> Result<Output> {
1686        // Reserved for grpc call
1687        self.drop_tables(&[table_name], drop_if_exists, query_context)
1688            .await
1689    }
1690
1691    #[tracing::instrument(skip_all)]
1692    pub async fn drop_tables(
1693        &self,
1694        table_names: &[TableName],
1695        drop_if_exists: bool,
1696        query_context: QueryContextRef,
1697    ) -> Result<Output> {
1698        let mut tables = Vec::with_capacity(table_names.len());
1699        for table_name in table_names {
1700            ensure_table_writable(&table_name.schema_name, &table_name.table_name)?;
1701
1702            if let Some(table) = self
1703                .catalog_manager
1704                .table(
1705                    &table_name.catalog_name,
1706                    &table_name.schema_name,
1707                    &table_name.table_name,
1708                    Some(&query_context),
1709                )
1710                .await
1711                .context(CatalogSnafu)?
1712            {
1713                tables.push(table.table_info().table_id());
1714            } else if drop_if_exists {
1715                // DROP TABLE IF EXISTS meets table not found - ignored
1716                continue;
1717            } else {
1718                return TableNotFoundSnafu {
1719                    table_name: table_name.to_string(),
1720                }
1721                .fail();
1722            }
1723        }
1724
1725        for (table_name, table_id) in table_names.iter().zip(tables.into_iter()) {
1726            self.drop_table_procedure(table_name, table_id, drop_if_exists, query_context.clone())
1727                .await?;
1728
1729            // Invalidates local cache ASAP.
1730            self.cache_invalidator
1731                .invalidate(
1732                    &Context::default(),
1733                    &[
1734                        CacheIdent::TableId(table_id),
1735                        CacheIdent::TableName(table_name.clone()),
1736                    ],
1737                )
1738                .await
1739                .context(error::InvalidateTableCacheSnafu)?;
1740        }
1741        Ok(Output::new_with_affected_rows(0))
1742    }
1743
1744    #[cfg(feature = "enterprise")]
1745    #[tracing::instrument(skip_all)]
1746    pub async fn undrop_table(
1747        &self,
1748        table_name: TableName,
1749        query_context: QueryContextRef,
1750    ) -> Result<Output> {
1751        execute_undrop_table(
1752            &self.table_metadata_manager,
1753            &self.procedure_executor,
1754            &self.cache_invalidator,
1755            table_name,
1756            query_context,
1757        )
1758        .await
1759    }
1760
1761    #[tracing::instrument(skip_all)]
1762    pub async fn drop_database(
1763        &self,
1764        catalog: String,
1765        schema: String,
1766        drop_if_exists: bool,
1767        query_context: QueryContextRef,
1768    ) -> Result<Output> {
1769        ensure!(
1770            !is_readonly_schema(&schema),
1771            SchemaReadOnlySnafu { name: schema }
1772        );
1773
1774        if self
1775            .catalog_manager
1776            .schema_exists(&catalog, &schema, None)
1777            .await
1778            .context(CatalogSnafu)?
1779        {
1780            if schema == query_context.current_schema() {
1781                SchemaInUseSnafu { name: schema }.fail()
1782            } else {
1783                self.drop_database_procedure(catalog, schema, drop_if_exists, query_context)
1784                    .await?;
1785
1786                Ok(Output::new_with_affected_rows(0))
1787            }
1788        } else if drop_if_exists {
1789            // DROP TABLE IF EXISTS meets table not found - ignored
1790            Ok(Output::new_with_affected_rows(0))
1791        } else {
1792            SchemaNotFoundSnafu {
1793                schema_info: schema,
1794            }
1795            .fail()
1796        }
1797    }
1798
1799    pub async fn truncate_table(
1800        &self,
1801        table_name: TableName,
1802        time_ranges: Vec<(Timestamp, Timestamp)>,
1803        query_context: QueryContextRef,
1804    ) -> Result<Output> {
1805        self.truncate_table_with_options(
1806            table_name,
1807            time_ranges,
1808            DdlSubmitOptions::default(),
1809            query_context,
1810        )
1811        .await
1812    }
1813
1814    /// Truncates a table, optionally waiting for the submitted procedure to finish.
1815    #[tracing::instrument(name = "truncate_table", skip_all)]
1816    pub(crate) async fn truncate_table_with_options(
1817        &self,
1818        table_name: TableName,
1819        time_ranges: Vec<(Timestamp, Timestamp)>,
1820        ddl_options: DdlSubmitOptions,
1821        query_context: QueryContextRef,
1822    ) -> Result<Output> {
1823        ensure_table_writable(&table_name.schema_name, &table_name.table_name)?;
1824
1825        let table = self
1826            .catalog_manager
1827            .table(
1828                &table_name.catalog_name,
1829                &table_name.schema_name,
1830                &table_name.table_name,
1831                Some(&query_context),
1832            )
1833            .await
1834            .context(CatalogSnafu)?
1835            .with_context(|| TableNotFoundSnafu {
1836                table_name: table_name.to_string(),
1837            })?;
1838        let table_id = table.table_info().table_id();
1839        let response = self
1840            .truncate_table_procedure(
1841                &table_name,
1842                table_id,
1843                time_ranges,
1844                ddl_options,
1845                query_context.clone(),
1846            )
1847            .await?;
1848
1849        if !ddl_options.wait {
1850            let procedure_id = String::from_utf8_lossy(&response.key).into_owned();
1851            let output = build_procedure_id_output(&procedure_id)?;
1852            query_context.set_last_procedure_id(procedure_id);
1853            return Ok(output);
1854        }
1855
1856        Ok(Output::new_with_affected_rows(0))
1857    }
1858
1859    #[tracing::instrument(skip_all)]
1860    pub async fn alter_table(
1861        &self,
1862        alter_table: AlterTable,
1863        query_context: QueryContextRef,
1864    ) -> Result<Output> {
1865        if matches!(
1866            alter_table.alter_operation(),
1867            AlterTableOperation::Repartition { .. } | AlterTableOperation::Partition { .. }
1868        ) {
1869            let request = expr_helper::to_repartition_request(alter_table, &query_context)?;
1870            return self.repartition_table(request, &query_context).await;
1871        }
1872
1873        let expr = expr_helper::to_alter_table_expr(alter_table, &query_context)?;
1874        self.alter_table_inner(expr, query_context, TriggerReason::Manual)
1875            .await
1876    }
1877
1878    #[tracing::instrument(skip_all)]
1879    pub async fn repartition_table(
1880        &self,
1881        request: RepartitionRequest,
1882        query_context: &QueryContextRef,
1883    ) -> Result<Output> {
1884        // Check if the schema is read-only.
1885        ensure_table_definition_writable(&request.schema_name, &request.table_name)?;
1886
1887        let table_ref = TableReference::full(
1888            &request.catalog_name,
1889            &request.schema_name,
1890            &request.table_name,
1891        );
1892        // Get the table from the catalog.
1893        let table = self
1894            .catalog_manager
1895            .table(
1896                &request.catalog_name,
1897                &request.schema_name,
1898                &request.table_name,
1899                Some(query_context),
1900            )
1901            .await
1902            .context(CatalogSnafu)?
1903            .with_context(|| TableNotFoundSnafu {
1904                table_name: table_ref.to_string(),
1905            })?;
1906        let table_id = table.table_info().ident.table_id;
1907        // Get existing partition expressions from the table route.
1908        let (physical_table_id, physical_table_route) = self
1909            .table_metadata_manager
1910            .table_route_manager()
1911            .get_physical_table_route(table_id)
1912            .await
1913            .context(TableMetadataManagerSnafu)?;
1914
1915        ensure!(
1916            physical_table_id == table_id,
1917            NotSupportedSnafu {
1918                feat: "REPARTITION on logical tables"
1919            }
1920        );
1921
1922        let table_info = table.table_info();
1923        let existing_partition_columns = table_info.meta.partition_columns().collect::<Vec<_>>();
1924        let column_schemas = table_info.meta.schema.column_schemas();
1925        // `REPARTITION ... ON COLUMNS` uses overwrite semantics: the provided
1926        // columns are the full target partition columns, not an extension of the
1927        // current ones. Therefore source expressions are converted with the
1928        // existing partition columns, while target expressions and the final
1929        // partition rule are validated against this effective target column set.
1930        let target_partition_columns = match &request.source {
1931            RepartitionSource::Partitions {
1932                target_partition_columns,
1933                ..
1934            } => {
1935                ensure!(
1936                    !existing_partition_columns.is_empty(),
1937                    InvalidPartitionRuleSnafu {
1938                        reason: format!(
1939                            "table {} does not have partition columns, cannot repartition",
1940                            table_ref
1941                        )
1942                    }
1943                );
1944
1945                if let Some(target_partition_columns) = target_partition_columns {
1946                    ensure!(
1947                        !target_partition_columns.is_empty(),
1948                        InvalidPartitionRuleSnafu {
1949                            reason: "ON COLUMNS requires at least one partition column"
1950                        }
1951                    );
1952                    validate_and_collect_partition_columns(
1953                        target_partition_columns,
1954                        column_schemas,
1955                    )?
1956                } else {
1957                    existing_partition_columns.clone()
1958                }
1959            }
1960            RepartitionSource::Unpartitioned { partition_columns } => {
1961                ensure!(
1962                    !partition_columns.is_empty(),
1963                    InvalidPartitionRuleSnafu {
1964                        reason: "PARTITION ON COLUMNS requires at least one partition column"
1965                    }
1966                );
1967                ensure!(
1968                    existing_partition_columns.is_empty(),
1969                    InvalidPartitionRuleSnafu {
1970                        reason: format!("table {} already has partition columns", table_ref)
1971                    }
1972                );
1973                partition_columns
1974                    .iter()
1975                    .map(|column_name| {
1976                        column_schemas
1977                            .iter()
1978                            .find(|column| &column.name == column_name)
1979                            .with_context(|| ColumnNotFoundSnafu { msg: column_name })
1980                    })
1981                    .collect::<Result<Vec<_>>>()?
1982            }
1983        };
1984
1985        let from_column_name_and_type = column_name_and_type(&existing_partition_columns);
1986        let target_column_name_and_type = column_name_and_type(&target_partition_columns);
1987        let target_partition_column_names = target_partition_columns
1988            .iter()
1989            .map(|column| column.name.clone())
1990            .collect::<Vec<_>>();
1991        let timezone = query_context.timezone();
1992        // Convert SQL Exprs to PartitionExprs.
1993        let from_partition_exprs = match &request.source {
1994            RepartitionSource::Partitions { from_exprs, .. } => from_exprs
1995                .iter()
1996                .map(|expr| convert_one_expr(expr, &from_column_name_and_type, &timezone))
1997                .collect::<Result<Vec<_>>>()?,
1998            RepartitionSource::Unpartitioned { .. } => vec![],
1999        };
2000
2001        let mut into_partition_exprs = request
2002            .into_exprs
2003            .iter()
2004            .map(|expr| convert_one_expr(expr, &target_column_name_and_type, &timezone))
2005            .collect::<Result<Vec<_>>>()?;
2006
2007        // `MERGE PARTITION` (and some `REPARTITION`) generates a single `OR` expression from
2008        // multiple source partitions; try to simplify it for better readability and stability.
2009        if matches!(&request.source, RepartitionSource::Partitions { .. })
2010            && from_partition_exprs.len() > 1
2011            && into_partition_exprs.len() == 1
2012            && let Some(expr) = into_partition_exprs.pop()
2013        {
2014            into_partition_exprs.push(partition::simplify::simplify_merged_partition_expr(expr));
2015        }
2016
2017        // Parse existing partition expressions from region routes.
2018        let mut existing_partition_exprs =
2019            Vec::with_capacity(physical_table_route.region_routes.len());
2020        for route in &physical_table_route.region_routes {
2021            let expr_json = route.region.partition_expr();
2022            if !expr_json.is_empty() {
2023                match PartitionExpr::from_json_str(&expr_json) {
2024                    Ok(Some(expr)) => existing_partition_exprs.push(expr),
2025                    Ok(None) => {
2026                        // Empty
2027                    }
2028                    Err(e) => {
2029                        return Err(e).context(DeserializePartitionExprSnafu);
2030                    }
2031                }
2032            }
2033        }
2034
2035        // Validate that from_partition_exprs are a subset of existing partition exprs.
2036        // We compare PartitionExpr directly since it implements Eq.
2037        if matches!(&request.source, RepartitionSource::Partitions { .. }) {
2038            for from_expr in &from_partition_exprs {
2039                ensure!(
2040                    existing_partition_exprs.contains(from_expr),
2041                    InvalidPartitionRuleSnafu {
2042                        reason: format!(
2043                            "partition expression '{}' does not exist in table {}",
2044                            from_expr, table_ref
2045                        )
2046                    }
2047                );
2048            }
2049        }
2050
2051        // Build the new partition expressions:
2052        // new_exprs = existing_exprs - from_exprs + into_exprs
2053        let new_partition_exprs: Vec<PartitionExpr> = match &request.source {
2054            RepartitionSource::Partitions { .. } => existing_partition_exprs
2055                .into_iter()
2056                .filter(|expr| !from_partition_exprs.contains(expr))
2057                .chain(into_partition_exprs.clone().into_iter())
2058                .collect(),
2059            RepartitionSource::Unpartitioned { .. } => into_partition_exprs.clone(),
2060        };
2061        ensure_partition_expr_columns_in_target(
2062            &new_partition_exprs,
2063            &target_partition_column_names.iter().collect(),
2064        )?;
2065        let new_partition_exprs_len = new_partition_exprs.len();
2066        let from_partition_exprs_len = from_partition_exprs.len();
2067
2068        // Validate the new partition expressions using MultiDimPartitionRule and PartitionChecker.
2069        let _ = MultiDimPartitionRule::try_new(
2070            target_partition_column_names,
2071            vec![],
2072            new_partition_exprs,
2073            true,
2074        )
2075        .context(InvalidPartitionSnafu)?;
2076
2077        let ddl_options = parse_ddl_options(&request.options)?;
2078        let serialize_exprs = |exprs: Vec<PartitionExpr>| -> Result<Vec<String>> {
2079            let mut json_exprs = Vec::with_capacity(exprs.len());
2080            for expr in exprs {
2081                json_exprs.push(expr.as_json_str().context(SerializePartitionExprSnafu)?);
2082            }
2083            Ok(json_exprs)
2084        };
2085        let from_partition_exprs_json = serialize_exprs(from_partition_exprs)?;
2086        let into_partition_exprs_json = serialize_exprs(into_partition_exprs)?;
2087        let source = match &request.source {
2088            RepartitionSource::Partitions {
2089                target_partition_columns,
2090                ..
2091            } => Source::PartitionExprs(PartitionedSource {
2092                exprs: from_partition_exprs_json,
2093                target_partition_columns: target_partition_columns
2094                    .clone()
2095                    .map(|columns| TargetPartitionColumns { columns }),
2096            }),
2097            RepartitionSource::Unpartitioned { partition_columns } => {
2098                Source::Unpartitioned(UnpartitionedSource {
2099                    partition_columns: partition_columns.clone(),
2100                })
2101            }
2102        };
2103        let repartition = Repartition {
2104            into_partition_exprs: into_partition_exprs_json,
2105            source: Some(source),
2106            ..Default::default()
2107        };
2108        let executor_context = to_executor_context(query_context.clone(), TriggerReason::Manual);
2109        let mut req = SubmitDdlTaskRequest::new(DdlTask::new_alter_table(AlterTableExpr {
2110            catalog_name: request.catalog_name.clone(),
2111            schema_name: request.schema_name.clone(),
2112            table_name: request.table_name.clone(),
2113            kind: Some(Kind::Repartition(repartition)),
2114        }));
2115        req.wait = ddl_options.wait;
2116        req.timeout = ddl_options.timeout;
2117
2118        info!(
2119            "Submitting repartition task for table {} (table_id={}), from {} to {} partitions, timeout: {:?}, wait: {}",
2120            table_ref,
2121            table_id,
2122            from_partition_exprs_len,
2123            new_partition_exprs_len,
2124            ddl_options.timeout,
2125            ddl_options.wait
2126        );
2127
2128        let response = self
2129            .procedure_executor
2130            .submit_ddl_task(executor_context, req)
2131            .await
2132            .context(error::ExecuteDdlSnafu)?;
2133
2134        if !ddl_options.wait {
2135            let procedure_id = String::from_utf8_lossy(&response.key).into_owned();
2136            let output = build_procedure_id_output(&procedure_id)?;
2137            query_context.set_last_procedure_id(procedure_id);
2138            return Ok(output);
2139        }
2140
2141        // Only invalidate cache if wait is true.
2142        let invalidate_keys = vec![
2143            CacheIdent::TableId(table_id),
2144            CacheIdent::TableName(TableName::new(
2145                request.catalog_name,
2146                request.schema_name,
2147                request.table_name,
2148            )),
2149        ];
2150
2151        // Invalidates local cache ASAP.
2152        self.cache_invalidator
2153            .invalidate(&Context::default(), &invalidate_keys)
2154            .await
2155            .context(error::InvalidateTableCacheSnafu)?;
2156
2157        Ok(Output::new_with_affected_rows(0))
2158    }
2159
2160    #[tracing::instrument(skip_all)]
2161    pub async fn alter_table_inner(
2162        &self,
2163        expr: AlterTableExpr,
2164        query_context: QueryContextRef,
2165        trigger_reason: TriggerReason,
2166    ) -> Result<Output> {
2167        ensure_table_definition_writable(&expr.schema_name, &expr.table_name)?;
2168
2169        let catalog_name = if expr.catalog_name.is_empty() {
2170            DEFAULT_CATALOG_NAME.to_string()
2171        } else {
2172            expr.catalog_name.clone()
2173        };
2174
2175        let schema_name = if expr.schema_name.is_empty() {
2176            DEFAULT_SCHEMA_NAME.to_string()
2177        } else {
2178            expr.schema_name.clone()
2179        };
2180
2181        let table_name = expr.table_name.clone();
2182
2183        let table = self
2184            .catalog_manager
2185            .table(
2186                &catalog_name,
2187                &schema_name,
2188                &table_name,
2189                Some(&query_context),
2190            )
2191            .await
2192            .context(CatalogSnafu)?
2193            .with_context(|| TableNotFoundSnafu {
2194                table_name: format_full_table_name(&catalog_name, &schema_name, &table_name),
2195            })?;
2196
2197        let table_id = table.table_info().ident.table_id;
2198        let need_alter = verify_alter(table_id, table.table_info(), expr.clone())?;
2199        if !need_alter {
2200            return Ok(Output::new_with_affected_rows(0));
2201        }
2202        info!(
2203            "Table info before alter is {:?}, expr: {:?}",
2204            table.table_info(),
2205            expr
2206        );
2207
2208        let physical_table_id = self
2209            .table_metadata_manager
2210            .table_route_manager()
2211            .get_physical_table_id(table_id)
2212            .await
2213            .context(TableMetadataManagerSnafu)?;
2214
2215        let executor_context = to_executor_context(query_context, trigger_reason);
2216
2217        let (req, invalidate_keys) = if physical_table_id == table_id {
2218            // This is physical table
2219            let req = SubmitDdlTaskRequest::new(DdlTask::new_alter_table(expr));
2220
2221            let invalidate_keys = vec![
2222                CacheIdent::TableId(table_id),
2223                CacheIdent::TableName(TableName::new(catalog_name, schema_name, table_name)),
2224            ];
2225
2226            (req, invalidate_keys)
2227        } else {
2228            // This is logical table. Retention lives on the physical table;
2229            // reject it here with an error that says so, instead of the
2230            // procedure's generic "only add columns" error.
2231            if let Some(Kind::SetTableOptions(options)) = &expr.kind {
2232                ensure!(
2233                    !options
2234                        .table_options
2235                        .iter()
2236                        .any(|option| option.key == TTL_KEY && is_retention_ttl(&option.value)),
2237                    RetentionTtlOnLogicalTableSnafu
2238                );
2239            }
2240            // Annotation alters only rewrite the logical table's own metadata;
2241            // `AlterLogicalTablesProcedure` only handles column adds.
2242            let annotation_alter = match expr.kind.as_ref() {
2243                Some(kind) => common_grpc_expr::annotation_alter_family(kind)
2244                    .context(AlterExprToRequestSnafu)?
2245                    .is_some_and(|family| family.allows_logical_tables()),
2246                None => false,
2247            };
2248            let task = if annotation_alter {
2249                DdlTask::new_alter_table(expr)
2250            } else {
2251                DdlTask::new_alter_logical_tables(vec![expr])
2252            };
2253            let req = SubmitDdlTaskRequest::new(task);
2254
2255            let mut invalidate_keys = vec![
2256                CacheIdent::TableId(physical_table_id),
2257                CacheIdent::TableId(table_id),
2258                CacheIdent::TableName(TableName::new(catalog_name, schema_name, table_name)),
2259            ];
2260
2261            let physical_table = self
2262                .table_metadata_manager
2263                .table_info_manager()
2264                .get(physical_table_id)
2265                .await
2266                .context(TableMetadataManagerSnafu)?
2267                .map(|x| x.into_inner());
2268            if let Some(physical_table) = physical_table {
2269                let physical_table_name = TableName::new(
2270                    physical_table.table_info.catalog_name,
2271                    physical_table.table_info.schema_name,
2272                    physical_table.table_info.name,
2273                );
2274                invalidate_keys.push(CacheIdent::TableName(physical_table_name));
2275            }
2276
2277            (req, invalidate_keys)
2278        };
2279
2280        self.procedure_executor
2281            .submit_ddl_task(executor_context, req)
2282            .await
2283            .context(error::ExecuteDdlSnafu)?;
2284
2285        // Invalidates local cache ASAP.
2286        self.cache_invalidator
2287            .invalidate(&Context::default(), &invalidate_keys)
2288            .await
2289            .context(error::InvalidateTableCacheSnafu)?;
2290
2291        Ok(Output::new_with_affected_rows(0))
2292    }
2293
2294    #[cfg(feature = "enterprise")]
2295    #[tracing::instrument(skip_all)]
2296    pub async fn alter_trigger(
2297        &self,
2298        _alter_expr: AlterTrigger,
2299        _query_context: QueryContextRef,
2300    ) -> Result<Output> {
2301        crate::error::NotSupportedSnafu {
2302            feat: "alter trigger",
2303        }
2304        .fail()
2305    }
2306
2307    #[tracing::instrument(skip_all)]
2308    pub async fn alter_database(
2309        &self,
2310        alter_expr: AlterDatabase,
2311        query_context: QueryContextRef,
2312    ) -> Result<Output> {
2313        let alter_expr = expr_helper::to_alter_database_expr(alter_expr, &query_context)?;
2314        self.alter_database_inner(alter_expr, query_context).await
2315    }
2316
2317    #[tracing::instrument(skip_all)]
2318    pub async fn alter_database_inner(
2319        &self,
2320        alter_expr: AlterDatabaseExpr,
2321        query_context: QueryContextRef,
2322    ) -> Result<Output> {
2323        ensure!(
2324            !is_readonly_schema(&alter_expr.schema_name),
2325            SchemaReadOnlySnafu {
2326                name: query_context.current_schema().clone()
2327            }
2328        );
2329
2330        let exists = self
2331            .catalog_manager
2332            .schema_exists(&alter_expr.catalog_name, &alter_expr.schema_name, None)
2333            .await
2334            .context(CatalogSnafu)?;
2335        ensure!(
2336            exists,
2337            SchemaNotFoundSnafu {
2338                schema_info: alter_expr.schema_name,
2339            }
2340        );
2341
2342        let cache_ident = [CacheIdent::SchemaName(SchemaName {
2343            catalog_name: alter_expr.catalog_name.clone(),
2344            schema_name: alter_expr.schema_name.clone(),
2345        })];
2346
2347        self.alter_database_procedure(alter_expr, query_context)
2348            .await?;
2349
2350        // Invalidates local cache ASAP.
2351        self.cache_invalidator
2352            .invalidate(&Context::default(), &cache_ident)
2353            .await
2354            .context(error::InvalidateTableCacheSnafu)?;
2355
2356        Ok(Output::new_with_affected_rows(0))
2357    }
2358
2359    async fn create_table_procedure(
2360        &self,
2361        create_table: CreateTableExpr,
2362        partitions: Vec<PartitionExpr>,
2363        table_info: TableInfo,
2364        query_context: QueryContextRef,
2365        trigger_reason: TriggerReason,
2366    ) -> Result<SubmitDdlTaskResponse> {
2367        let partitions = partitions
2368            .into_iter()
2369            .map(|expr| expr.as_pb_partition().context(PartitionExprToPbSnafu))
2370            .collect::<Result<Vec<_>>>()?;
2371
2372        let executor_context = to_executor_context_with_origin_frontend(
2373            query_context,
2374            &self.origin_frontend_addr,
2375            trigger_reason,
2376        );
2377        let request = SubmitDdlTaskRequest::new(DdlTask::new_create_table(
2378            create_table,
2379            partitions,
2380            table_info,
2381        ));
2382
2383        self.procedure_executor
2384            .submit_ddl_task(executor_context, request)
2385            .await
2386            .context(error::ExecuteDdlSnafu)
2387    }
2388
2389    async fn create_logical_tables_procedure(
2390        &self,
2391        tables_data: Vec<(CreateTableExpr, TableInfo)>,
2392        query_context: QueryContextRef,
2393        trigger_reason: TriggerReason,
2394    ) -> Result<SubmitDdlTaskResponse> {
2395        let executor_context = to_executor_context_with_origin_frontend(
2396            query_context,
2397            &self.origin_frontend_addr,
2398            trigger_reason,
2399        );
2400        let request = SubmitDdlTaskRequest::new(DdlTask::new_create_logical_tables(tables_data));
2401
2402        self.procedure_executor
2403            .submit_ddl_task(executor_context, request)
2404            .await
2405            .context(error::ExecuteDdlSnafu)
2406    }
2407
2408    async fn alter_logical_tables_procedure(
2409        &self,
2410        physical_table_id: TableId,
2411        tables_data: Vec<(TableId, AlterTableExpr)>,
2412        query_context: QueryContextRef,
2413        trigger_reason: TriggerReason,
2414    ) -> Result<SubmitDdlTaskResponse> {
2415        let mut invalidate_keys = vec![CacheIdent::TableId(physical_table_id)];
2416        if let Some(physical) = self
2417            .table_metadata_manager
2418            .table_info_manager()
2419            .get(physical_table_id)
2420            .await
2421            .context(TableMetadataManagerSnafu)?
2422        {
2423            invalidate_keys.push(CacheIdent::TableName(physical.table_name()));
2424        }
2425        for (id, expr) in &tables_data {
2426            invalidate_keys.push(CacheIdent::TableId(*id));
2427            invalidate_keys.push(CacheIdent::TableName(TableName::new(
2428                &expr.catalog_name,
2429                &expr.schema_name,
2430                &expr.table_name,
2431            )));
2432        }
2433        let mut executor_context = to_executor_context(query_context, trigger_reason);
2434        let (table_ids, exprs): (Vec<_>, Vec<_>) = tables_data.into_iter().unzip();
2435        if let Some(context) = &mut executor_context.query_context {
2436            context.extensions.insert(
2437                ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY.to_string(),
2438                table_ids
2439                    .iter()
2440                    .map(ToString::to_string)
2441                    .collect::<Vec<_>>()
2442                    .join(","),
2443            );
2444        }
2445        let request = SubmitDdlTaskRequest::new(DdlTask::new_alter_logical_tables(exprs));
2446
2447        let response = self
2448            .procedure_executor
2449            .submit_ddl_task(executor_context, request)
2450            .await
2451            .context(error::ExecuteDdlSnafu)?;
2452        // Metasrv notifications are asynchronous; callers need the updated local schema now.
2453        self.cache_invalidator
2454            .invalidate(&Context::default(), &invalidate_keys)
2455            .await
2456            .context(error::InvalidateTableCacheSnafu)?;
2457        Ok(response)
2458    }
2459
2460    async fn drop_table_procedure(
2461        &self,
2462        table_name: &TableName,
2463        table_id: TableId,
2464        drop_if_exists: bool,
2465        query_context: QueryContextRef,
2466    ) -> Result<SubmitDdlTaskResponse> {
2467        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
2468        let request = SubmitDdlTaskRequest::new(DdlTask::new_drop_table(
2469            table_name.catalog_name.clone(),
2470            table_name.schema_name.clone(),
2471            table_name.table_name.clone(),
2472            table_id,
2473            drop_if_exists,
2474        ));
2475
2476        self.procedure_executor
2477            .submit_ddl_task(executor_context, request)
2478            .await
2479            .context(error::ExecuteDdlSnafu)
2480    }
2481
2482    async fn drop_database_procedure(
2483        &self,
2484        catalog: String,
2485        schema: String,
2486        drop_if_exists: bool,
2487        query_context: QueryContextRef,
2488    ) -> Result<SubmitDdlTaskResponse> {
2489        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
2490        let request =
2491            SubmitDdlTaskRequest::new(DdlTask::new_drop_database(catalog, schema, drop_if_exists));
2492
2493        self.procedure_executor
2494            .submit_ddl_task(executor_context, request)
2495            .await
2496            .context(error::ExecuteDdlSnafu)
2497    }
2498
2499    async fn alter_database_procedure(
2500        &self,
2501        alter_expr: AlterDatabaseExpr,
2502        query_context: QueryContextRef,
2503    ) -> Result<SubmitDdlTaskResponse> {
2504        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
2505        let request = SubmitDdlTaskRequest::new(DdlTask::new_alter_database(alter_expr));
2506
2507        self.procedure_executor
2508            .submit_ddl_task(executor_context, request)
2509            .await
2510            .context(error::ExecuteDdlSnafu)
2511    }
2512
2513    async fn truncate_table_procedure(
2514        &self,
2515        table_name: &TableName,
2516        table_id: TableId,
2517        time_ranges: Vec<(Timestamp, Timestamp)>,
2518        ddl_options: DdlSubmitOptions,
2519        query_context: QueryContextRef,
2520    ) -> Result<SubmitDdlTaskResponse> {
2521        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
2522        let mut request = SubmitDdlTaskRequest::new(DdlTask::new_truncate_table(
2523            table_name.catalog_name.clone(),
2524            table_name.schema_name.clone(),
2525            table_name.table_name.clone(),
2526            table_id,
2527            time_ranges,
2528        ));
2529        request.wait = ddl_options.wait;
2530        request.timeout = ddl_options.timeout;
2531
2532        self.procedure_executor
2533            .submit_ddl_task(executor_context, request)
2534            .await
2535            .context(error::ExecuteDdlSnafu)
2536    }
2537
2538    #[tracing::instrument(skip_all)]
2539    pub async fn create_database(
2540        &self,
2541        database: &str,
2542        create_if_not_exists: bool,
2543        options: HashMap<String, String>,
2544        query_context: QueryContextRef,
2545    ) -> Result<Output> {
2546        let catalog = query_context.current_catalog();
2547        ensure!(
2548            NAME_PATTERN_REG.is_match(catalog),
2549            error::UnexpectedSnafu {
2550                violated: format!("Invalid catalog name: {}", catalog)
2551            }
2552        );
2553
2554        ensure!(
2555            NAME_PATTERN_REG.is_match(database),
2556            error::UnexpectedSnafu {
2557                violated: format!("Invalid database name: {}", database)
2558            }
2559        );
2560
2561        #[cfg(feature = "enterprise")]
2562        let creator = match &self.create_database_handler {
2563            Some(handler) => handler.creator(&query_context).context(ExternalSnafu)?,
2564            None => None,
2565        };
2566        #[cfg(not(feature = "enterprise"))]
2567        let creator = None;
2568
2569        let output = if !self
2570            .catalog_manager
2571            .schema_exists(catalog, database, None)
2572            .await
2573            .context(CatalogSnafu)?
2574            && !self.catalog_manager.is_reserved_schema_name(database)
2575        {
2576            self.create_database_procedure(
2577                catalog.to_string(),
2578                database.to_string(),
2579                create_if_not_exists,
2580                options,
2581                query_context.clone(),
2582                creator,
2583            )
2584            .await?;
2585
2586            Output::new_with_affected_rows(1)
2587        } else if create_if_not_exists {
2588            Output::new_with_affected_rows(1)
2589        } else {
2590            return error::SchemaExistsSnafu { name: database }.fail();
2591        };
2592
2593        #[cfg(feature = "enterprise")]
2594        if let Some(handler) = &self.create_database_handler {
2595            handler
2596                .refresh_current_user(&query_context)
2597                .await
2598                .context(ExternalSnafu)?;
2599        }
2600
2601        Ok(output)
2602    }
2603
2604    async fn create_database_procedure(
2605        &self,
2606        catalog: String,
2607        database: String,
2608        create_if_not_exists: bool,
2609        options: HashMap<String, String>,
2610        query_context: QueryContextRef,
2611        creator: Option<CreatorGrantIntent>,
2612    ) -> Result<SubmitDdlTaskResponse> {
2613        let executor_context = to_executor_context(query_context, TriggerReason::Manual);
2614        let request = SubmitDdlTaskRequest::new(DdlTask::new_create_database(
2615            catalog,
2616            database,
2617            create_if_not_exists,
2618            options,
2619            creator,
2620        ));
2621
2622        self.procedure_executor
2623            .submit_ddl_task(executor_context, request)
2624            .await
2625            .context(error::ExecuteDdlSnafu)
2626    }
2627}
2628
2629/// Parse partition statement [Partitions] into [PartitionExpr] and partition columns.
2630pub fn parse_partitions(
2631    create_table: &CreateTableExpr,
2632    partitions: Option<Partitions>,
2633    query_ctx: &QueryContextRef,
2634) -> Result<(Vec<PartitionExpr>, Vec<String>)> {
2635    // If partitions are not defined by user, use the timestamp column (which has to be existed) as
2636    // the partition column, and create only one partition.
2637    let partition_columns = find_partition_columns(&partitions)?;
2638    let partition_exprs =
2639        find_partition_entries(create_table, &partitions, &partition_columns, query_ctx)?;
2640
2641    // Validates partition
2642    let exprs = partition_exprs.clone();
2643    MultiDimPartitionRule::try_new(partition_columns.clone(), vec![], exprs, true)
2644        .context(InvalidPartitionSnafu)?;
2645
2646    Ok((partition_exprs, partition_columns))
2647}
2648
2649fn parse_partitions_for_logical_validation(
2650    create_table: &CreateTableExpr,
2651    partitions: &Partitions,
2652    query_ctx: &QueryContextRef,
2653) -> Result<(Vec<String>, Vec<PartitionExpr>)> {
2654    let partition_columns = partitions
2655        .column_list
2656        .iter()
2657        .map(|ident| ident.value.clone())
2658        .collect::<Vec<_>>();
2659
2660    let column_name_and_type = partition_columns
2661        .iter()
2662        .map(|pc| {
2663            let column = create_table
2664                .column_defs
2665                .iter()
2666                .find(|c| &c.name == pc)
2667                .context(ColumnNotFoundSnafu { msg: pc.clone() })?;
2668            let column_name = &column.name;
2669            let data_type = ConcreteDataType::from(
2670                ColumnDataTypeWrapper::try_new(column.data_type, column.datatype_extension.clone())
2671                    .context(ColumnDataTypeSnafu)?,
2672            );
2673            Ok((column_name, data_type))
2674        })
2675        .collect::<Result<HashMap<_, _>>>()?;
2676
2677    let mut partition_exprs = Vec::with_capacity(partitions.exprs.len());
2678    for expr in &partitions.exprs {
2679        let partition_expr = convert_one_expr(expr, &column_name_and_type, &query_ctx.timezone())?;
2680        partition_exprs.push(partition_expr);
2681    }
2682
2683    MultiDimPartitionRule::try_new(
2684        partition_columns.clone(),
2685        vec![],
2686        partition_exprs.clone(),
2687        true,
2688    )
2689    .context(InvalidPartitionSnafu)?;
2690
2691    Ok((partition_columns, partition_exprs))
2692}
2693
2694/// Verifies an alter and returns whether it is necessary to perform the alter.
2695///
2696/// # Returns
2697///
2698/// Returns true if the alter need to be porformed; otherwise, it returns false.
2699pub fn verify_alter(
2700    table_id: TableId,
2701    table_info: Arc<TableInfo>,
2702    expr: AlterTableExpr,
2703) -> Result<bool> {
2704    let request: AlterTableRequest =
2705        common_grpc_expr::alter_expr_to_request(table_id, expr, Some(&table_info.meta))
2706            .context(AlterExprToRequestSnafu)?;
2707
2708    let AlterTableRequest {
2709        table_name,
2710        alter_kind,
2711        ..
2712    } = &request;
2713
2714    if let AlterKind::RenameTable { new_table_name } = alter_kind {
2715        ensure!(
2716            NAME_PATTERN_REG.is_match(new_table_name),
2717            error::UnexpectedSnafu {
2718                violated: format!("Invalid table name: {}", new_table_name)
2719            }
2720        );
2721        // Renaming INTO a computed graph table's name would let the overlay
2722        // shadow the renamed physical table, orphaning its data.
2723        ensure_table_definition_writable(&table_info.schema_name, new_table_name)?;
2724    } else if let AlterKind::AddColumns { columns } = alter_kind {
2725        // If all the columns are marked as add_if_not_exists and they already exist in the table,
2726        // there is no need to perform the alter.
2727        let column_names: HashSet<_> = table_info
2728            .meta
2729            .schema
2730            .column_schemas()
2731            .iter()
2732            .map(|schema| &schema.name)
2733            .collect();
2734        if columns.iter().all(|column| {
2735            column_names.contains(&column.column_schema.name) && column.add_if_not_exists
2736        }) {
2737            return Ok(false);
2738        }
2739    }
2740
2741    let new_meta = table_info
2742        .meta
2743        .builder_with_alter_kind(table_name, &request.alter_kind)
2744        .context(error::TableSnafu)?
2745        .build()
2746        .context(error::BuildTableMetaSnafu { table_name })?;
2747
2748    validate_json2_primary_keys(&new_meta.schema, &new_meta.primary_key_indices)?;
2749
2750    Ok(true)
2751}
2752
2753/// Returns whether `ttl` is a retention period, i.e. a valid TTL other than
2754/// `instant`. Invalid values return false so they fail normal option validation.
2755pub(crate) fn is_retention_ttl(ttl: &str) -> bool {
2756    TimeToLive::from_humantime_or_str(ttl).is_ok_and(|ttl| !ttl.is_instant())
2757}
2758
2759pub fn create_table_info(
2760    create_table: &CreateTableExpr,
2761    partition_columns: Vec<String>,
2762) -> Result<TableInfo> {
2763    let mut column_schemas = Vec::with_capacity(create_table.column_defs.len());
2764    let mut column_name_to_index_map = HashMap::new();
2765
2766    for (idx, column) in create_table.column_defs.iter().enumerate() {
2767        let schema =
2768            column_def::try_as_column_schema(column).context(error::InvalidColumnDefSnafu {
2769                column: &column.name,
2770            })?;
2771        let schema = schema.with_time_index(column.name == create_table.time_index);
2772
2773        column_schemas.push(schema);
2774        let _ = column_name_to_index_map.insert(column.name.clone(), idx);
2775    }
2776
2777    let next_column_id = column_schemas.len() as u32;
2778    let schema = Arc::new(Schema::try_new(column_schemas).context(ConvertSchemaSnafu)?);
2779
2780    let primary_key_indices = create_table
2781        .primary_keys
2782        .iter()
2783        .map(|name| {
2784            column_name_to_index_map
2785                .get(name)
2786                .cloned()
2787                .context(ColumnNotFoundSnafu { msg: name })
2788        })
2789        .collect::<Result<Vec<_>>>()?;
2790
2791    let partition_key_indices = partition_columns
2792        .into_iter()
2793        .map(|col_name| {
2794            column_name_to_index_map
2795                .get(&col_name)
2796                .cloned()
2797                .context(ColumnNotFoundSnafu { msg: col_name })
2798        })
2799        .collect::<Result<Vec<_>>>()?;
2800
2801    let mut table_options = TableOptions::try_from_iter(&create_table.table_options)
2802        .context(UnrecognizedTableOptionSnafu)?;
2803
2804    validate_json2_primary_keys(&schema, &primary_key_indices)?;
2805
2806    validate_and_normalize_annotations(&mut table_options, &schema, &partition_key_indices)?;
2807
2808    let meta = TableMeta {
2809        schema,
2810        primary_key_indices,
2811        value_indices: vec![],
2812        engine: create_table.engine.clone(),
2813        next_column_id,
2814        options: table_options,
2815        created_on: Utc::now(),
2816        updated_on: Utc::now(),
2817        partition_key_indices,
2818        column_ids: vec![],
2819    };
2820
2821    let desc = if create_table.desc.is_empty() {
2822        create_table.table_options.get(COMMENT_KEY).cloned()
2823    } else {
2824        Some(create_table.desc.clone())
2825    };
2826
2827    let table_info = TableInfo {
2828        ident: metadata::TableIdent {
2829            // The table id of distributed table is assigned by Meta, set "0" here as a placeholder.
2830            table_id: 0,
2831            version: 0,
2832        },
2833        name: create_table.table_name.clone(),
2834        desc,
2835        catalog_name: create_table.catalog_name.clone(),
2836        schema_name: create_table.schema_name.clone(),
2837        meta,
2838        table_type: TableType::Base,
2839    };
2840    Ok(table_info)
2841}
2842
2843fn validate_json2_primary_keys(schema: &Schema, primary_key_indices: &[usize]) -> Result<()> {
2844    for &index in primary_key_indices {
2845        let column = &schema.column_schemas()[index];
2846        ensure!(
2847            !column.data_type.is_json2(),
2848            InvalidSqlSnafu {
2849                err_msg: format!("JSON2 column `{}` cannot be a primary key", column.name),
2850            }
2851        );
2852    }
2853    Ok(())
2854}
2855
2856/// Rejects DDL against read-only schemas and computed entity-graph tables.
2857fn ensure_table_writable(schema: &str, table: &str) -> Result<()> {
2858    ensure!(
2859        !is_readonly_schema(schema),
2860        SchemaReadOnlySnafu {
2861            name: schema.to_string()
2862        }
2863    );
2864    ensure!(
2865        !is_readonly_table(schema, table),
2866        TableReadOnlySnafu {
2867            name: table.to_string()
2868        }
2869    );
2870    Ok(())
2871}
2872
2873/// [`ensure_table_writable`] plus the definition guard for system-defined
2874/// tables: user CREATE, ALTER and RENAME-into are rejected so the canonical
2875/// schema cannot be squatted or mutated. DROP and TRUNCATE stay allowed — the
2876/// next INSERT recreates the table canonically, which is also the recovery
2877/// path if the canonical definition changes across an upgrade.
2878fn ensure_table_definition_writable(schema: &str, table: &str) -> Result<()> {
2879    ensure_table_writable(schema, table)?;
2880    ensure!(
2881        !is_ddl_reserved_table(schema, table),
2882        TableDdlReservedSnafu {
2883            name: table.to_string()
2884        }
2885    );
2886    Ok(())
2887}
2888
2889/// CREATE-side annotation validation: one rule source in the table crate,
2890/// mapped onto this crate's existing error variants so client-visible codes
2891/// and messages stay put.
2892fn validate_and_normalize_annotations(
2893    options: &mut TableOptions,
2894    schema: &Schema,
2895    partition_key_indices: &[usize],
2896) -> Result<()> {
2897    use table::requests::AnnotationValidationError as CheckError;
2898    let handle_error = |e: CheckError| match e {
2899        CheckError::ColumnNotFound { column } => ColumnNotFoundSnafu { msg: column }.build(),
2900        e @ (CheckError::UnknownKey { .. }
2901        | CheckError::InvalidValue { .. }
2902        | CheckError::InvalidPartitionNumHint { .. }
2903        | CheckError::ColumnNotStringForm { .. }) => InvalidSqlSnafu {
2904            err_msg: e.to_string(),
2905        }
2906        .build(),
2907        e @ (CheckError::NotSingleColumn
2908        | CheckError::PartitionMetadataConflict
2909        | CheckError::TimeIndexConflict) => InvalidPartitionRuleSnafu {
2910            reason: e.to_string(),
2911        }
2912        .build(),
2913    };
2914    validate_and_normalize_annotation_options(options, schema, partition_key_indices)
2915        .map_err(handle_error)
2916}
2917
2918fn find_partition_columns(partitions: &Option<Partitions>) -> Result<Vec<String>> {
2919    let columns = if let Some(partitions) = partitions {
2920        partitions
2921            .column_list
2922            .iter()
2923            .map(|x| x.value.clone())
2924            .collect::<Vec<_>>()
2925    } else {
2926        vec![]
2927    };
2928    Ok(columns)
2929}
2930
2931/// Parse [Partitions] into a group of partition entries.
2932///
2933/// Returns a list of [PartitionExpr], each of which defines a partition.
2934fn find_partition_entries(
2935    create_table: &CreateTableExpr,
2936    partitions: &Option<Partitions>,
2937    partition_columns: &[String],
2938    query_ctx: &QueryContextRef,
2939) -> Result<Vec<PartitionExpr>> {
2940    let Some(partitions) = partitions else {
2941        return Ok(vec![]);
2942    };
2943
2944    // extract concrete data type of partition columns
2945    let column_name_and_type = partition_columns
2946        .iter()
2947        .map(|pc| {
2948            let column = create_table
2949                .column_defs
2950                .iter()
2951                .find(|c| &c.name == pc)
2952                // unwrap is safe here because we have checked that partition columns are defined
2953                .unwrap();
2954            let column_name = &column.name;
2955            let data_type = ConcreteDataType::from(
2956                ColumnDataTypeWrapper::try_new(column.data_type, column.datatype_extension.clone())
2957                    .context(ColumnDataTypeSnafu)?,
2958            );
2959            Ok((column_name, data_type))
2960        })
2961        .collect::<Result<HashMap<_, _>>>()?;
2962
2963    // Transform parser expr to partition expr
2964    let mut partition_exprs = Vec::with_capacity(partitions.exprs.len());
2965    for partition in &partitions.exprs {
2966        let partition_expr =
2967            convert_one_expr(partition, &column_name_and_type, &query_ctx.timezone())?;
2968        partition_exprs.push(partition_expr);
2969    }
2970
2971    Ok(partition_exprs)
2972}
2973
2974fn column_name_and_type<'a>(
2975    partition_columns: &'a [&'a ColumnSchema],
2976) -> HashMap<&'a String, ConcreteDataType> {
2977    partition_columns
2978        .iter()
2979        .map(|column| (&column.name, column.data_type.clone()))
2980        .collect()
2981}
2982
2983fn validate_and_collect_partition_columns<'a>(
2984    column_names: &[String],
2985    column_schemas: &'a [ColumnSchema],
2986) -> Result<Vec<&'a ColumnSchema>> {
2987    let mut seen = HashSet::with_capacity(column_names.len());
2988    column_names
2989        .iter()
2990        .map(|column_name| {
2991            ensure!(
2992                seen.insert(column_name),
2993                InvalidPartitionRuleSnafu {
2994                    reason: format!("duplicate partition column '{}'", column_name)
2995                }
2996            );
2997            column_schemas
2998                .iter()
2999                .find(|column| &column.name == column_name)
3000                .with_context(|| ColumnNotFoundSnafu { msg: column_name })
3001        })
3002        .collect()
3003}
3004
3005fn ensure_partition_expr_columns_in_target(
3006    partition_exprs: &[PartitionExpr],
3007    target_partition_columns: &HashSet<&String>,
3008) -> Result<()> {
3009    for expr in partition_exprs {
3010        ensure_partition_operand_columns_in_target(&expr.lhs, target_partition_columns)?;
3011        ensure_partition_operand_columns_in_target(&expr.rhs, target_partition_columns)?;
3012    }
3013
3014    Ok(())
3015}
3016
3017fn ensure_partition_operand_columns_in_target(
3018    operand: &Operand,
3019    target_partition_columns: &HashSet<&String>,
3020) -> Result<()> {
3021    match operand {
3022        Operand::Column(column) => ensure!(
3023            target_partition_columns.contains(column),
3024            InvalidPartitionRuleSnafu {
3025                reason: format!(
3026                    "partition expression references column '{}' that is not in target partition columns",
3027                    column
3028                )
3029            }
3030        ),
3031        Operand::Expr(expr) => {
3032            ensure_partition_operand_columns_in_target(&expr.lhs, target_partition_columns)?;
3033            ensure_partition_operand_columns_in_target(&expr.rhs, target_partition_columns)?;
3034        }
3035        Operand::IcebergHash(hash) => ensure!(
3036            target_partition_columns.contains(&hash.column().to_string()),
3037            InvalidPartitionRuleSnafu {
3038                reason: format!(
3039                    "partition expression references column '{}' that is not in target partition columns",
3040                    hash.column()
3041                )
3042            }
3043        ),
3044        Operand::Value(_) => {}
3045    }
3046
3047    Ok(())
3048}
3049
3050fn convert_one_expr(
3051    expr: &Expr,
3052    column_name_and_type: &HashMap<&String, ConcreteDataType>,
3053    timezone: &Timezone,
3054) -> Result<PartitionExpr> {
3055    let Expr::BinaryOp { left, op, right } = expr else {
3056        return InvalidPartitionRuleSnafu {
3057            reason: "partition rule must be a binary expression",
3058        }
3059        .fail();
3060    };
3061
3062    let op =
3063        RestrictedOp::try_from_parser(&op.clone()).with_context(|| InvalidPartitionRuleSnafu {
3064            reason: format!("unsupported operator in partition expr {op}"),
3065        })?;
3066
3067    // convert leaf node.
3068    let (lhs, op, rhs) = match (left.as_ref(), right.as_ref()) {
3069        // col, val
3070        (Expr::Identifier(ident), Expr::Value(value)) => {
3071            let (column_name, data_type) = convert_identifier(ident, column_name_and_type)?;
3072            let value = convert_value(&value.value, data_type, timezone, None)?;
3073            (Operand::Column(column_name), op, Operand::Value(value))
3074        }
3075        (Expr::Identifier(ident), Expr::UnaryOp { op: unary_op, expr })
3076            if let Expr::Value(v) = &**expr =>
3077        {
3078            let (column_name, data_type) = convert_identifier(ident, column_name_and_type)?;
3079            let value = convert_value(&v.value, data_type, timezone, Some(*unary_op))?;
3080            (Operand::Column(column_name), op, Operand::Value(value))
3081        }
3082        // val, col
3083        (Expr::Value(value), Expr::Identifier(ident)) => {
3084            let (column_name, data_type) = convert_identifier(ident, column_name_and_type)?;
3085            let value = convert_value(&value.value, data_type, timezone, None)?;
3086            (Operand::Value(value), op, Operand::Column(column_name))
3087        }
3088        (Expr::UnaryOp { op: unary_op, expr }, Expr::Identifier(ident))
3089            if let Expr::Value(v) = &**expr =>
3090        {
3091            let (column_name, data_type) = convert_identifier(ident, column_name_and_type)?;
3092            let value = convert_value(&v.value, data_type, timezone, Some(*unary_op))?;
3093            (Operand::Value(value), op, Operand::Column(column_name))
3094        }
3095        // func, val
3096        (Expr::Function(function), literal)
3097            if !matches!(op, RestrictedOp::And | RestrictedOp::Or) =>
3098        {
3099            let hash = convert_iceberg_hash(function, column_name_and_type)?;
3100            let value = convert_literal(literal, IcebergHash::output_type(), timezone)?;
3101            (Operand::IcebergHash(hash), op, Operand::Value(value))
3102        }
3103        // val, func
3104        (literal, Expr::Function(function))
3105            if !matches!(op, RestrictedOp::And | RestrictedOp::Or) =>
3106        {
3107            let hash = convert_iceberg_hash(function, column_name_and_type)?;
3108            let value = convert_literal(literal, IcebergHash::output_type(), timezone)?;
3109            (Operand::Value(value), op, Operand::IcebergHash(hash))
3110        }
3111        (Expr::BinaryOp { .. }, Expr::BinaryOp { .. }) => {
3112            // sub-expr must against another sub-expr
3113            let lhs = convert_one_expr(left, column_name_and_type, timezone)?;
3114            let rhs = convert_one_expr(right, column_name_and_type, timezone)?;
3115            (Operand::Expr(lhs), op, Operand::Expr(rhs))
3116        }
3117        _ => {
3118            return InvalidPartitionRuleSnafu {
3119                reason: format!("invalid partition expr {expr}"),
3120            }
3121            .fail();
3122        }
3123    };
3124
3125    Ok(PartitionExpr::new(lhs, op, rhs))
3126}
3127
3128/// Converts an `iceberg_hash` call, which takes exactly one partition column.
3129fn convert_iceberg_hash(
3130    function: &Function,
3131    column_name_and_type: &HashMap<&String, ConcreteDataType>,
3132) -> Result<IcebergHash> {
3133    let invalid = || {
3134        InvalidPartitionRuleSnafu {
3135            reason: format!("unsupported partition function call {function}"),
3136        }
3137        .build()
3138    };
3139    let FunctionArguments::List(args) = &function.args else {
3140        return Err(invalid());
3141    };
3142    let [FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Identifier(ident)))] =
3143        args.args.as_slice()
3144    else {
3145        return Err(invalid());
3146    };
3147    if function.filter.is_some()
3148        || function.over.is_some()
3149        || function.null_treatment.is_some()
3150        || !function.within_group.is_empty()
3151        || !matches!(function.parameters, FunctionArguments::None)
3152        || args.duplicate_treatment.is_some()
3153        || !args.clauses.is_empty()
3154    {
3155        return Err(invalid());
3156    }
3157    ensure!(
3158        function
3159            .name
3160            .to_string()
3161            .eq_ignore_ascii_case(IcebergHash::NAME),
3162        InvalidPartitionRuleSnafu {
3163            reason: format!("unsupported partition function {}", function.name),
3164        }
3165    );
3166    let (column_name, data_type) = convert_identifier(ident, column_name_and_type)?;
3167    ensure!(
3168        IcebergHash::accepts(&data_type),
3169        InvalidPartitionRuleSnafu {
3170            reason: format!(
3171                "partition function {} does not support column type {data_type}",
3172                IcebergHash::NAME
3173            ),
3174        }
3175    );
3176    Ok(IcebergHash::new(column_name))
3177}
3178
3179fn convert_literal(expr: &Expr, data_type: ConcreteDataType, timezone: &Timezone) -> Result<Value> {
3180    match expr {
3181        Expr::Value(value) => convert_value(&value.value, data_type, timezone, None),
3182        Expr::UnaryOp { op, expr } if let Expr::Value(value) = &**expr => {
3183            convert_value(&value.value, data_type, timezone, Some(*op))
3184        }
3185        _ => InvalidPartitionRuleSnafu {
3186            reason: format!("expect a literal in partition expr, got {expr}"),
3187        }
3188        .fail(),
3189    }
3190}
3191
3192fn convert_identifier(
3193    ident: &Ident,
3194    column_name_and_type: &HashMap<&String, ConcreteDataType>,
3195) -> Result<(String, ConcreteDataType)> {
3196    let column_name = ident.value.clone();
3197    let data_type = column_name_and_type
3198        .get(&column_name)
3199        .cloned()
3200        .with_context(|| ColumnNotFoundSnafu { msg: &column_name })?;
3201    Ok((column_name, data_type))
3202}
3203
3204fn convert_value(
3205    value: &ParserValue,
3206    data_type: ConcreteDataType,
3207    timezone: &Timezone,
3208    unary_op: Option<UnaryOperator>,
3209) -> Result<Value> {
3210    sql_value_to_value(
3211        &ColumnSchema::new("<NONAME>", data_type, true),
3212        value,
3213        Some(timezone),
3214        unary_op,
3215        false,
3216    )
3217    .context(error::SqlCommonSnafu)
3218}
3219
3220#[cfg(feature = "enterprise")]
3221async fn execute_undrop_table(
3222    table_metadata_manager: &TableMetadataManagerRef,
3223    procedure_executor: &ProcedureExecutorRef,
3224    cache_invalidator: &CacheInvalidatorRef,
3225    table_name: TableName,
3226    query_context: QueryContextRef,
3227) -> Result<Output> {
3228    // Undropping restores a table definition and could resurrect a
3229    // pre-canonical shape of a DDL-reserved table; rejected like CREATE.
3230    ensure_table_definition_writable(&table_name.schema_name, &table_name.table_name)?;
3231
3232    let dropped = table_metadata_manager
3233        .get_dropped_table(&table_name)
3234        .await
3235        .context(TableMetadataManagerSnafu)?
3236        .with_context(|| TableNotFoundSnafu {
3237            table_name: table_name.to_string(),
3238        })?;
3239
3240    let executor_context = to_executor_context(query_context, TriggerReason::Manual);
3241    let request = SubmitDdlTaskRequest::new(DdlTask::new_undrop_table(dropped.table_id));
3242    procedure_executor
3243        .submit_ddl_task(executor_context, request)
3244        .await
3245        .context(error::ExecuteDdlSnafu)?;
3246
3247    if let Err(err) = cache_invalidator
3248        .invalidate(
3249            &Context::default(),
3250            &[
3251                CacheIdent::TableId(dropped.table_id),
3252                CacheIdent::TableName(table_name),
3253            ],
3254        )
3255        .await
3256    {
3257        warn!(
3258            "Failed to invalidate cache after restoring table '{}' (id={}): {}",
3259            dropped.table_name, dropped.table_id, err
3260        );
3261    }
3262
3263    Ok(Output::new_with_affected_rows(0))
3264}
3265
3266#[cfg(test)]
3267mod test {
3268    #[cfg(feature = "enterprise")]
3269    use std::sync::{Arc, Mutex};
3270    use std::time::Duration;
3271
3272    #[cfg(feature = "enterprise")]
3273    use api::v1::meta::{ProcedureDetailResponse, ReconcileRequest, ReconcileResponse};
3274    use arrow::datatypes::{DataType as ArrowDataType, Field as ArrowField};
3275    #[cfg(feature = "enterprise")]
3276    use common_meta::cache_invalidator::{CacheInvalidator, CacheInvalidatorRef};
3277    #[cfg(feature = "enterprise")]
3278    use common_meta::instruction::CacheIdent;
3279    #[cfg(feature = "enterprise")]
3280    use common_meta::key::table_route::TableRouteValue;
3281    #[cfg(feature = "enterprise")]
3282    use common_meta::key::test_utils::new_test_table_info_with_name;
3283    #[cfg(feature = "enterprise")]
3284    use common_meta::key::{TableMetadataManager, TableMetadataManagerRef};
3285    #[cfg(feature = "enterprise")]
3286    use common_meta::kv_backend::memory::MemoryKvBackend;
3287    #[cfg(feature = "enterprise")]
3288    use common_meta::procedure_executor::{
3289        ExecutorContext, ProcedureExecutor, ProcedureExecutorRef,
3290    };
3291    #[cfg(feature = "enterprise")]
3292    use common_meta::rpc::ddl::{DdlTask, SubmitDdlTaskRequest, SubmitDdlTaskResponse};
3293    #[cfg(feature = "enterprise")]
3294    use common_meta::rpc::procedure::{
3295        MigrateRegionRequest, MigrateRegionResponse, ProcedureStateResponse,
3296    };
3297    use datafusion::functions_aggregate::expr_fn::count;
3298    use datafusion::logical_expr::builder::LogicalTableSource;
3299    use datafusion::logical_expr::{LogicalPlanBuilder, col};
3300    use session::context::QueryContext;
3301    use sql::dialect::GreptimeDbDialect;
3302    use sql::parser::{ParseOptions, ParserContext};
3303    use sql::statements::statement::Statement;
3304    use sqlparser::parser::Parser;
3305    use table::requests::REPARTITION_COLUMN_HINT_KEY;
3306
3307    use super::*;
3308    use crate::expr_helper;
3309
3310    #[cfg(feature = "enterprise")]
3311    #[derive(Default)]
3312    struct RecordingProcedureExecutor {
3313        requests: Mutex<Vec<SubmitDdlTaskRequest>>,
3314        contexts: Mutex<Vec<ExecutorContext>>,
3315        fail: bool,
3316    }
3317
3318    #[cfg(feature = "enterprise")]
3319    #[async_trait::async_trait]
3320    impl ProcedureExecutor for RecordingProcedureExecutor {
3321        async fn submit_ddl_task(
3322            &self,
3323            ctx: ExecutorContext,
3324            request: SubmitDdlTaskRequest,
3325        ) -> common_meta::error::Result<SubmitDdlTaskResponse> {
3326            self.contexts.lock().unwrap().push(ctx);
3327            self.requests.lock().unwrap().push(request);
3328            if self.fail {
3329                return common_meta::error::UnsupportedSnafu {
3330                    operation: "test submit failure",
3331                }
3332                .fail();
3333            }
3334            Ok(SubmitDdlTaskResponse::default())
3335        }
3336
3337        async fn migrate_region(
3338            &self,
3339            _: &ExecutorContext,
3340            _: MigrateRegionRequest,
3341        ) -> common_meta::error::Result<MigrateRegionResponse> {
3342            unimplemented!()
3343        }
3344        async fn reconcile(
3345            &self,
3346            _: &ExecutorContext,
3347            _: ReconcileRequest,
3348        ) -> common_meta::error::Result<ReconcileResponse> {
3349            unimplemented!()
3350        }
3351        async fn query_procedure_state(
3352            &self,
3353            _: &ExecutorContext,
3354            _: &str,
3355        ) -> common_meta::error::Result<ProcedureStateResponse> {
3356            unimplemented!()
3357        }
3358        async fn list_procedures(
3359            &self,
3360            _: &ExecutorContext,
3361        ) -> common_meta::error::Result<ProcedureDetailResponse> {
3362            unimplemented!()
3363        }
3364    }
3365
3366    #[cfg(feature = "enterprise")]
3367    #[derive(Default)]
3368    struct RecordingCacheInvalidator {
3369        invalidations: Mutex<Vec<Vec<CacheIdent>>>,
3370        fail: bool,
3371    }
3372
3373    #[cfg(feature = "enterprise")]
3374    #[async_trait::async_trait]
3375    impl CacheInvalidator for RecordingCacheInvalidator {
3376        async fn invalidate(
3377            &self,
3378            _: &Context,
3379            caches: &[CacheIdent],
3380        ) -> common_meta::error::Result<()> {
3381            self.invalidations.lock().unwrap().push(caches.to_vec());
3382            if self.fail {
3383                return common_meta::error::UnsupportedSnafu {
3384                    operation: "test cache failure",
3385                }
3386                .fail();
3387            }
3388            Ok(())
3389        }
3390
3391        fn invalidate_all(&self) -> common_meta::error::Result<()> {
3392            Ok(())
3393        }
3394    }
3395
3396    #[cfg(feature = "enterprise")]
3397    async fn dropped_table_manager(table_id: TableId, name: &TableName) -> TableMetadataManagerRef {
3398        let backend = Arc::new(MemoryKvBackend::default());
3399        let manager = Arc::new(TableMetadataManager::new(backend));
3400        let mut info = new_test_table_info_with_name(table_id, &name.table_name);
3401        info.catalog_name = name.catalog_name.clone();
3402        info.schema_name = name.schema_name.clone();
3403        let route = TableRouteValue::physical(vec![]);
3404        manager
3405            .create_table_metadata(info, route.clone(), HashMap::new())
3406            .await
3407            .unwrap();
3408        manager
3409            .delete_table_metadata(table_id, name, &route, &HashMap::new(), None)
3410            .await
3411            .unwrap();
3412        manager
3413    }
3414
3415    #[cfg(feature = "enterprise")]
3416    #[tokio::test]
3417    async fn test_undrop_table_execution_path() {
3418        let name = TableName::new("greptime", "public", "metrics");
3419        let manager = dropped_table_manager(42, &name).await;
3420        // A same-name live table must not redirect restoration to its ID.
3421        let mut live = new_test_table_info_with_name(99, "metrics");
3422        live.catalog_name = "greptime".to_string();
3423        live.schema_name = "public".to_string();
3424        manager
3425            .create_table_metadata(live, TableRouteValue::physical(vec![]), HashMap::new())
3426            .await
3427            .unwrap();
3428        let procedure = Arc::new(RecordingProcedureExecutor::default());
3429        let cache = Arc::new(RecordingCacheInvalidator::default());
3430
3431        execute_undrop_table(
3432            &manager,
3433            &(procedure.clone() as ProcedureExecutorRef),
3434            &(cache.clone() as CacheInvalidatorRef),
3435            name.clone(),
3436            QueryContext::arc(),
3437        )
3438        .await
3439        .unwrap();
3440
3441        let requests = procedure.requests.lock().unwrap();
3442        assert!(matches!(&requests[0].task, DdlTask::UndropTable(task) if task.table_id == 42));
3443        let contexts = procedure.contexts.lock().unwrap();
3444        assert_eq!(
3445            contexts[0].event_input.as_ref().map(|input| input.reason),
3446            Some(TriggerReason::Manual)
3447        );
3448        assert_eq!(
3449            cache.invalidations.lock().unwrap()[0],
3450            vec![CacheIdent::TableId(42), CacheIdent::TableName(name)]
3451        );
3452    }
3453
3454    #[cfg(feature = "enterprise")]
3455    #[tokio::test]
3456    async fn test_undrop_table_missing_tombstone_submits_nothing() {
3457        let manager = Arc::new(TableMetadataManager::new(Arc::new(
3458            MemoryKvBackend::default(),
3459        )));
3460        let procedure = Arc::new(RecordingProcedureExecutor::default());
3461        let cache = Arc::new(RecordingCacheInvalidator::default());
3462        let err = execute_undrop_table(
3463            &manager,
3464            &(procedure.clone() as ProcedureExecutorRef),
3465            &(cache as CacheInvalidatorRef),
3466            TableName::new("greptime", "public", "missing"),
3467            QueryContext::arc(),
3468        )
3469        .await
3470        .unwrap_err();
3471        assert!(matches!(err, crate::error::Error::TableNotFound { .. }));
3472        assert!(procedure.requests.lock().unwrap().is_empty());
3473    }
3474
3475    #[cfg(feature = "enterprise")]
3476    #[tokio::test]
3477    async fn test_undrop_table_submit_failure_does_not_invalidate() {
3478        let name = TableName::new("greptime", "public", "metrics");
3479        let manager = dropped_table_manager(42, &name).await;
3480        let procedure = Arc::new(RecordingProcedureExecutor {
3481            fail: true,
3482            ..Default::default()
3483        });
3484        let cache = Arc::new(RecordingCacheInvalidator::default());
3485        execute_undrop_table(
3486            &manager,
3487            &(procedure as ProcedureExecutorRef),
3488            &(cache.clone() as CacheInvalidatorRef),
3489            name,
3490            QueryContext::arc(),
3491        )
3492        .await
3493        .unwrap_err();
3494        assert!(cache.invalidations.lock().unwrap().is_empty());
3495    }
3496
3497    #[cfg(feature = "enterprise")]
3498    #[tokio::test]
3499    async fn test_undrop_table_cache_failure_returns_success_after_submit() {
3500        let name = TableName::new("greptime", "public", "metrics");
3501        let manager = dropped_table_manager(42, &name).await;
3502        let procedure = Arc::new(RecordingProcedureExecutor::default());
3503        let cache = Arc::new(RecordingCacheInvalidator {
3504            fail: true,
3505            ..Default::default()
3506        });
3507        execute_undrop_table(
3508            &manager,
3509            &(procedure.clone() as ProcedureExecutorRef),
3510            &(cache.clone() as CacheInvalidatorRef),
3511            name.clone(),
3512            QueryContext::arc(),
3513        )
3514        .await
3515        .unwrap();
3516        assert_eq!(procedure.requests.lock().unwrap().len(), 1);
3517        assert_eq!(
3518            cache.invalidations.lock().unwrap()[0],
3519            vec![CacheIdent::TableId(42), CacheIdent::TableName(name)]
3520        );
3521    }
3522
3523    #[test]
3524    fn test_parse_ddl_options() {
3525        let defaults = parse_ddl_options(&OptionMap::default()).unwrap();
3526        assert!(defaults.wait);
3527        assert_eq!(defaults.timeout, SubmitDdlTaskRequest::default_timeout());
3528
3529        let options = OptionMap::from([
3530            ("timeout".to_string(), "5m".to_string()),
3531            ("wait".to_string(), "false".to_string()),
3532        ]);
3533        let ddl_options = parse_ddl_options(&options).unwrap();
3534        assert!(!ddl_options.wait);
3535        assert_eq!(Duration::from_secs(300), ddl_options.timeout);
3536
3537        let options = OptionMap::from([("timeout".to_string(), "1500ms".to_string())]);
3538        assert_eq!(
3539            parse_ddl_options(&options).unwrap().timeout,
3540            Duration::from_millis(1500)
3541        );
3542        for (key, value) in [
3543            ("wait", "yes"),
3544            ("timeout", "not-a-duration"),
3545            ("timeout", "-1s"),
3546        ] {
3547            let options = OptionMap::from([(key.to_string(), value.to_string())]);
3548            assert!(matches!(
3549                parse_ddl_options(&options),
3550                Err(error::Error::InvalidSql { .. })
3551            ));
3552        }
3553    }
3554
3555    #[test]
3556    fn test_validate_and_normalize_annotations() {
3557        let schema = Schema::new(vec![
3558            ColumnSchema::new("service_name", ConcreteDataType::string_datatype(), true),
3559            ColumnSchema::new("host_id", ConcreteDataType::string_datatype(), true),
3560            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
3561            ColumnSchema::new("payload", ConcreteDataType::binary_datatype(), true),
3562        ]);
3563        let opts = |pairs: &[(&str, &str)]| TableOptions {
3564            extra_options: pairs
3565                .iter()
3566                .map(|(k, v)| (k.to_string(), v.to_string()))
3567                .collect(),
3568            ..Default::default()
3569        };
3570        let check = |pairs: &[(&str, &str)]| {
3571            let mut options = opts(pairs);
3572            validate_and_normalize_annotations(&mut options, &schema, &[]).map(|()| options)
3573        };
3574
3575        // Any existing column with a string form may be an id, tag or field.
3576        for pairs in [
3577            &[(
3578                "greptime.semantic.entity.process.id",
3579                "service_name,host_id",
3580            )][..],
3581            &[("greptime.semantic.entity.service.id", "value")][..],
3582        ] {
3583            assert!(check(pairs).is_ok());
3584        }
3585
3586        // Missing columns keep this crate's error variant and status code.
3587        let missing = check(&[("greptime.semantic.entity.service.id", "nope")]).unwrap_err();
3588        assert!(matches!(missing, error::Error::ColumnNotFound { .. }));
3589        assert_eq!(
3590            common_error::status_code::StatusCode::InvalidArguments,
3591            common_error::ext::ErrorExt::status_code(&missing)
3592        );
3593
3594        let binary_id = check(&[("greptime.semantic.entity.service.id", "payload")]).unwrap_err();
3595        assert!(matches!(binary_id, error::Error::InvalidSql { .. }));
3596
3597        // The SQL parser checks keys and value domains, but gRPC expressions
3598        // bypass it.
3599        let bad_value = check(&[("greptime.semantic.signal_type", "garbage")]).unwrap_err();
3600        assert!(matches!(bad_value, error::Error::InvalidSql { .. }));
3601
3602        let unknown_key = check(&[("greptime.semantic.nonsense", "x")]).unwrap_err();
3603        assert!(matches!(unknown_key, error::Error::InvalidSql { .. }));
3604    }
3605
3606    #[test]
3607    fn test_validate_and_normalize_flow_options_empty() {
3608        assert!(
3609            validate_and_normalize_flow_options(HashMap::new(), None)
3610                .unwrap()
3611                .is_empty()
3612        );
3613    }
3614
3615    #[test]
3616    fn test_validate_and_normalize_flow_options_valid() {
3617        let options = HashMap::from([
3618            (DEFER_ON_MISSING_SOURCE_KEY.to_string(), "TRUE".to_string()),
3619            (
3620                FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY.to_string(),
3621                "FALSE".to_string(),
3622            ),
3623        ]);
3624
3625        assert_eq!(
3626            validate_and_normalize_flow_options(options, None).unwrap(),
3627            HashMap::from([
3628                (DEFER_ON_MISSING_SOURCE_KEY.to_string(), "true".to_string(),),
3629                (
3630                    FLOW_EXPERIMENTAL_ENABLE_INCREMENTAL_READ_KEY.to_string(),
3631                    "false".to_string(),
3632                )
3633            ])
3634        );
3635    }
3636
3637    #[cfg(not(feature = "enterprise"))]
3638    #[test]
3639    fn test_validate_and_normalize_flow_options_unknown_option() {
3640        let err = validate_and_normalize_flow_options(
3641            HashMap::from([("foo".to_string(), "bar".to_string())]),
3642            None,
3643        )
3644        .unwrap_err();
3645
3646        assert!(
3647            err.to_string()
3648                .contains("unknown flow option 'foo', supported options:")
3649        );
3650    }
3651
3652    #[test]
3653    fn test_validate_and_normalize_flow_options_reserved_option() {
3654        let err = validate_and_normalize_flow_options(
3655            HashMap::from([(
3656                FlowType::FLOW_TYPE_KEY.to_string(),
3657                FlowType::BATCHING.to_string(),
3658            )]),
3659            None,
3660        )
3661        .unwrap_err();
3662
3663        assert!(
3664            err.to_string()
3665                .contains("flow option 'flow_type' is reserved for internal use")
3666        );
3667    }
3668
3669    #[test]
3670    fn test_validate_and_normalize_flow_options_invalid_bool() {
3671        let err = validate_and_normalize_flow_options(
3672            HashMap::from([(
3673                DEFER_ON_MISSING_SOURCE_KEY.to_string(),
3674                "not-a-bool".to_string(),
3675            )]),
3676            None,
3677        )
3678        .unwrap_err();
3679
3680        assert!(
3681            err.to_string()
3682                .contains("invalid flow option 'defer_on_missing_source': 'not-a-bool'")
3683        );
3684    }
3685
3686    #[test]
3687    fn test_parser_flow_option_access_key_id() {
3688        let sql = r"
3689CREATE FLOW task_6
3690SINK TO schema_1.table_1
3691WITH (access_key_id = [true])
3692AS
3693SELECT max(c1), min(c2) FROM schema_2.table_2;";
3694        let stmt =
3695            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
3696                .unwrap()
3697                .pop()
3698                .unwrap();
3699
3700        let Statement::CreateFlow(create_flow) = stmt else {
3701            unreachable!()
3702        };
3703        let expr =
3704            expr_helper::to_create_flow_task_expr(create_flow, &QueryContext::arc()).unwrap();
3705
3706        #[cfg(not(feature = "enterprise"))]
3707        {
3708            let err = validate_and_normalize_flow_options(expr.flow_options, None).unwrap_err();
3709            assert!(
3710                err.to_string()
3711                    .contains("unknown flow option 'access_key_id'")
3712            );
3713        }
3714        #[cfg(feature = "enterprise")]
3715        assert_eq!(
3716            validate_and_normalize_flow_options(expr.flow_options, None).unwrap(),
3717            HashMap::from([("access_key_id".to_string(), "['true']".to_string())])
3718        );
3719    }
3720
3721    fn stateless_test_scan(name: &str) -> LogicalPlan {
3722        let schema = arrow::datatypes::Schema::new(vec![ArrowField::new(
3723            "value",
3724            ArrowDataType::Int32,
3725            true,
3726        )]);
3727        LogicalPlanBuilder::scan(
3728            name,
3729            Arc::new(LogicalTableSource::new(Arc::new(schema))),
3730            None,
3731        )
3732        .unwrap()
3733        .build()
3734        .unwrap()
3735    }
3736
3737    #[test]
3738    fn test_is_stateless_flow_plan_accepts_scan_projection_and_filter() {
3739        let scan = stateless_test_scan("source");
3740        assert!(is_stateless_flow_plan(&scan));
3741
3742        let projection = LogicalPlanBuilder::from(scan.clone())
3743            .project(vec![col("value")])
3744            .unwrap()
3745            .build()
3746            .unwrap();
3747        assert!(is_stateless_flow_plan(&projection));
3748
3749        let filter = LogicalPlanBuilder::from(projection)
3750            .filter(col("value").gt(datafusion_expr::lit(0)))
3751            .unwrap()
3752            .build()
3753            .unwrap();
3754        assert!(is_stateless_flow_plan(&filter));
3755    }
3756
3757    #[test]
3758    fn test_is_stateless_flow_plan_rejects_aggregate_and_multiple_scans() {
3759        let scan = stateless_test_scan("source");
3760        let aggregate = LogicalPlanBuilder::from(scan.clone())
3761            .aggregate(
3762                Vec::<datafusion_expr::Expr>::new(),
3763                vec![count(col("value"))],
3764            )
3765            .unwrap()
3766            .build()
3767            .unwrap();
3768        assert!(!is_stateless_flow_plan(&aggregate));
3769
3770        let distinct = LogicalPlanBuilder::from(scan.clone())
3771            .distinct()
3772            .unwrap()
3773            .build()
3774            .unwrap();
3775        assert!(is_stateless_flow_plan(&distinct));
3776
3777        let distinct_on_aggregate = LogicalPlanBuilder::from(aggregate)
3778            .distinct()
3779            .unwrap()
3780            .build()
3781            .unwrap();
3782        assert!(!is_stateless_flow_plan(&distinct_on_aggregate));
3783
3784        let multiple_scans = LogicalPlanBuilder::from(stateless_test_scan("left"))
3785            .cross_join(stateless_test_scan("right"))
3786            .unwrap()
3787            .build()
3788            .unwrap();
3789        assert!(!is_stateless_flow_plan(&multiple_scans));
3790    }
3791
3792    // --- Schedule option tests ---
3793
3794    #[test]
3795    fn test_eval_interval_rejected_non_positive() {
3796        // Zero eval_interval should be rejected.
3797        let err = validate_and_normalize_flow_options(HashMap::new(), Some(0)).unwrap_err();
3798        assert!(err.to_string().contains("EVAL INTERVAL must be positive"));
3799
3800        // Negative eval_interval should be rejected.
3801        let err = validate_and_normalize_flow_options(HashMap::new(), Some(-5)).unwrap_err();
3802        assert!(err.to_string().contains("EVAL INTERVAL must be positive"));
3803
3804        // Positive eval_interval should be accepted.
3805        let result = validate_and_normalize_flow_options(HashMap::new(), Some(300));
3806        assert!(result.is_ok());
3807    }
3808
3809    #[test]
3810    fn test_internal_schedule_key_rejected() {
3811        let err = validate_and_normalize_flow_options(
3812            HashMap::from([(INTERNAL_EVAL_SCHEDULE_KEY.to_string(), "value".to_string())]),
3813            Some(300),
3814        )
3815        .unwrap_err();
3816        assert!(err.to_string().contains("reserved for internal use"));
3817    }
3818
3819    #[cfg(not(feature = "enterprise"))]
3820    #[test]
3821    fn test_schedule_keys_rejected_as_unknown_options() {
3822        for key in [
3823            "eval_interval_anchor",
3824            "eval_interval_start",
3825            "eval_interval_missed_tick_policy",
3826            "eval_interval_catchup_max_runs",
3827            "eval_interval_catchup_max_lag",
3828        ] {
3829            let err = validate_and_normalize_flow_options(
3830                HashMap::from([(key.to_string(), "value".to_string())]),
3831                Some(300),
3832            )
3833            .unwrap_err();
3834            assert!(
3835                err.to_string()
3836                    .contains(&format!("unknown flow option '{key}'"))
3837            );
3838        }
3839    }
3840
3841    #[cfg(feature = "enterprise")]
3842    #[test]
3843    fn test_schedule_keys_preserved() {
3844        let options = HashMap::from([
3845            ("eval_interval_anchor".to_string(), "anchor".to_string()),
3846            ("eval_interval_start".to_string(), "start".to_string()),
3847            (
3848                "eval_interval_missed_tick_policy".to_string(),
3849                "missed".to_string(),
3850            ),
3851            (
3852                "eval_interval_catchup_max_runs".to_string(),
3853                "runs".to_string(),
3854            ),
3855            (
3856                "eval_interval_catchup_max_lag".to_string(),
3857                "lag".to_string(),
3858            ),
3859        ]);
3860        assert_eq!(
3861            validate_and_normalize_flow_options(options.clone(), Some(300)).unwrap(),
3862            options
3863        );
3864    }
3865
3866    #[test]
3867    fn test_internal_transport_keys_rejected_as_reserved() {
3868        for key in [
3869            "__greptime_internal_eval_schedule",
3870            "__greptime_internal_eval_offset_secs",
3871        ] {
3872            let err = validate_and_normalize_flow_options(
3873                HashMap::from([(key.to_string(), "120".to_string())]),
3874                Some(300),
3875            )
3876            .unwrap_err();
3877
3878            assert!(
3879                err.to_string()
3880                    .contains(&format!("flow option '{key}' is reserved for internal use")),
3881                "unexpected error for {key}: {err}"
3882            );
3883        }
3884    }
3885
3886    #[test]
3887    fn test_determine_flow_type_for_source_state_missing_sources_require_opt_in() {
3888        let err =
3889            determine_flow_type_for_source_state("my_flow", &HashMap::new(), true, false, false)
3890                .unwrap_err();
3891
3892        assert!(err.to_string().contains(
3893            "missing source tables for flow 'my_flow'; use WITH (defer_on_missing_source = true) to create a pending flow"
3894        ));
3895    }
3896
3897    #[test]
3898    fn test_determine_flow_type_for_source_state_missing_sources_prefer_batching() {
3899        let flow_options =
3900            HashMap::from([(DEFER_ON_MISSING_SOURCE_KEY.to_string(), "true".to_string())]);
3901
3902        assert_eq!(
3903            determine_flow_type_for_source_state("my_flow", &flow_options, true, true, false)
3904                .unwrap(),
3905            Some(FlowType::Batching)
3906        );
3907        let err = determine_flow_type_for_source_state("my_flow", &flow_options, true, true, true)
3908            .unwrap_err();
3909        assert!(err.to_string().contains(
3910            "flow 'my_flow' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode"
3911        ));
3912    }
3913
3914    #[test]
3915    fn test_determine_flow_type_for_source_state_existing_sources_require_plan() {
3916        assert_eq!(
3917            determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, true, false)
3918                .unwrap(),
3919            None
3920        );
3921    }
3922
3923    #[test]
3924    fn test_determine_flow_type_for_source_state_instant_ttl_with_eval_interval_is_rejected() {
3925        // A flow with `EVAL INTERVAL` is forced onto the batching scheduler,
3926        // which cannot read instant-TTL source tables: reject instead of
3927        // silently falling back to streaming (where the schedule/offset would
3928        // be ignored).
3929        let err =
3930            determine_flow_type_for_source_state("my_flow", &HashMap::new(), false, true, true)
3931                .unwrap_err();
3932        assert!(
3933            err.to_string().contains(
3934                "flow 'my_flow' with EVAL INTERVAL requires the batching scheduler, but source tables with ttl=instant are not supported under batching mode"
3935            ),
3936            "unexpected error: {err}"
3937        );
3938    }
3939
3940    #[test]
3941    fn test_name_is_match() {
3942        assert!(!NAME_PATTERN_REG.is_match("/adaf"));
3943        assert!(!NAME_PATTERN_REG.is_match("🈲"));
3944        assert!(NAME_PATTERN_REG.is_match("hello"));
3945        assert!(NAME_PATTERN_REG.is_match("test@"));
3946        assert!(!NAME_PATTERN_REG.is_match("@test"));
3947        assert!(NAME_PATTERN_REG.is_match("test#"));
3948        assert!(!NAME_PATTERN_REG.is_match("#test"));
3949        assert!(!NAME_PATTERN_REG.is_match("@"));
3950        assert!(!NAME_PATTERN_REG.is_match("#"));
3951    }
3952
3953    #[test]
3954    fn test_convert_iceberg_hash() {
3955        let names = ["host", "count", "device", "measure", "host-name"].map(String::from);
3956        let column_name_and_type = HashMap::from([
3957            (&names[0], ConcreteDataType::string_datatype()),
3958            (&names[1], ConcreteDataType::int16_datatype()),
3959            (&names[2], ConcreteDataType::uint64_datatype()),
3960            (&names[3], ConcreteDataType::float64_datatype()),
3961            (&names[4], ConcreteDataType::string_datatype()),
3962        ]);
3963        let timezone = Timezone::from_tz_string("UTC").unwrap();
3964        let dialect = GreptimeDbDialect {};
3965        let parse = |sql: &str| {
3966            Parser::new(&dialect)
3967                .try_with_sql(sql)
3968                .unwrap()
3969                .parse_expr()
3970                .unwrap()
3971        };
3972
3973        for sql in [
3974            "iceberg_hash(host) < 0",
3975            "ICEBERG_HASH(device) >= -1073741824",
3976            "0 > iceberg_hash(count)",
3977            "iceberg_hash(host) < 100 AND host < 'm'",
3978            r#"iceberg_hash("host-name") < 0 AND "host-name" < 'm'"#,
3979        ] {
3980            let expr = convert_one_expr(&parse(sql), &column_name_and_type, &timezone).unwrap();
3981            // SHOW CREATE TABLE prints the rule back as SQL, quoting identifiers.
3982            let mut partitions = Partitions {
3983                column_list: vec![],
3984                exprs: vec![expr.to_parser_expr()],
3985            };
3986            partitions.set_quote('"');
3987            let restored = parse(&partitions.exprs[0].to_string());
3988            assert_eq!(
3989                convert_one_expr(&restored, &column_name_and_type, &timezone).unwrap(),
3990                expr,
3991                "{sql}"
3992            );
3993        }
3994
3995        for sql in [
3996            "iceberg_hash(measure) < 0",
3997            "iceberg_hash(host, count) < 0",
3998            "iceberg_hash('a') < 0",
3999            "iceberg_hash(missing) < 0",
4000            "iceberg_hash(DISTINCT host) < 0",
4001            "md5(host) < 0",
4002            "iceberg_hash(host) < host",
4003            "iceberg_hash(host) < 'abc'",
4004            "iceberg_hash(host) < 2147483648",
4005        ] {
4006            assert!(
4007                convert_one_expr(&parse(sql), &column_name_and_type, &timezone).is_err(),
4008                "{sql}"
4009            );
4010        }
4011    }
4012
4013    #[test]
4014    fn test_partition_expr_equivalence_with_swapped_operands() {
4015        let column_name = "device_id".to_string();
4016        let column_name_and_type =
4017            HashMap::from([(&column_name, ConcreteDataType::int32_datatype())]);
4018        let timezone = Timezone::from_tz_string("UTC").unwrap();
4019        let dialect = GreptimeDbDialect {};
4020
4021        let mut parser = Parser::new(&dialect)
4022            .try_with_sql("device_id < 100")
4023            .unwrap();
4024        let expr_left = parser.parse_expr().unwrap();
4025
4026        let mut parser = Parser::new(&dialect)
4027            .try_with_sql("100 > device_id")
4028            .unwrap();
4029        let expr_right = parser.parse_expr().unwrap();
4030
4031        let partition_left =
4032            convert_one_expr(&expr_left, &column_name_and_type, &timezone).unwrap();
4033        let partition_right =
4034            convert_one_expr(&expr_right, &column_name_and_type, &timezone).unwrap();
4035
4036        assert_eq!(partition_left, partition_right);
4037        assert!([partition_left.clone()].contains(&partition_right));
4038
4039        let mut physical_partition_exprs = vec![partition_left];
4040        let mut logical_partition_exprs = vec![partition_right];
4041        physical_partition_exprs.sort_unstable();
4042        logical_partition_exprs.sort_unstable();
4043        assert_eq!(physical_partition_exprs, logical_partition_exprs);
4044    }
4045
4046    #[test]
4047    fn test_repartition_target_partition_columns_are_overwrite_context() {
4048        let device_id = ColumnSchema::new("device_id", ConcreteDataType::int32_datatype(), true);
4049        let area = ColumnSchema::new("area", ConcreteDataType::string_datatype(), true);
4050        let existing_partition_columns = vec![&device_id];
4051        let target_partition_columns = vec![&device_id, &area];
4052        let existing_column_name_and_type = column_name_and_type(&existing_partition_columns);
4053        let target_column_name_and_type = column_name_and_type(&target_partition_columns);
4054        let timezone = Timezone::from_tz_string("UTC").unwrap();
4055        let dialect = GreptimeDbDialect {};
4056
4057        let mut parser = Parser::new(&dialect)
4058            .try_with_sql("device_id < 100 AND area < 'South'")
4059            .unwrap();
4060        let expr = parser.parse_expr().unwrap();
4061
4062        let err = convert_one_expr(&expr, &existing_column_name_and_type, &timezone).unwrap_err();
4063        assert!(err.to_string().contains("area"));
4064
4065        let partition_expr = convert_one_expr(&expr, &target_column_name_and_type, &timezone)
4066            .expect("target columns should overwrite the conversion context");
4067        let partition_expr = partition_expr.to_string();
4068        assert!(partition_expr.contains("device_id"));
4069        assert!(partition_expr.contains("area"));
4070        assert!(partition_expr.contains("South"));
4071    }
4072
4073    #[test]
4074    fn test_repartition_rejects_remaining_expr_outside_target_columns() {
4075        let device_id = "device_id".to_string();
4076        let area = "area".to_string();
4077        let timezone = Timezone::from_tz_string("UTC").unwrap();
4078        let column_name_and_type = HashMap::from([
4079            (&device_id, ConcreteDataType::int32_datatype()),
4080            (&area, ConcreteDataType::string_datatype()),
4081        ]);
4082        let dialect = GreptimeDbDialect {};
4083        let target_partition_columns = HashSet::from([&area]);
4084        for sql in ["device_id >= 100", "iceberg_hash(device_id) >= 0"] {
4085            let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
4086            let remaining_old_expr = convert_one_expr(
4087                &parser.parse_expr().unwrap(),
4088                &column_name_and_type,
4089                &timezone,
4090            )
4091            .unwrap();
4092
4093            let err = ensure_partition_expr_columns_in_target(
4094                &[remaining_old_expr],
4095                &target_partition_columns,
4096            )
4097            .unwrap_err();
4098
4099            assert!(err.to_string().contains("device_id"), "{sql}");
4100            assert!(
4101                err.to_string().contains("target partition columns"),
4102                "{sql}"
4103            );
4104        }
4105    }
4106
4107    #[test]
4108    fn test_repartition_rejects_duplicate_target_partition_columns() {
4109        let device_id = ColumnSchema::new("device_id", ConcreteDataType::int32_datatype(), true);
4110        let column_schemas = vec![device_id];
4111        let target_partition_columns = vec!["device_id".to_string(), "device_id".to_string()];
4112
4113        let err =
4114            validate_and_collect_partition_columns(&target_partition_columns, &column_schemas)
4115                .unwrap_err();
4116
4117        assert!(err.to_string().contains("duplicate partition column"));
4118        assert!(err.to_string().contains("device_id"));
4119    }
4120
4121    fn create_expr_from_sql(sql: &str) -> CreateTableExpr {
4122        let result =
4123            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
4124                .unwrap();
4125
4126        match &result[0] {
4127            Statement::CreateTable(create) => {
4128                expr_helper::create_to_expr(create, &QueryContext::arc()).unwrap()
4129            }
4130            _ => unreachable!(),
4131        }
4132    }
4133
4134    #[test]
4135    fn test_create_table_with_repartition_partition_num_hint() {
4136        let key = table::requests::REPARTITION_PARTITION_NUM_HINT_KEY;
4137        for (value, expected) in [
4138            (" 8 ", Some("8")),
4139            ("0", None),
4140            ("-1", None),
4141            ("4294967296", None),
4142        ] {
4143            let expr = create_expr_from_sql(&format!(
4144                "CREATE TABLE metrics (host STRING, ts TIMESTAMP TIME INDEX, PRIMARY KEY(host)) WITH ('{key}' = '{value}')"
4145            ));
4146            let result = create_table_info(&expr, vec![]);
4147            if let Some(expected) = expected {
4148                let info = result.unwrap();
4149                assert_eq!(
4150                    info.meta.options.extra_options.get(key).map(String::as_str),
4151                    Some(expected)
4152                );
4153            } else {
4154                assert!(
4155                    result
4156                        .unwrap_err()
4157                        .to_string()
4158                        .contains("expects a positive integer")
4159                );
4160            }
4161        }
4162    }
4163
4164    #[test]
4165    fn test_create_table_with_repartition_column_hint() {
4166        let expr = create_expr_from_sql(
4167            r"
4168CREATE TABLE metrics (
4169  host STRING,
4170  ts TIMESTAMP TIME INDEX,
4171  cpu DOUBLE,
4172  PRIMARY KEY(host)
4173)
4174WITH ('repartition.column.hint' = ' host ')",
4175        );
4176
4177        let table_info = create_table_info(&expr, vec![]).unwrap();
4178        assert_eq!(
4179            table_info
4180                .meta
4181                .options
4182                .extra_options
4183                .get(REPARTITION_COLUMN_HINT_KEY),
4184            Some(&"host".to_string())
4185        );
4186    }
4187
4188    #[test]
4189    fn test_create_table_info_rejects_non_timestamp_time_index() {
4190        let expr = CreateTableExpr {
4191            catalog_name: "greptime".to_string(),
4192            schema_name: "public".to_string(),
4193            table_name: "demo".to_string(),
4194            desc: String::new(),
4195            column_defs: vec![api::v1::ColumnDef {
4196                name: "host".to_string(),
4197                data_type: api::v1::ColumnDataType::String as i32,
4198                is_nullable: true,
4199                default_constraint: vec![],
4200                semantic_type: 0,
4201                comment: String::new(),
4202                datatype_extension: None,
4203                options: None,
4204            }],
4205            time_index: "host".to_string(),
4206            primary_keys: vec![],
4207            create_if_not_exists: false,
4208            table_options: HashMap::new(),
4209            table_id: None,
4210            engine: "mito".to_string(),
4211        };
4212
4213        let err = create_table_info(&expr, vec![]).unwrap_err();
4214        assert_eq!(
4215            common_error::ext::ErrorExt::status_code(&err),
4216            common_error::status_code::StatusCode::InvalidArguments
4217        );
4218    }
4219
4220    #[test]
4221    fn test_verify_alter_guards_entity_column_types() {
4222        let expr = create_expr_from_sql(
4223            "CREATE TABLE t (svc STRING, ts TIMESTAMP TIME INDEX) \
4224             WITH ('greptime.semantic.entity.service.id'='svc');",
4225        );
4226        let table_info = Arc::new(create_table_info(&expr, vec![]).unwrap());
4227        let alter = |kind| AlterTableExpr {
4228            catalog_name: "greptime".to_string(),
4229            schema_name: "public".to_string(),
4230            table_name: "t".to_string(),
4231            kind: Some(kind),
4232        };
4233
4234        let modify = alter(Kind::ModifyColumnTypes(api::v1::ModifyColumnTypes {
4235            modify_column_types: vec![api::v1::ModifyColumnType {
4236                column_name: "svc".to_string(),
4237                target_type: api::v1::ColumnDataType::Binary as i32,
4238                target_type_extension: None,
4239            }],
4240        }));
4241        let err = verify_alter(1, table_info.clone(), modify).unwrap_err();
4242        let msg = common_error::ext::ErrorExt::output_msg(&err);
4243        assert!(
4244            msg.contains("must keep a type that renders as a string"),
4245            "{msg}"
4246        );
4247
4248        // Dropping a declared column stays allowed: the derivation skips the
4249        // stale declaration.
4250        let drop = alter(Kind::DropColumns(api::v1::DropColumns {
4251            drop_columns: vec![api::v1::DropColumn {
4252                name: "svc".to_string(),
4253            }],
4254        }));
4255        assert!(verify_alter(1, table_info, drop).unwrap());
4256    }
4257
4258    #[test]
4259    fn test_json2_supports_non_append_mode() -> std::result::Result<(), Box<dyn std::error::Error>>
4260    {
4261        for options in [
4262            "",
4263            "WITH (append_mode='false')",
4264            "WITH (append_mode='true')",
4265            "WITH (merge_mode='last_non_null')",
4266        ] {
4267            let expr = create_expr_from_sql(&format!(
4268                "CREATE TABLE monitor (payload JSON2, ts TIMESTAMP TIME INDEX) {options};"
4269            ));
4270            create_table_info(&expr, vec![])?;
4271        }
4272        Ok(())
4273    }
4274
4275    #[test]
4276    fn test_json2_cannot_be_primary_key() -> std::result::Result<(), Box<dyn std::error::Error>> {
4277        let expr = create_expr_from_sql(
4278            "CREATE TABLE monitor (payload JSON2, ts TIMESTAMP TIME INDEX, PRIMARY KEY(payload));",
4279        );
4280        let err = create_table_info(&expr, vec![])
4281            .err()
4282            .ok_or("expected JSON2 primary key rejection")?;
4283        assert!(
4284            err.to_string()
4285                .contains("JSON2 column `payload` cannot be a primary key"),
4286            "{err}"
4287        );
4288        Ok(())
4289    }
4290
4291    #[test]
4292    fn test_create_table_with_empty_repartition_column_hint() {
4293        let expr = create_expr_from_sql(
4294            r"
4295CREATE TABLE metrics (
4296  host STRING,
4297  ts TIMESTAMP TIME INDEX,
4298  cpu DOUBLE,
4299  PRIMARY KEY(host)
4300)
4301WITH ('repartition.column.hint' = '')",
4302        );
4303
4304        let err = create_table_info(&expr, vec![]).unwrap_err();
4305        assert!(
4306            err.to_string()
4307                .contains("repartition.column.hint expects exactly one column name")
4308        );
4309    }
4310
4311    #[test]
4312    fn test_create_table_with_multiple_repartition_column_hints() {
4313        let expr = create_expr_from_sql(
4314            r"
4315CREATE TABLE metrics (
4316  host STRING,
4317  region_id STRING,
4318  ts TIMESTAMP TIME INDEX,
4319  cpu DOUBLE,
4320  PRIMARY KEY(host)
4321)
4322WITH ('repartition.column.hint' = 'host,region_id')",
4323        );
4324
4325        let err = create_table_info(&expr, vec![]).unwrap_err();
4326        assert!(
4327            err.to_string()
4328                .contains("repartition.column.hint expects exactly one column name")
4329        );
4330    }
4331
4332    #[test]
4333    fn test_create_table_with_missing_repartition_column_hint() {
4334        let expr = create_expr_from_sql(
4335            r"
4336CREATE TABLE metrics (
4337  host STRING,
4338  ts TIMESTAMP TIME INDEX,
4339  cpu DOUBLE,
4340  PRIMARY KEY(host)
4341)
4342WITH ('repartition.column.hint' = 'region_id')",
4343        );
4344
4345        let err = create_table_info(&expr, vec![]).unwrap_err();
4346        assert!(
4347            err.to_string()
4348                .contains("Cannot find column by name: region")
4349        );
4350    }
4351
4352    #[test]
4353    fn test_create_table_with_time_index_repartition_column_hint() {
4354        let expr = create_expr_from_sql(
4355            r"
4356CREATE TABLE metrics (
4357  host STRING,
4358  ts TIMESTAMP TIME INDEX,
4359  cpu DOUBLE,
4360  PRIMARY KEY(host)
4361)
4362WITH ('repartition.column.hint' = 'ts')",
4363        );
4364
4365        let err = create_table_info(&expr, vec![]).unwrap_err();
4366        assert!(
4367            err.to_string()
4368                .contains("cannot set repartition.column.hint to the time index column")
4369        );
4370    }
4371
4372    #[test]
4373    fn test_create_partitioned_table_with_repartition_column_hint() {
4374        let expr = create_expr_from_sql(
4375            r"
4376CREATE TABLE metrics (
4377  host STRING,
4378  ts TIMESTAMP TIME INDEX,
4379  cpu DOUBLE,
4380  PRIMARY KEY(host)
4381)
4382WITH ('repartition.column.hint' = 'host')",
4383        );
4384
4385        let err = create_table_info(&expr, vec!["host".to_string()]).unwrap_err();
4386        assert!(
4387            err.to_string()
4388                .contains("cannot set repartition.column.hint on a table with partition metadata")
4389        );
4390    }
4391}