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