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_allow_query_fallback;
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 var_name = set_var.variable.to_string().to_uppercase();
531
532        debug!(
533            "Trying to set {}={} for session: {} ",
534            var_name,
535            set_var.value.iter().map(|e| e.to_string()).join(", "),
536            query_ctx.conn_info()
537        );
538
539        match var_name.as_str() {
540            "READ_PREFERENCE" => set_read_preference(set_var.value, query_ctx)?,
541            "SKIP_WAL" => set_skip_wal(set_var.value, query_ctx)?,
542
543            "@@TIME_ZONE" | "@@SESSION.TIME_ZONE" | "TIMEZONE" | "TIME_ZONE" => {
544                set_timezone(set_var.value, query_ctx)?
545            }
546
547            "BYTEA_OUTPUT" => set_bytea_output(set_var.value, query_ctx)?,
548
549            // Same as "bytea_output", we just ignore it here.
550            // Not harmful since it only relates to how date is viewed in client app's output.
551            // The tracked issue is https://github.com/GreptimeTeam/greptimedb/issues/3442.
552            "DATESTYLE" => set_datestyle(set_var.value, query_ctx)?,
553            "INTERVALSTYLE" => set_intervalstyle(set_var.value, query_ctx)?,
554
555            // Allow query to fallback when failed to push down.
556            "ALLOW_QUERY_FALLBACK" => set_allow_query_fallback(set_var.value, query_ctx)?,
557
558            "CLIENT_ENCODING" => validate_client_encoding(set_var)?,
559            "@@SESSION.MAX_EXECUTION_TIME" | "MAX_EXECUTION_TIME" => match query_ctx.channel() {
560                Channel::Mysql => set_query_timeout(set_var.value, query_ctx)?,
561                Channel::Postgres => {
562                    warn!(
563                        "Unsupported set variable {} for channel {:?}",
564                        var_name,
565                        query_ctx.channel()
566                    );
567                    query_ctx.set_warning(format!("Unsupported set variable {}", var_name))
568                }
569                _ => {
570                    return NotSupportedSnafu {
571                        feat: format!("Unsupported set variable {}", var_name),
572                    }
573                    .fail();
574                }
575            },
576            "STATEMENT_TIMEOUT" => match query_ctx.channel() {
577                Channel::Postgres => set_query_timeout(set_var.value, query_ctx)?,
578                Channel::Mysql => {
579                    warn!(
580                        "Unsupported set variable {} for channel {:?}",
581                        var_name,
582                        query_ctx.channel()
583                    );
584                    query_ctx.set_warning(format!("Unsupported set variable {}", var_name));
585                }
586                _ => {
587                    return NotSupportedSnafu {
588                        feat: format!("Unsupported set variable {}", var_name),
589                    }
590                    .fail();
591                }
592            },
593            "SEARCH_PATH" => {
594                if query_ctx.channel() == Channel::Postgres {
595                    let search_path = set_var.search_path().context(NotSupportedSnafu {
596                        feat: "Unsupported search path in set variable statement",
597                    })?;
598                    query_ctx.set_current_schema(search_path);
599                } else {
600                    return NotSupportedSnafu {
601                        feat: format!("Unsupported set variable {}", var_name),
602                    }
603                    .fail();
604                }
605            }
606            _ => {
607                if query_ctx.channel() == Channel::Postgres || query_ctx.channel() == Channel::Mysql
608                {
609                    // For unknown SET statements, we give a warning with success.
610                    // This prevents the SET call from becoming a blocker of MySQL/Postgres clients'
611                    // connection establishment.
612                    warn!(
613                        "Unsupported set variable {} for channel {:?}",
614                        var_name,
615                        query_ctx.channel()
616                    );
617                    query_ctx.set_warning(format!("Unsupported set variable {}", var_name));
618                } else {
619                    return NotSupportedSnafu {
620                        feat: format!("Unsupported set variable {}", var_name),
621                    }
622                    .fail();
623                }
624            }
625        }
626        Ok(Output::new_with_affected_rows(0))
627    }
628
629    #[tracing::instrument(skip_all)]
630    pub async fn plan(
631        &self,
632        stmt: &QueryStatement,
633        query_ctx: QueryContextRef,
634    ) -> Result<LogicalPlan> {
635        self.query_engine
636            .planner()
637            .plan(stmt, query_ctx)
638            .await
639            .context(PlanStatementSnafu)
640    }
641
642    /// Execute [`LogicalPlan`] directly.
643    #[tracing::instrument(skip_all)]
644    pub async fn exec_plan(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
645        self.query_engine
646            .execute(plan, query_ctx)
647            .await
648            .context(ExecLogicalPlanSnafu)
649    }
650
651    pub fn optimize_logical_plan(&self, plan: LogicalPlan) -> Result<LogicalPlan> {
652        self.query_engine
653            .planner()
654            .optimize(plan)
655            .context(PlanStatementSnafu)
656    }
657
658    #[tracing::instrument(skip_all)]
659    async fn plan_exec(&self, stmt: QueryStatement, query_ctx: QueryContextRef) -> Result<Output> {
660        let plan = self.plan(&stmt, query_ctx.clone()).await?;
661        self.exec_plan(plan, query_ctx).await
662    }
663
664    async fn get_table(&self, table_ref: &TableReference<'_>) -> Result<TableRef> {
665        let TableReference {
666            catalog,
667            schema,
668            table,
669        } = table_ref;
670        self.catalog_manager
671            .table(catalog, schema, table, None)
672            .await
673            .context(CatalogSnafu)?
674            .with_context(|| TableNotFoundSnafu {
675                table_name: table_ref.to_string(),
676            })
677    }
678
679    pub fn procedure_executor(&self) -> &ProcedureExecutorRef {
680        &self.procedure_executor
681    }
682
683    pub fn cache_invalidator(&self) -> &CacheInvalidatorRef {
684        &self.cache_invalidator
685    }
686
687    /// Convert truncate time ranges for the given table from sql values to timestamps
688    ///
689    pub async fn convert_truncate_time_ranges(
690        &self,
691        table_name: &TableName,
692        sql_values_time_range: &[(sqlparser::ast::Value, sqlparser::ast::Value)],
693        query_ctx: &QueryContextRef,
694    ) -> Result<Vec<(Timestamp, Timestamp)>> {
695        if sql_values_time_range.is_empty() {
696            return Ok(vec![]);
697        }
698        let table = self.get_table(&table_name.table_ref()).await?;
699        let info = table.table_info();
700        let time_index_dt = info
701            .meta
702            .schema
703            .timestamp_column()
704            .context(UnexpectedSnafu {
705                violated: "Table must have a timestamp column",
706            })?;
707
708        let time_unit = time_index_dt
709            .data_type
710            .as_timestamp()
711            .with_context(|| UnexpectedSnafu {
712                violated: format!(
713                    "Table {}'s time index column must be a timestamp type, found: {:?}",
714                    table_name, time_index_dt
715                ),
716            })?
717            .unit();
718
719        let start_column = ColumnSchema::new(
720            "range_start",
721            ConcreteDataType::timestamp_datatype(time_unit),
722            false,
723        );
724        let end_column = ColumnSchema::new(
725            "range_end",
726            ConcreteDataType::timestamp_datatype(time_unit),
727            false,
728        );
729        let mut time_ranges = Vec::with_capacity(sql_values_time_range.len());
730        for (start, end) in sql_values_time_range {
731            let start = common_sql::convert::sql_value_to_value(
732                &start_column,
733                start,
734                Some(&query_ctx.timezone()),
735                None,
736                false,
737            )
738            .context(SqlCommonSnafu)
739            .and_then(|v| {
740                if let datatypes::value::Value::Timestamp(t) = v {
741                    Ok(t)
742                } else {
743                    error::InvalidSqlSnafu {
744                        err_msg: format!("Expected a timestamp value, found {v:?}"),
745                    }
746                    .fail()
747                }
748            })?;
749
750            let end = common_sql::convert::sql_value_to_value(
751                &end_column,
752                end,
753                Some(&query_ctx.timezone()),
754                None,
755                false,
756            )
757            .context(SqlCommonSnafu)
758            .and_then(|v| {
759                if let datatypes::value::Value::Timestamp(t) = v {
760                    Ok(t)
761                } else {
762                    error::InvalidSqlSnafu {
763                        err_msg: format!("Expected a timestamp value, found {v:?}"),
764                    }
765                    .fail()
766                }
767            })?;
768            time_ranges.push((start, end));
769        }
770        Ok(time_ranges)
771    }
772
773    /// Returns the inserter for the statement executor.
774    pub(crate) fn inserter(&self) -> &InserterRef {
775        &self.inserter
776    }
777}
778
779fn to_copy_query_request(stmt: CopyQueryToArgument) -> Result<CopyQueryToRequest> {
780    let CopyQueryToArgument {
781        with,
782        connection,
783        location,
784    } = stmt;
785
786    Ok(CopyQueryToRequest {
787        location,
788        with: with.into_map(),
789        connection: connection.into_map(),
790    })
791}
792
793// Verifies time related format is valid
794fn verify_time_related_format(with: &OptionMap) -> Result<()> {
795    let time_format = with.get(common_datasource::file_format::TIME_FORMAT);
796    let date_format = with.get(common_datasource::file_format::DATE_FORMAT);
797    let timestamp_format = with.get(common_datasource::file_format::TIMESTAMP_FORMAT);
798    let file_format = with.get(common_datasource::file_format::FORMAT_TYPE);
799
800    if !matches!(file_format, Some(f) if f.eq_ignore_ascii_case("csv")) {
801        ensure!(
802            time_format.is_none() && date_format.is_none() && timestamp_format.is_none(),
803            error::TimestampFormatNotSupportedSnafu {
804                format: "<unknown>".to_string(),
805                file_format: file_format.unwrap_or_default(),
806            }
807        );
808    }
809
810    for (key, format_opt) in [
811        (common_datasource::file_format::TIME_FORMAT, time_format),
812        (common_datasource::file_format::DATE_FORMAT, date_format),
813        (
814            common_datasource::file_format::TIMESTAMP_FORMAT,
815            timestamp_format,
816        ),
817    ] {
818        if let Some(format) = format_opt {
819            chrono::format::strftime::StrftimeItems::new(format)
820                .parse()
821                .map_err(|_| error::InvalidCopyParameterSnafu { key, value: format }.build())?;
822        }
823    }
824
825    Ok(())
826}
827
828fn to_copy_table_request(stmt: CopyTable, query_ctx: QueryContextRef) -> Result<CopyTableRequest> {
829    let direction = match stmt {
830        CopyTable::To(_) => CopyDirection::Export,
831        CopyTable::From(_) => CopyDirection::Import,
832    };
833
834    let CopyTableArgument {
835        location,
836        connection,
837        with,
838        table_name,
839        limit,
840        ..
841    } = match stmt {
842        CopyTable::To(arg) => arg,
843        CopyTable::From(arg) => arg,
844    };
845    let (catalog_name, schema_name, table_name) =
846        table_idents_to_full_name(&table_name, &query_ctx)
847            .map_err(BoxedError::new)
848            .context(ExternalSnafu)?;
849
850    let timestamp_range = timestamp_range_from_option_map(&with, &query_ctx)?;
851
852    verify_time_related_format(&with)?;
853
854    let pattern = with
855        .get(common_datasource::file_format::FILE_PATTERN)
856        .map(|x| x.to_string());
857
858    Ok(CopyTableRequest {
859        catalog_name,
860        schema_name,
861        table_name,
862        location,
863        with: with.into_map(),
864        connection: connection.into_map(),
865        pattern,
866        direction,
867        timestamp_range,
868        limit,
869    })
870}
871
872/// Converts [CopyDatabaseArgument] to [CopyDatabaseRequest].
873/// This function extracts the necessary info including catalog/database name, time range, etc.
874pub fn to_copy_database_request(
875    arg: CopyDatabaseArgument,
876    query_ctx: &QueryContextRef,
877) -> Result<CopyDatabaseRequest> {
878    let (catalog_name, database_name) = idents_to_full_database_name(&arg.database_name, query_ctx)
879        .map_err(BoxedError::new)
880        .context(ExternalSnafu)?;
881    let time_range = timestamp_range_from_option_map(&arg.with, query_ctx)?;
882
883    Ok(CopyDatabaseRequest {
884        catalog_name,
885        schema_name: database_name,
886        location: arg.location,
887        with: arg.with.into_map(),
888        connection: arg.connection.into_map(),
889        time_range,
890    })
891}
892
893/// Extracts timestamp range from OptionMap with keys `start_time` and `end_time`.
894/// The timestamp ranges should be a valid timestamp string as defined in [Timestamp::from_str].
895/// The timezone used for conversion will respect that inside `query_ctx`.
896fn timestamp_range_from_option_map(
897    options: &OptionMap,
898    query_ctx: &QueryContextRef,
899) -> Result<Option<TimestampRange>> {
900    let start_timestamp = extract_timestamp(options, COPY_DATABASE_TIME_START_KEY, query_ctx)?;
901    let end_timestamp = extract_timestamp(options, COPY_DATABASE_TIME_END_KEY, query_ctx)?;
902    let time_range = match (start_timestamp, end_timestamp) {
903        (Some(start), Some(end)) => Some(TimestampRange::new(start, end).with_context(|| {
904            error::InvalidTimestampRangeSnafu {
905                start: start.to_iso8601_string(),
906                end: end.to_iso8601_string(),
907            }
908        })?),
909        (Some(start), None) => Some(TimestampRange::from_start(start)),
910        (None, Some(end)) => Some(TimestampRange::until_end(end, false)), // exclusive end
911        (None, None) => None,
912    };
913    Ok(time_range)
914}
915
916/// Extracts timestamp from a [HashMap<String, String>] with given key.
917fn extract_timestamp(
918    map: &OptionMap,
919    key: &str,
920    query_ctx: &QueryContextRef,
921) -> Result<Option<Timestamp>> {
922    map.get(key)
923        .map(|v| {
924            Timestamp::from_str(v, Some(&query_ctx.timezone()))
925                .map_err(|_| error::InvalidCopyParameterSnafu { key, value: v }.build())
926        })
927        .transpose()
928}
929
930fn idents_to_full_database_name(
931    obj_name: &ObjectName,
932    query_ctx: &QueryContextRef,
933) -> Result<(String, String)> {
934    match &obj_name.0[..] {
935        [database] => Ok((
936            query_ctx.current_catalog().to_owned(),
937            database.to_string_unquoted(),
938        )),
939        [catalog, database] => Ok((catalog.to_string_unquoted(), database.to_string_unquoted())),
940        _ => InvalidSqlSnafu {
941            err_msg: format!(
942                "expect database name to be <catalog>.<database>, <database>, found: {obj_name}",
943            ),
944        }
945        .fail(),
946    }
947}
948
949/// The [`Inserter`] implementation for the statement executor.
950pub struct InserterImpl {
951    statement_executor: StatementExecutorRef,
952    options: Option<InsertOptions>,
953}
954
955impl InserterImpl {
956    pub fn new(statement_executor: StatementExecutorRef, options: Option<InsertOptions>) -> Self {
957        Self {
958            statement_executor,
959            options,
960        }
961    }
962}
963
964#[async_trait::async_trait]
965impl Inserter for InserterImpl {
966    async fn insert_rows(
967        &self,
968        context: &client::inserter::Context<'_>,
969        requests: RowInsertRequests,
970    ) -> ClientResult<()> {
971        let mut ctx_builder = QueryContextBuilder::default()
972            .current_catalog(context.catalog.to_string())
973            .current_schema(context.schema.to_string());
974        if let Some(options) = self.options.as_ref() {
975            ctx_builder = ctx_builder
976                .set_extension(
977                    TTL_KEY.to_string(),
978                    format_duration(options.ttl).to_string(),
979                )
980                .set_extension(APPEND_MODE_KEY.to_string(), options.append_mode.to_string());
981        }
982        let query_ctx = ctx_builder.build().into();
983
984        self.statement_executor
985            .inserter()
986            .handle_row_inserts(
987                requests,
988                query_ctx,
989                self.statement_executor.as_ref(),
990                false,
991                false,
992            )
993            .await
994            .map_err(BoxedError::new)
995            .context(ClientExternalSnafu)
996            .map(|_| ())
997    }
998
999    fn set_options(&mut self, options: &InsertOptions) {
1000        self.options = Some(*options);
1001    }
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006    use std::assert_matches;
1007    use std::collections::HashMap;
1008
1009    use common_time::range::TimestampRange;
1010    use common_time::{Timestamp, Timezone};
1011    use session::context::QueryContextBuilder;
1012    use sql::statements::OptionMap;
1013
1014    use crate::error;
1015    use crate::statement::copy_database::{
1016        COPY_DATABASE_TIME_END_KEY, COPY_DATABASE_TIME_START_KEY,
1017    };
1018    use crate::statement::{timestamp_range_from_option_map, verify_time_related_format};
1019
1020    fn check_timestamp_range((start, end): (&str, &str)) -> error::Result<Option<TimestampRange>> {
1021        let query_ctx = QueryContextBuilder::default()
1022            .timezone(Timezone::from_tz_string("Asia/Shanghai").unwrap())
1023            .build()
1024            .into();
1025        let map = OptionMap::from(
1026            [
1027                (COPY_DATABASE_TIME_START_KEY.to_string(), start.to_string()),
1028                (COPY_DATABASE_TIME_END_KEY.to_string(), end.to_string()),
1029            ]
1030            .into_iter()
1031            .collect::<HashMap<_, _>>(),
1032        );
1033        timestamp_range_from_option_map(&map, &query_ctx)
1034    }
1035
1036    #[test]
1037    fn test_timestamp_range_from_option_map() {
1038        assert_eq!(
1039            Some(
1040                TimestampRange::new(
1041                    Timestamp::new_second(1649635200),
1042                    Timestamp::new_second(1649664000),
1043                )
1044                .unwrap(),
1045            ),
1046            check_timestamp_range(("2022-04-11 08:00:00", "2022-04-11 16:00:00"),).unwrap()
1047        );
1048
1049        assert_matches!(
1050            check_timestamp_range(("2022-04-11 08:00:00", "2022-04-11 07:00:00")).unwrap_err(),
1051            error::Error::InvalidTimestampRange { .. }
1052        );
1053    }
1054
1055    #[test]
1056    fn test_verify_timestamp_format() {
1057        let map = OptionMap::from(
1058            [
1059                (
1060                    common_datasource::file_format::TIMESTAMP_FORMAT.to_string(),
1061                    "%Y-%m-%d %H:%M:%S".to_string(),
1062                ),
1063                (
1064                    common_datasource::file_format::FORMAT_TYPE.to_string(),
1065                    "csv".to_string(),
1066                ),
1067            ]
1068            .into_iter()
1069            .collect::<HashMap<_, _>>(),
1070        );
1071        assert!(verify_time_related_format(&map).is_ok());
1072
1073        let map = OptionMap::from(
1074            [
1075                (
1076                    common_datasource::file_format::TIMESTAMP_FORMAT.to_string(),
1077                    "%Y-%m-%d %H:%M:%S".to_string(),
1078                ),
1079                (
1080                    common_datasource::file_format::FORMAT_TYPE.to_string(),
1081                    "json".to_string(),
1082                ),
1083            ]
1084            .into_iter()
1085            .collect::<HashMap<_, _>>(),
1086        );
1087
1088        assert_matches!(
1089            verify_time_related_format(&map).unwrap_err(),
1090            error::Error::TimestampFormatNotSupported { .. }
1091        );
1092        let map = OptionMap::from(
1093            [
1094                (
1095                    common_datasource::file_format::TIMESTAMP_FORMAT.to_string(),
1096                    "%111112".to_string(),
1097                ),
1098                (
1099                    common_datasource::file_format::FORMAT_TYPE.to_string(),
1100                    "csv".to_string(),
1101                ),
1102            ]
1103            .into_iter()
1104            .collect::<HashMap<_, _>>(),
1105        );
1106
1107        assert_matches!(
1108            verify_time_related_format(&map).unwrap_err(),
1109            error::Error::InvalidCopyParameter { .. }
1110        );
1111    }
1112}