Skip to main content

operator/
statement.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
15mod admin;
16mod comment;
17mod copy_database;
18mod copy_query_to;
19mod copy_table_from;
20mod copy_table_to;
21mod cursor;
22mod database_copy;
23pub mod ddl;
24mod describe;
25mod dml;
26pub mod export_database;
27pub mod export_logical_tables;
28pub mod import_packed;
29mod kill;
30pub mod semantic_graph;
31mod set;
32mod show;
33mod tql;
34
35use std::collections::HashMap;
36use std::sync::Arc;
37
38use api::v1::RowInsertRequests;
39use catalog::CatalogManagerRef;
40use catalog::kvbackend::KvBackendCatalogManager;
41use catalog::process_manager::ProcessManagerRef;
42use client::RecordBatches;
43use client::error::{ExternalSnafu as ClientExternalSnafu, Result as ClientResult};
44use client::inserter::{InsertOptions, Inserter};
45use common_datasource::object_store::LocalFileAccess;
46use common_error::ext::BoxedError;
47use common_meta::cache_invalidator::CacheInvalidatorRef;
48use common_meta::key::flow::{FlowMetadataManager, FlowMetadataManagerRef};
49use common_meta::key::schema_name::SchemaNameKey;
50use common_meta::key::view_info::{ViewInfoManager, ViewInfoManagerRef};
51use common_meta::key::{TableMetadataManager, TableMetadataManagerRef};
52use common_meta::kv_backend::KvBackendRef;
53use common_meta::procedure_executor::ProcedureExecutorRef;
54#[cfg(feature = "enterprise")]
55use common_meta::rpc::ddl::CreatorGrantIntent;
56use common_query::Output;
57use common_telemetry::{debug, tracing, warn};
58use common_time::Timestamp;
59use common_time::range::TimestampRange;
60use datafusion_expr::LogicalPlan;
61use datatypes::prelude::ConcreteDataType;
62use datatypes::schema::ColumnSchema;
63use humantime::format_duration;
64use itertools::Itertools;
65use partition::manager::PartitionRuleManagerRef;
66use query::QueryEngineRef;
67use query::parser::QueryStatement;
68use session::context::{Channel, QueryContextBuilder, QueryContextRef};
69use session::table_name::table_idents_to_full_name;
70use set::{set_query_timeout, set_read_preference, set_skip_wal};
71use snafu::{OptionExt, ResultExt, ensure};
72use sql::ast::ObjectNamePartExt;
73use sql::statements::OptionMap;
74use sql::statements::copy::{
75    CopyDatabase, CopyDatabaseArgument, CopyQueryToArgument, CopyTable, CopyTableArgument,
76};
77use sql::statements::set_variables::SetVariables;
78use sql::statements::show::ShowCreateTableVariant;
79use sql::statements::statement::Statement;
80use sql::util::format_raw_object_name;
81use sqlparser::ast::ObjectName;
82use store_api::mito_engine_options::{APPEND_MODE_KEY, TTL_KEY};
83use table::TableRef;
84use table::requests::{CopyDatabaseRequest, CopyDirection, CopyQueryToRequest, CopyTableRequest};
85use table::table_name::TableName;
86use table::table_reference::TableReference;
87
88pub use self::admin::{
89    AdminEventRecorderHandle, AdminFunctionLayer, AdminFunctionLayerRef,
90    AdminFunctionRecordingLayer, AdminFunctionRequest, AdminFunctionResponse, AdminFunctionService,
91    AdminFunctionServiceRef, admin_output_schema,
92};
93use self::set::{
94    set_bytea_output, set_datestyle, set_intervalstyle, set_timezone, validate_client_encoding,
95};
96use crate::error::{
97    self, CatalogSnafu, ExecLogicalPlanSnafu, ExternalSnafu, InvalidSqlSnafu, NotSupportedSnafu,
98    PlanStatementSnafu, Result, SchemaNotFoundSnafu, SqlCommonSnafu, TableMetadataManagerSnafu,
99    TableNotFoundSnafu, UnexpectedSnafu, UpgradeCatalogManagerRefSnafu,
100};
101use crate::insert::InserterRef;
102use crate::statement::copy_database::{COPY_DATABASE_TIME_END_KEY, COPY_DATABASE_TIME_START_KEY};
103use crate::statement::set::set_query_option;
104
105/// A configurator that customizes or enhances a [`StatementExecutor`].
106#[async_trait::async_trait]
107pub trait StatementExecutorConfigurator: Send + Sync {
108    async fn configure(
109        &self,
110        executor: StatementExecutor,
111        ctx: ExecutorConfigureContext,
112    ) -> std::result::Result<StatementExecutor, BoxedError>;
113}
114
115pub type StatementExecutorConfiguratorRef = Arc<dyn StatementExecutorConfigurator>;
116
117#[cfg(feature = "enterprise")]
118#[async_trait::async_trait]
119pub trait CreateDatabaseHandler: Send + Sync {
120    fn creator(
121        &self,
122        query_ctx: &QueryContextRef,
123    ) -> std::result::Result<Option<CreatorGrantIntent>, BoxedError>;
124
125    async fn refresh_current_user(
126        &self,
127        query_ctx: &QueryContextRef,
128    ) -> std::result::Result<(), BoxedError>;
129}
130
131#[cfg(feature = "enterprise")]
132pub type CreateDatabaseHandlerRef = Arc<dyn CreateDatabaseHandler>;
133
134pub struct ExecutorConfigureContext {
135    pub kv_backend: KvBackendRef,
136}
137
138#[derive(Clone)]
139pub struct StatementExecutor {
140    catalog_manager: CatalogManagerRef,
141    query_engine: QueryEngineRef,
142    procedure_executor: ProcedureExecutorRef,
143    table_metadata_manager: TableMetadataManagerRef,
144    flow_metadata_manager: FlowMetadataManagerRef,
145    view_info_manager: ViewInfoManagerRef,
146    partition_manager: PartitionRuleManagerRef,
147    cache_invalidator: CacheInvalidatorRef,
148    inserter: InserterRef,
149    process_manager: Option<ProcessManagerRef>,
150    origin_frontend_addr: String,
151    admin_function_service: AdminFunctionServiceRef,
152    pub(crate) local_file_access: LocalFileAccess,
153    #[cfg(feature = "enterprise")]
154    create_database_handler: Option<CreateDatabaseHandlerRef>,
155    #[cfg(feature = "enterprise")]
156    trigger_querier: Option<TriggerQuerierRef>,
157}
158
159pub type StatementExecutorRef = Arc<StatementExecutor>;
160
161/// Trait for querying trigger info, such as `SHOW CREATE TRIGGER` etc.
162#[cfg(feature = "enterprise")]
163#[async_trait::async_trait]
164pub trait TriggerQuerier: Send + Sync {
165    // Query the `SHOW CREATE TRIGGER` statement for the given trigger.
166    async fn show_create_trigger(
167        &self,
168        catalog: &str,
169        trigger: &str,
170        query_ctx: &QueryContextRef,
171    ) -> std::result::Result<Output, BoxedError>;
172
173    fn as_any(&self) -> &dyn std::any::Any;
174}
175
176#[cfg(feature = "enterprise")]
177pub type TriggerQuerierRef = Arc<dyn TriggerQuerier>;
178
179impl StatementExecutor {
180    #[allow(clippy::too_many_arguments)]
181    pub fn new(
182        catalog_manager: CatalogManagerRef,
183        query_engine: QueryEngineRef,
184        procedure_executor: ProcedureExecutorRef,
185        kv_backend: KvBackendRef,
186        cache_invalidator: CacheInvalidatorRef,
187        inserter: InserterRef,
188        partition_manager: PartitionRuleManagerRef,
189        process_manager: Option<ProcessManagerRef>,
190        origin_frontend_addr: String,
191        local_file_access: LocalFileAccess,
192    ) -> Self {
193        let admin_function_service = admin::new_admin_function_service(query_engine.clone());
194        Self {
195            catalog_manager,
196            query_engine,
197            procedure_executor,
198            table_metadata_manager: Arc::new(TableMetadataManager::new(kv_backend.clone())),
199            flow_metadata_manager: Arc::new(FlowMetadataManager::new(kv_backend.clone())),
200            view_info_manager: Arc::new(ViewInfoManager::new(kv_backend.clone())),
201            partition_manager,
202            cache_invalidator,
203            inserter,
204            process_manager,
205            origin_frontend_addr,
206            admin_function_service,
207            local_file_access,
208            #[cfg(feature = "enterprise")]
209            create_database_handler: None,
210            #[cfg(feature = "enterprise")]
211            trigger_querier: None,
212        }
213    }
214
215    /// Adds a layer around the ADMIN function execution service.
216    ///
217    /// The last added layer is the outermost layer.
218    pub fn with_admin_function_layer(mut self, layer: AdminFunctionLayerRef) -> Self {
219        self.admin_function_service = layer.layer(self.admin_function_service);
220        self
221    }
222
223    #[cfg(feature = "enterprise")]
224    pub fn with_trigger_querier(mut self, querier: TriggerQuerierRef) -> Self {
225        self.trigger_querier = Some(querier);
226        self
227    }
228
229    #[cfg(feature = "enterprise")]
230    pub fn with_create_database_handler(mut self, handler: CreateDatabaseHandlerRef) -> Self {
231        self.create_database_handler = Some(handler);
232        self
233    }
234
235    #[cfg(feature = "testing")]
236    pub async fn execute_stmt(
237        &self,
238        stmt: QueryStatement,
239        query_ctx: QueryContextRef,
240    ) -> Result<Output> {
241        match stmt {
242            QueryStatement::Sql(stmt) => self.execute_sql(stmt, query_ctx).await,
243            QueryStatement::Promql(_, _) => self.plan_exec(stmt, query_ctx).await,
244        }
245    }
246
247    #[tracing::instrument(skip_all)]
248    pub async fn execute_sql(&self, stmt: Statement, query_ctx: QueryContextRef) -> Result<Output> {
249        match stmt {
250            Statement::Query(_) | Statement::Explain(_) | Statement::Delete(_) => {
251                self.plan_exec(QueryStatement::Sql(stmt), query_ctx).await
252            }
253
254            Statement::DeclareCursor(declare_cursor) => {
255                self.declare_cursor(declare_cursor, query_ctx).await
256            }
257            Statement::FetchCursor(fetch_cursor) => {
258                self.fetch_cursor(fetch_cursor, query_ctx).await
259            }
260            Statement::CloseCursor(close_cursor) => {
261                self.close_cursor(close_cursor, query_ctx).await
262            }
263
264            Statement::Insert(insert) => self.insert(insert, query_ctx).await,
265
266            Statement::Tql(tql) => self.execute_tql(tql, query_ctx).await,
267
268            Statement::DescribeTable(stmt) => self.describe_table(stmt, query_ctx).await,
269
270            Statement::ShowDatabases(stmt) => self.show_databases(stmt, query_ctx).await,
271
272            Statement::ShowTables(stmt) => self.show_tables(stmt, query_ctx).await,
273
274            Statement::ShowTableStatus(stmt) => self.show_table_status(stmt, query_ctx).await,
275
276            Statement::ShowCollation(kind) => self.show_collation(kind, query_ctx).await,
277
278            Statement::ShowCharset(kind) => self.show_charset(kind, query_ctx).await,
279
280            Statement::ShowViews(stmt) => self.show_views(stmt, query_ctx).await,
281
282            Statement::ShowFlows(stmt) => self.show_flows(stmt, query_ctx).await,
283            Statement::ShowFlowStatus(stmt) => self.show_flow_status(stmt, query_ctx).await,
284
285            #[cfg(feature = "enterprise")]
286            Statement::ShowTriggers(stmt) => self.show_triggers(stmt, query_ctx).await,
287
288            Statement::Copy(sql::statements::copy::Copy::CopyQueryTo(stmt)) => {
289                let query_output = self
290                    .plan_exec(QueryStatement::Sql(*stmt.query), query_ctx)
291                    .await?;
292                let req = to_copy_query_request(stmt.arg)?;
293
294                self.copy_query_to(req, query_output)
295                    .await
296                    .map(Output::new_with_affected_rows)
297            }
298
299            Statement::Copy(sql::statements::copy::Copy::CopyTable(stmt)) => {
300                let req = to_copy_table_request(stmt, query_ctx.clone())?;
301                match req.direction {
302                    CopyDirection::Export => self
303                        .copy_table_to(req, query_ctx)
304                        .await
305                        .map(Output::new_with_affected_rows),
306                    CopyDirection::Import => self.copy_table_from(req, query_ctx).await,
307                }
308            }
309
310            Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy_database)) => {
311                match copy_database {
312                    CopyDatabase::To(arg) => {
313                        self.copy_database_to(
314                            to_copy_database_request(arg, &query_ctx)?,
315                            query_ctx.clone(),
316                        )
317                        .await
318                    }
319                    CopyDatabase::From(arg) => {
320                        self.copy_database_from(
321                            to_copy_database_request(arg, &query_ctx)?,
322                            query_ctx,
323                        )
324                        .await
325                    }
326                }
327            }
328
329            Statement::CreateTable(stmt) => {
330                let _ = self.create_table(stmt, query_ctx).await?;
331                Ok(Output::new_with_affected_rows(0))
332            }
333            Statement::CreateTableLike(stmt) => {
334                let _ = self.create_table_like(stmt, query_ctx).await?;
335                Ok(Output::new_with_affected_rows(0))
336            }
337            Statement::CreateExternalTable(stmt) => {
338                let _ = self.create_external_table(stmt, query_ctx).await?;
339                Ok(Output::new_with_affected_rows(0))
340            }
341            Statement::CreateFlow(stmt) => self.create_flow(stmt, query_ctx).await,
342            #[cfg(feature = "enterprise")]
343            Statement::CreateTrigger(stmt) => self.create_trigger(stmt, query_ctx).await,
344            Statement::DropFlow(stmt) => {
345                self.drop_flow(
346                    query_ctx.current_catalog().to_string(),
347                    format_raw_object_name(stmt.flow_name()),
348                    stmt.drop_if_exists(),
349                    query_ctx,
350                )
351                .await
352            }
353            #[cfg(feature = "enterprise")]
354            Statement::DropTrigger(stmt) => {
355                self.drop_trigger(
356                    query_ctx.current_catalog().to_string(),
357                    format_raw_object_name(stmt.trigger_name()),
358                    stmt.drop_if_exists(),
359                    query_ctx,
360                )
361                .await
362            }
363            Statement::CreateView(stmt) => {
364                let _ = self.create_view(stmt, query_ctx).await?;
365                Ok(Output::new_with_affected_rows(0))
366            }
367            Statement::DropView(stmt) => {
368                let (catalog_name, schema_name, view_name) =
369                    table_idents_to_full_name(&stmt.view_name, &query_ctx)
370                        .map_err(BoxedError::new)
371                        .context(ExternalSnafu)?;
372
373                self.drop_view(
374                    catalog_name,
375                    schema_name,
376                    view_name,
377                    stmt.drop_if_exists,
378                    query_ctx,
379                )
380                .await
381            }
382            Statement::AlterTable(alter_table) => self.alter_table(alter_table, query_ctx).await,
383
384            Statement::AlterDatabase(alter_database) => {
385                self.alter_database(alter_database, query_ctx).await
386            }
387
388            #[cfg(feature = "enterprise")]
389            Statement::AlterTrigger(alter_trigger) => {
390                self.alter_trigger(alter_trigger, query_ctx).await
391            }
392
393            Statement::DropTable(stmt) => {
394                let mut table_names = Vec::with_capacity(stmt.table_names().len());
395                for table_name_stmt in stmt.table_names() {
396                    let (catalog, schema, table) =
397                        table_idents_to_full_name(table_name_stmt, &query_ctx)
398                            .map_err(BoxedError::new)
399                            .context(ExternalSnafu)?;
400                    table_names.push(TableName::new(catalog, schema, table));
401                }
402                self.drop_tables(&table_names[..], stmt.drop_if_exists(), query_ctx.clone())
403                    .await
404            }
405            #[cfg(feature = "enterprise")]
406            Statement::UndropTable(stmt) => {
407                let (catalog, schema, table) =
408                    table_idents_to_full_name(stmt.table_name(), &query_ctx)
409                        .map_err(BoxedError::new)
410                        .context(ExternalSnafu)?;
411                self.undrop_table(TableName::new(catalog, schema, table), query_ctx)
412                    .await
413            }
414            Statement::DropDatabase(stmt) => {
415                self.drop_database(
416                    query_ctx.current_catalog().to_string(),
417                    format_raw_object_name(stmt.name()),
418                    stmt.drop_if_exists(),
419                    query_ctx,
420                )
421                .await
422            }
423            Statement::TruncateTable(stmt) => {
424                let (catalog, schema, table) =
425                    table_idents_to_full_name(stmt.table_name(), &query_ctx)
426                        .map_err(BoxedError::new)
427                        .context(ExternalSnafu)?;
428                let table_name = TableName::new(catalog, schema, table);
429                let time_ranges = self
430                    .convert_truncate_time_ranges(&table_name, stmt.time_ranges(), &query_ctx)
431                    .await?;
432                self.truncate_table(table_name, time_ranges, query_ctx)
433                    .await
434            }
435            Statement::CreateDatabase(stmt) => {
436                self.create_database(
437                    &format_raw_object_name(&stmt.name),
438                    stmt.if_not_exists,
439                    stmt.options.into_map(),
440                    query_ctx,
441                )
442                .await
443            }
444            Statement::ShowCreateDatabase(show) => {
445                let (catalog, database) =
446                    idents_to_full_database_name(&show.database_name, &query_ctx)
447                        .map_err(BoxedError::new)
448                        .context(ExternalSnafu)?;
449                let table_metadata_manager = self
450                    .catalog_manager
451                    .as_any()
452                    .downcast_ref::<KvBackendCatalogManager>()
453                    .map(|manager| manager.table_metadata_manager_ref().clone())
454                    .context(UpgradeCatalogManagerRefSnafu)?;
455                let opts: HashMap<String, String> = table_metadata_manager
456                    .schema_manager()
457                    .get(SchemaNameKey::new(&catalog, &database))
458                    .await
459                    .context(TableMetadataManagerSnafu)?
460                    .context(SchemaNotFoundSnafu {
461                        schema_info: &database,
462                    })?
463                    .into_inner()
464                    .into();
465
466                self.show_create_database(&database, opts.into()).await
467            }
468            Statement::ShowCreateTable(show) => {
469                let (catalog, schema, table) =
470                    table_idents_to_full_name(&show.table_name, &query_ctx)
471                        .map_err(BoxedError::new)
472                        .context(ExternalSnafu)?;
473
474                let table_ref = self
475                    .catalog_manager
476                    .table(&catalog, &schema, &table, Some(&query_ctx))
477                    .await
478                    .context(CatalogSnafu)?
479                    .context(TableNotFoundSnafu { table_name: &table })?;
480                let table_name = TableName::new(catalog, schema, table);
481
482                match show.variant {
483                    ShowCreateTableVariant::Original => {
484                        self.show_create_table(table_name, table_ref, query_ctx)
485                            .await
486                    }
487                    ShowCreateTableVariant::PostgresForeignTable => {
488                        self.show_create_table_for_pg(table_name, table_ref, query_ctx)
489                            .await
490                    }
491                }
492            }
493            Statement::ShowCreateFlow(show) => self.show_create_flow(show, query_ctx).await,
494            Statement::ShowCreateView(show) => self.show_create_view(show, query_ctx).await,
495            #[cfg(feature = "enterprise")]
496            Statement::ShowCreateTrigger(show) => self.show_create_trigger(show, query_ctx).await,
497            Statement::SetVariables(set_var) => self.set_variables(set_var, query_ctx),
498            Statement::ShowVariables(show_variable) => self.show_variable(show_variable, query_ctx),
499            Statement::Comment(stmt) => self.comment(stmt, query_ctx).await,
500            Statement::ShowColumns(show_columns) => {
501                self.show_columns(show_columns, query_ctx).await
502            }
503            Statement::ShowIndex(show_index) => self.show_index(show_index, query_ctx).await,
504            Statement::ShowRegion(show_region) => self.show_region(show_region, query_ctx).await,
505            Statement::ShowStatus(_) => self.show_status(query_ctx).await,
506            Statement::ShowSearchPath(_) => self.show_search_path(query_ctx).await,
507            Statement::Use(db) => self.use_database(db, query_ctx).await,
508            Statement::Admin(admin) => self.execute_admin_command(admin, query_ctx).await,
509            Statement::Kill(kill) => self.execute_kill(query_ctx, kill).await,
510            Statement::ShowProcesslist(show) => self.show_processlist(show, query_ctx).await,
511        }
512    }
513
514    pub async fn use_database(&self, db: String, query_ctx: QueryContextRef) -> Result<Output> {
515        let catalog = query_ctx.current_catalog();
516        ensure!(
517            self.catalog_manager
518                .schema_exists(catalog, db.as_ref(), Some(&query_ctx))
519                .await
520                .context(CatalogSnafu)?,
521            SchemaNotFoundSnafu { schema_info: &db }
522        );
523
524        query_ctx.set_current_schema(&db);
525
526        Ok(Output::new_with_record_batches(RecordBatches::empty()))
527    }
528
529    fn set_variables(&self, set_var: SetVariables, query_ctx: QueryContextRef) -> Result<Output> {
530        let variable = sql::ast::object_name_to_string_unquoted(&set_var.variable);
531        let var_name = variable.to_uppercase();
532
533        debug!(
534            "Trying to set {}={} for session: {} ",
535            var_name,
536            set_var.value.iter().map(|e| e.to_string()).join(", "),
537            query_ctx.conn_info()
538        );
539
540        if set_query_option(&variable, set_var.value.clone(), query_ctx.clone())? {
541            return Ok(Output::new_with_affected_rows(0));
542        }
543
544        match var_name.as_str() {
545            "READ_PREFERENCE" => set_read_preference(set_var.value, query_ctx)?,
546            "SKIP_WAL" => set_skip_wal(set_var.value, query_ctx)?,
547
548            "@@TIME_ZONE" | "@@SESSION.TIME_ZONE" | "TIMEZONE" | "TIME_ZONE" => {
549                set_timezone(set_var.value, query_ctx)?
550            }
551
552            "BYTEA_OUTPUT" => set_bytea_output(set_var.value, query_ctx)?,
553
554            // Same as "bytea_output", we just ignore it here.
555            // Not harmful since it only relates to how date is viewed in client app's output.
556            // The tracked issue is https://github.com/GreptimeTeam/greptimedb/issues/3442.
557            "DATESTYLE" => set_datestyle(set_var.value, query_ctx)?,
558            "INTERVALSTYLE" => set_intervalstyle(set_var.value, query_ctx)?,
559
560            "CLIENT_ENCODING" => validate_client_encoding(set_var)?,
561            "@@SESSION.MAX_EXECUTION_TIME" | "MAX_EXECUTION_TIME" => match query_ctx.channel() {
562                Channel::Mysql => set_query_timeout(set_var.value, query_ctx)?,
563                Channel::Postgres => {
564                    warn!(
565                        "Unsupported set variable {} for channel {:?}",
566                        var_name,
567                        query_ctx.channel()
568                    );
569                    query_ctx.set_warning(format!("Unsupported set variable {}", var_name))
570                }
571                _ => {
572                    return NotSupportedSnafu {
573                        feat: format!("Unsupported set variable {}", var_name),
574                    }
575                    .fail();
576                }
577            },
578            "STATEMENT_TIMEOUT" => match query_ctx.channel() {
579                Channel::Postgres => set_query_timeout(set_var.value, query_ctx)?,
580                Channel::Mysql => {
581                    warn!(
582                        "Unsupported set variable {} for channel {:?}",
583                        var_name,
584                        query_ctx.channel()
585                    );
586                    query_ctx.set_warning(format!("Unsupported set variable {}", var_name));
587                }
588                _ => {
589                    return NotSupportedSnafu {
590                        feat: format!("Unsupported set variable {}", var_name),
591                    }
592                    .fail();
593                }
594            },
595            "SEARCH_PATH" => {
596                if query_ctx.channel() == Channel::Postgres {
597                    let search_path = set_var.search_path().context(NotSupportedSnafu {
598                        feat: "Unsupported search path in set variable statement",
599                    })?;
600                    query_ctx.set_current_schema(search_path);
601                } else {
602                    return NotSupportedSnafu {
603                        feat: format!("Unsupported set variable {}", var_name),
604                    }
605                    .fail();
606                }
607            }
608            _ => {
609                if query_ctx.channel() == Channel::Postgres || query_ctx.channel() == Channel::Mysql
610                {
611                    // For unknown SET statements, we give a warning with success.
612                    // This prevents the SET call from becoming a blocker of MySQL/Postgres clients'
613                    // connection establishment.
614                    warn!(
615                        "Unsupported set variable {} for channel {:?}",
616                        var_name,
617                        query_ctx.channel()
618                    );
619                    query_ctx.set_warning(format!("Unsupported set variable {}", var_name));
620                } else {
621                    return NotSupportedSnafu {
622                        feat: format!("Unsupported set variable {}", var_name),
623                    }
624                    .fail();
625                }
626            }
627        }
628        Ok(Output::new_with_affected_rows(0))
629    }
630
631    #[tracing::instrument(skip_all)]
632    pub async fn plan(
633        &self,
634        stmt: &QueryStatement,
635        query_ctx: QueryContextRef,
636    ) -> Result<LogicalPlan> {
637        self.query_engine
638            .planner()
639            .plan(stmt, query_ctx)
640            .await
641            .context(PlanStatementSnafu)
642    }
643
644    /// Execute [`LogicalPlan`] directly.
645    #[tracing::instrument(skip_all)]
646    pub async fn exec_plan(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
647        self.query_engine
648            .execute(plan, query_ctx)
649            .await
650            .context(ExecLogicalPlanSnafu)
651    }
652
653    pub fn optimize_logical_plan(&self, plan: LogicalPlan) -> Result<LogicalPlan> {
654        self.query_engine
655            .planner()
656            .optimize(plan)
657            .context(PlanStatementSnafu)
658    }
659
660    #[tracing::instrument(skip_all)]
661    async fn plan_exec(&self, stmt: QueryStatement, query_ctx: QueryContextRef) -> Result<Output> {
662        let plan = self.plan(&stmt, query_ctx.clone()).await?;
663        self.exec_plan(plan, query_ctx).await
664    }
665
666    async fn get_table(&self, table_ref: &TableReference<'_>) -> Result<TableRef> {
667        let TableReference {
668            catalog,
669            schema,
670            table,
671        } = table_ref;
672        self.catalog_manager
673            .table(catalog, schema, table, None)
674            .await
675            .context(CatalogSnafu)?
676            .with_context(|| TableNotFoundSnafu {
677                table_name: table_ref.to_string(),
678            })
679    }
680
681    pub fn procedure_executor(&self) -> &ProcedureExecutorRef {
682        &self.procedure_executor
683    }
684
685    pub fn cache_invalidator(&self) -> &CacheInvalidatorRef {
686        &self.cache_invalidator
687    }
688
689    /// Convert truncate time ranges for the given table from sql values to timestamps
690    ///
691    pub async fn convert_truncate_time_ranges(
692        &self,
693        table_name: &TableName,
694        sql_values_time_range: &[(sqlparser::ast::Value, sqlparser::ast::Value)],
695        query_ctx: &QueryContextRef,
696    ) -> Result<Vec<(Timestamp, Timestamp)>> {
697        if sql_values_time_range.is_empty() {
698            return Ok(vec![]);
699        }
700        let table = self.get_table(&table_name.table_ref()).await?;
701        let info = table.table_info();
702        let time_index_dt = info
703            .meta
704            .schema
705            .timestamp_column()
706            .context(UnexpectedSnafu {
707                violated: "Table must have a timestamp column",
708            })?;
709
710        let time_unit = time_index_dt
711            .data_type
712            .as_timestamp()
713            .with_context(|| UnexpectedSnafu {
714                violated: format!(
715                    "Table {}'s time index column must be a timestamp type, found: {:?}",
716                    table_name, time_index_dt
717                ),
718            })?
719            .unit();
720
721        let start_column = ColumnSchema::new(
722            "range_start",
723            ConcreteDataType::timestamp_datatype(time_unit),
724            false,
725        );
726        let end_column = ColumnSchema::new(
727            "range_end",
728            ConcreteDataType::timestamp_datatype(time_unit),
729            false,
730        );
731        let mut time_ranges = Vec::with_capacity(sql_values_time_range.len());
732        for (start, end) in sql_values_time_range {
733            let start = common_sql::convert::sql_value_to_value(
734                &start_column,
735                start,
736                Some(&query_ctx.timezone()),
737                None,
738                false,
739            )
740            .context(SqlCommonSnafu)
741            .and_then(|v| {
742                if let datatypes::value::Value::Timestamp(t) = v {
743                    Ok(t)
744                } else {
745                    error::InvalidSqlSnafu {
746                        err_msg: format!("Expected a timestamp value, found {v:?}"),
747                    }
748                    .fail()
749                }
750            })?;
751
752            let end = common_sql::convert::sql_value_to_value(
753                &end_column,
754                end,
755                Some(&query_ctx.timezone()),
756                None,
757                false,
758            )
759            .context(SqlCommonSnafu)
760            .and_then(|v| {
761                if let datatypes::value::Value::Timestamp(t) = v {
762                    Ok(t)
763                } else {
764                    error::InvalidSqlSnafu {
765                        err_msg: format!("Expected a timestamp value, found {v:?}"),
766                    }
767                    .fail()
768                }
769            })?;
770            time_ranges.push((start, end));
771        }
772        Ok(time_ranges)
773    }
774
775    /// Returns the inserter for the statement executor.
776    pub(crate) fn inserter(&self) -> &InserterRef {
777        &self.inserter
778    }
779}
780
781fn to_copy_query_request(stmt: CopyQueryToArgument) -> Result<CopyQueryToRequest> {
782    let CopyQueryToArgument {
783        with,
784        connection,
785        location,
786    } = stmt;
787
788    Ok(CopyQueryToRequest {
789        location,
790        with: with.into_map(),
791        connection: connection.into_map(),
792    })
793}
794
795// Verifies time related format is valid
796fn verify_time_related_format(with: &OptionMap) -> Result<()> {
797    let time_format = with.get(common_datasource::file_format::TIME_FORMAT);
798    let date_format = with.get(common_datasource::file_format::DATE_FORMAT);
799    let timestamp_format = with.get(common_datasource::file_format::TIMESTAMP_FORMAT);
800    let file_format = with.get(common_datasource::file_format::FORMAT_TYPE);
801
802    if !matches!(file_format, Some(f) if f.eq_ignore_ascii_case("csv")) {
803        ensure!(
804            time_format.is_none() && date_format.is_none() && timestamp_format.is_none(),
805            error::TimestampFormatNotSupportedSnafu {
806                format: "<unknown>".to_string(),
807                file_format: file_format.unwrap_or_default(),
808            }
809        );
810    }
811
812    for (key, format_opt) in [
813        (common_datasource::file_format::TIME_FORMAT, time_format),
814        (common_datasource::file_format::DATE_FORMAT, date_format),
815        (
816            common_datasource::file_format::TIMESTAMP_FORMAT,
817            timestamp_format,
818        ),
819    ] {
820        if let Some(format) = format_opt {
821            chrono::format::strftime::StrftimeItems::new(format)
822                .parse()
823                .map_err(|_| error::InvalidCopyParameterSnafu { key, value: format }.build())?;
824        }
825    }
826
827    Ok(())
828}
829
830fn to_copy_table_request(stmt: CopyTable, query_ctx: QueryContextRef) -> Result<CopyTableRequest> {
831    let direction = match stmt {
832        CopyTable::To(_) => CopyDirection::Export,
833        CopyTable::From(_) => CopyDirection::Import,
834    };
835
836    let CopyTableArgument {
837        location,
838        connection,
839        with,
840        table_name,
841        limit,
842        ..
843    } = match stmt {
844        CopyTable::To(arg) => arg,
845        CopyTable::From(arg) => arg,
846    };
847    let (catalog_name, schema_name, table_name) =
848        table_idents_to_full_name(&table_name, &query_ctx)
849            .map_err(BoxedError::new)
850            .context(ExternalSnafu)?;
851
852    let timestamp_range = timestamp_range_from_option_map(&with, &query_ctx)?;
853
854    verify_time_related_format(&with)?;
855
856    let pattern = with
857        .get(common_datasource::file_format::FILE_PATTERN)
858        .map(|x| x.to_string());
859
860    Ok(CopyTableRequest {
861        catalog_name,
862        schema_name,
863        table_name,
864        location,
865        with: with.into_map(),
866        connection: connection.into_map(),
867        pattern,
868        direction,
869        timestamp_range,
870        limit,
871    })
872}
873
874/// Converts [CopyDatabaseArgument] to [CopyDatabaseRequest].
875/// This function extracts the necessary info including catalog/database name, time range, etc.
876pub fn to_copy_database_request(
877    arg: CopyDatabaseArgument,
878    query_ctx: &QueryContextRef,
879) -> Result<CopyDatabaseRequest> {
880    let (catalog_name, database_name) = idents_to_full_database_name(&arg.database_name, query_ctx)
881        .map_err(BoxedError::new)
882        .context(ExternalSnafu)?;
883    let time_range = timestamp_range_from_option_map(&arg.with, query_ctx)?;
884
885    Ok(CopyDatabaseRequest {
886        catalog_name,
887        schema_name: database_name,
888        location: arg.location,
889        with: arg.with.into_map(),
890        connection: arg.connection.into_map(),
891        time_range,
892    })
893}
894
895/// Extracts timestamp range from OptionMap with keys `start_time` and `end_time`.
896/// The timestamp ranges should be a valid timestamp string as defined in [Timestamp::from_str].
897/// The timezone used for conversion will respect that inside `query_ctx`.
898fn timestamp_range_from_option_map(
899    options: &OptionMap,
900    query_ctx: &QueryContextRef,
901) -> Result<Option<TimestampRange>> {
902    let start_timestamp = extract_timestamp(options, COPY_DATABASE_TIME_START_KEY, query_ctx)?;
903    let end_timestamp = extract_timestamp(options, COPY_DATABASE_TIME_END_KEY, query_ctx)?;
904    let time_range = match (start_timestamp, end_timestamp) {
905        (Some(start), Some(end)) => Some(TimestampRange::new(start, end).with_context(|| {
906            error::InvalidTimestampRangeSnafu {
907                start: start.to_iso8601_string(),
908                end: end.to_iso8601_string(),
909            }
910        })?),
911        (Some(start), None) => Some(TimestampRange::from_start(start)),
912        (None, Some(end)) => Some(TimestampRange::until_end(end, false)), // exclusive end
913        (None, None) => None,
914    };
915    Ok(time_range)
916}
917
918/// Extracts timestamp from a [HashMap<String, String>] with given key.
919fn extract_timestamp(
920    map: &OptionMap,
921    key: &str,
922    query_ctx: &QueryContextRef,
923) -> Result<Option<Timestamp>> {
924    map.get(key)
925        .map(|v| {
926            Timestamp::from_str(v, Some(&query_ctx.timezone()))
927                .map_err(|_| error::InvalidCopyParameterSnafu { key, value: v }.build())
928        })
929        .transpose()
930}
931
932fn idents_to_full_database_name(
933    obj_name: &ObjectName,
934    query_ctx: &QueryContextRef,
935) -> Result<(String, String)> {
936    match &obj_name.0[..] {
937        [database] => Ok((
938            query_ctx.current_catalog().to_owned(),
939            database.to_string_unquoted(),
940        )),
941        [catalog, database] => Ok((catalog.to_string_unquoted(), database.to_string_unquoted())),
942        _ => InvalidSqlSnafu {
943            err_msg: format!(
944                "expect database name to be <catalog>.<database>, <database>, found: {obj_name}",
945            ),
946        }
947        .fail(),
948    }
949}
950
951/// The [`Inserter`] implementation for the statement executor.
952pub struct InserterImpl {
953    statement_executor: StatementExecutorRef,
954    options: Option<InsertOptions>,
955}
956
957impl InserterImpl {
958    pub fn new(statement_executor: StatementExecutorRef, options: Option<InsertOptions>) -> Self {
959        Self {
960            statement_executor,
961            options,
962        }
963    }
964}
965
966#[async_trait::async_trait]
967impl Inserter for InserterImpl {
968    async fn insert_rows(
969        &self,
970        context: &client::inserter::Context<'_>,
971        requests: RowInsertRequests,
972    ) -> ClientResult<()> {
973        let mut ctx_builder = QueryContextBuilder::default()
974            .current_catalog(context.catalog.to_string())
975            .current_schema(context.schema.to_string());
976        if let Some(options) = self.options.as_ref() {
977            ctx_builder = ctx_builder
978                .set_extension(
979                    TTL_KEY.to_string(),
980                    format_duration(options.ttl).to_string(),
981                )
982                .set_extension(APPEND_MODE_KEY.to_string(), options.append_mode.to_string());
983        }
984        let query_ctx = ctx_builder.build().into();
985
986        self.statement_executor
987            .inserter()
988            .handle_row_inserts(
989                requests,
990                query_ctx,
991                self.statement_executor.as_ref(),
992                false,
993                false,
994            )
995            .await
996            .map_err(BoxedError::new)
997            .context(ClientExternalSnafu)
998            .map(|_| ())
999    }
1000
1001    fn set_options(&mut self, options: &InsertOptions) {
1002        self.options = Some(*options);
1003    }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008    use std::assert_matches;
1009    use std::collections::HashMap;
1010
1011    use common_time::range::TimestampRange;
1012    use common_time::{Timestamp, Timezone};
1013    use session::context::QueryContextBuilder;
1014    use sql::statements::OptionMap;
1015
1016    use crate::error;
1017    use crate::statement::copy_database::{
1018        COPY_DATABASE_TIME_END_KEY, COPY_DATABASE_TIME_START_KEY,
1019    };
1020    use crate::statement::{timestamp_range_from_option_map, verify_time_related_format};
1021
1022    fn check_timestamp_range((start, end): (&str, &str)) -> error::Result<Option<TimestampRange>> {
1023        let query_ctx = QueryContextBuilder::default()
1024            .timezone(Timezone::from_tz_string("Asia/Shanghai").unwrap())
1025            .build()
1026            .into();
1027        let map = OptionMap::from(
1028            [
1029                (COPY_DATABASE_TIME_START_KEY.to_string(), start.to_string()),
1030                (COPY_DATABASE_TIME_END_KEY.to_string(), end.to_string()),
1031            ]
1032            .into_iter()
1033            .collect::<HashMap<_, _>>(),
1034        );
1035        timestamp_range_from_option_map(&map, &query_ctx)
1036    }
1037
1038    #[test]
1039    fn test_timestamp_range_from_option_map() {
1040        assert_eq!(
1041            Some(
1042                TimestampRange::new(
1043                    Timestamp::new_second(1649635200),
1044                    Timestamp::new_second(1649664000),
1045                )
1046                .unwrap(),
1047            ),
1048            check_timestamp_range(("2022-04-11 08:00:00", "2022-04-11 16:00:00"),).unwrap()
1049        );
1050
1051        assert_matches!(
1052            check_timestamp_range(("2022-04-11 08:00:00", "2022-04-11 07:00:00")).unwrap_err(),
1053            error::Error::InvalidTimestampRange { .. }
1054        );
1055    }
1056
1057    #[test]
1058    fn test_verify_timestamp_format() {
1059        let map = OptionMap::from(
1060            [
1061                (
1062                    common_datasource::file_format::TIMESTAMP_FORMAT.to_string(),
1063                    "%Y-%m-%d %H:%M:%S".to_string(),
1064                ),
1065                (
1066                    common_datasource::file_format::FORMAT_TYPE.to_string(),
1067                    "csv".to_string(),
1068                ),
1069            ]
1070            .into_iter()
1071            .collect::<HashMap<_, _>>(),
1072        );
1073        assert!(verify_time_related_format(&map).is_ok());
1074
1075        let map = OptionMap::from(
1076            [
1077                (
1078                    common_datasource::file_format::TIMESTAMP_FORMAT.to_string(),
1079                    "%Y-%m-%d %H:%M:%S".to_string(),
1080                ),
1081                (
1082                    common_datasource::file_format::FORMAT_TYPE.to_string(),
1083                    "json".to_string(),
1084                ),
1085            ]
1086            .into_iter()
1087            .collect::<HashMap<_, _>>(),
1088        );
1089
1090        assert_matches!(
1091            verify_time_related_format(&map).unwrap_err(),
1092            error::Error::TimestampFormatNotSupported { .. }
1093        );
1094        let map = OptionMap::from(
1095            [
1096                (
1097                    common_datasource::file_format::TIMESTAMP_FORMAT.to_string(),
1098                    "%111112".to_string(),
1099                ),
1100                (
1101                    common_datasource::file_format::FORMAT_TYPE.to_string(),
1102                    "csv".to_string(),
1103                ),
1104            ]
1105            .into_iter()
1106            .collect::<HashMap<_, _>>(),
1107        );
1108
1109        assert_matches!(
1110            verify_time_related_format(&map).unwrap_err(),
1111            error::Error::InvalidCopyParameter { .. }
1112        );
1113    }
1114}