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