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