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