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 copy_database;
17mod copy_query_to;
18mod copy_table_from;
19mod copy_table_to;
20mod cursor;
21mod ddl;
22mod describe;
23mod dml;
24mod set;
25mod show;
26mod tql;
27
28use std::collections::HashMap;
29use std::pin::Pin;
30use std::sync::Arc;
31use std::time::Duration;
32
33use async_stream::stream;
34use catalog::kvbackend::KvBackendCatalogManager;
35use catalog::CatalogManagerRef;
36use client::{OutputData, RecordBatches};
37use common_error::ext::BoxedError;
38use common_meta::cache::TableRouteCacheRef;
39use common_meta::cache_invalidator::CacheInvalidatorRef;
40use common_meta::ddl::ProcedureExecutorRef;
41use common_meta::key::flow::{FlowMetadataManager, FlowMetadataManagerRef};
42use common_meta::key::schema_name::SchemaNameKey;
43use common_meta::key::view_info::{ViewInfoManager, ViewInfoManagerRef};
44use common_meta::key::{TableMetadataManager, TableMetadataManagerRef};
45use common_meta::kv_backend::KvBackendRef;
46use common_query::Output;
47use common_recordbatch::error::StreamTimeoutSnafu;
48use common_recordbatch::RecordBatchStreamWrapper;
49use common_telemetry::tracing;
50use common_time::range::TimestampRange;
51use common_time::Timestamp;
52use datafusion_expr::LogicalPlan;
53use futures::stream::{Stream, StreamExt};
54use partition::manager::{PartitionRuleManager, PartitionRuleManagerRef};
55use query::parser::QueryStatement;
56use query::QueryEngineRef;
57use session::context::{Channel, QueryContextRef};
58use session::table_name::table_idents_to_full_name;
59use set::{set_query_timeout, set_read_preference};
60use snafu::{ensure, OptionExt, ResultExt};
61use sql::statements::copy::{
62    CopyDatabase, CopyDatabaseArgument, CopyQueryToArgument, CopyTable, CopyTableArgument,
63};
64use sql::statements::set_variables::SetVariables;
65use sql::statements::show::ShowCreateTableVariant;
66use sql::statements::statement::Statement;
67use sql::statements::OptionMap;
68use sql::util::format_raw_object_name;
69use sqlparser::ast::ObjectName;
70use table::requests::{CopyDatabaseRequest, CopyDirection, CopyQueryToRequest, CopyTableRequest};
71use table::table_name::TableName;
72use table::table_reference::TableReference;
73use table::TableRef;
74
75use self::set::{
76    set_bytea_output, set_datestyle, set_search_path, set_timezone, validate_client_encoding,
77};
78use crate::error::{
79    self, CatalogSnafu, ExecLogicalPlanSnafu, ExternalSnafu, InvalidSqlSnafu, NotSupportedSnafu,
80    PlanStatementSnafu, Result, SchemaNotFoundSnafu, StatementTimeoutSnafu,
81    TableMetadataManagerSnafu, TableNotFoundSnafu, UpgradeCatalogManagerRefSnafu,
82};
83use crate::insert::InserterRef;
84use crate::statement::copy_database::{COPY_DATABASE_TIME_END_KEY, COPY_DATABASE_TIME_START_KEY};
85
86#[derive(Clone)]
87pub struct StatementExecutor {
88    catalog_manager: CatalogManagerRef,
89    query_engine: QueryEngineRef,
90    procedure_executor: ProcedureExecutorRef,
91    table_metadata_manager: TableMetadataManagerRef,
92    flow_metadata_manager: FlowMetadataManagerRef,
93    view_info_manager: ViewInfoManagerRef,
94    partition_manager: PartitionRuleManagerRef,
95    cache_invalidator: CacheInvalidatorRef,
96    inserter: InserterRef,
97}
98
99pub type StatementExecutorRef = Arc<StatementExecutor>;
100
101impl StatementExecutor {
102    pub fn new(
103        catalog_manager: CatalogManagerRef,
104        query_engine: QueryEngineRef,
105        procedure_executor: ProcedureExecutorRef,
106        kv_backend: KvBackendRef,
107        cache_invalidator: CacheInvalidatorRef,
108        inserter: InserterRef,
109        table_route_cache: TableRouteCacheRef,
110    ) -> Self {
111        Self {
112            catalog_manager,
113            query_engine,
114            procedure_executor,
115            table_metadata_manager: Arc::new(TableMetadataManager::new(kv_backend.clone())),
116            flow_metadata_manager: Arc::new(FlowMetadataManager::new(kv_backend.clone())),
117            view_info_manager: Arc::new(ViewInfoManager::new(kv_backend.clone())),
118            partition_manager: Arc::new(PartitionRuleManager::new(kv_backend, table_route_cache)),
119            cache_invalidator,
120            inserter,
121        }
122    }
123
124    #[cfg(feature = "testing")]
125    pub async fn execute_stmt(
126        &self,
127        stmt: QueryStatement,
128        query_ctx: QueryContextRef,
129    ) -> Result<Output> {
130        match stmt {
131            QueryStatement::Sql(stmt) => self.execute_sql(stmt, query_ctx).await,
132            QueryStatement::Promql(_) => self.plan_exec(stmt, query_ctx).await,
133        }
134    }
135
136    #[tracing::instrument(skip_all)]
137    pub async fn execute_sql(&self, stmt: Statement, query_ctx: QueryContextRef) -> Result<Output> {
138        match stmt {
139            Statement::Query(_) | Statement::Explain(_) | Statement::Delete(_) => {
140                self.plan_exec(QueryStatement::Sql(stmt), query_ctx).await
141            }
142
143            Statement::DeclareCursor(declare_cursor) => {
144                self.declare_cursor(declare_cursor, query_ctx).await
145            }
146            Statement::FetchCursor(fetch_cursor) => {
147                self.fetch_cursor(fetch_cursor, query_ctx).await
148            }
149            Statement::CloseCursor(close_cursor) => {
150                self.close_cursor(close_cursor, query_ctx).await
151            }
152
153            Statement::Insert(insert) => self.insert(insert, query_ctx).await,
154
155            Statement::Tql(tql) => self.execute_tql(tql, query_ctx).await,
156
157            Statement::DescribeTable(stmt) => self.describe_table(stmt, query_ctx).await,
158
159            Statement::ShowDatabases(stmt) => self.show_databases(stmt, query_ctx).await,
160
161            Statement::ShowTables(stmt) => self.show_tables(stmt, query_ctx).await,
162
163            Statement::ShowTableStatus(stmt) => self.show_table_status(stmt, query_ctx).await,
164
165            Statement::ShowCollation(kind) => self.show_collation(kind, query_ctx).await,
166
167            Statement::ShowCharset(kind) => self.show_charset(kind, query_ctx).await,
168
169            Statement::ShowViews(stmt) => self.show_views(stmt, query_ctx).await,
170
171            Statement::ShowFlows(stmt) => self.show_flows(stmt, query_ctx).await,
172
173            Statement::Copy(sql::statements::copy::Copy::CopyQueryTo(stmt)) => {
174                let query_output = self
175                    .plan_exec(QueryStatement::Sql(*stmt.query), query_ctx)
176                    .await?;
177                let req = to_copy_query_request(stmt.arg)?;
178
179                self.copy_query_to(req, query_output)
180                    .await
181                    .map(Output::new_with_affected_rows)
182            }
183
184            Statement::Copy(sql::statements::copy::Copy::CopyTable(stmt)) => {
185                let req = to_copy_table_request(stmt, query_ctx.clone())?;
186                match req.direction {
187                    CopyDirection::Export => self
188                        .copy_table_to(req, query_ctx)
189                        .await
190                        .map(Output::new_with_affected_rows),
191                    CopyDirection::Import => self.copy_table_from(req, query_ctx).await,
192                }
193            }
194
195            Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy_database)) => {
196                match copy_database {
197                    CopyDatabase::To(arg) => {
198                        self.copy_database_to(
199                            to_copy_database_request(arg, &query_ctx)?,
200                            query_ctx.clone(),
201                        )
202                        .await
203                    }
204                    CopyDatabase::From(arg) => {
205                        self.copy_database_from(
206                            to_copy_database_request(arg, &query_ctx)?,
207                            query_ctx,
208                        )
209                        .await
210                    }
211                }
212            }
213
214            Statement::CreateTable(stmt) => {
215                let _ = self.create_table(stmt, query_ctx).await?;
216                Ok(Output::new_with_affected_rows(0))
217            }
218            Statement::CreateTableLike(stmt) => {
219                let _ = self.create_table_like(stmt, query_ctx).await?;
220                Ok(Output::new_with_affected_rows(0))
221            }
222            Statement::CreateExternalTable(stmt) => {
223                let _ = self.create_external_table(stmt, query_ctx).await?;
224                Ok(Output::new_with_affected_rows(0))
225            }
226            Statement::CreateFlow(stmt) => self.create_flow(stmt, query_ctx).await,
227            Statement::DropFlow(stmt) => {
228                self.drop_flow(
229                    query_ctx.current_catalog().to_string(),
230                    format_raw_object_name(stmt.flow_name()),
231                    stmt.drop_if_exists(),
232                    query_ctx,
233                )
234                .await
235            }
236            Statement::CreateView(stmt) => {
237                let _ = self.create_view(stmt, query_ctx).await?;
238                Ok(Output::new_with_affected_rows(0))
239            }
240            Statement::DropView(stmt) => {
241                let (catalog_name, schema_name, view_name) =
242                    table_idents_to_full_name(&stmt.view_name, &query_ctx)
243                        .map_err(BoxedError::new)
244                        .context(ExternalSnafu)?;
245
246                self.drop_view(
247                    catalog_name,
248                    schema_name,
249                    view_name,
250                    stmt.drop_if_exists,
251                    query_ctx,
252                )
253                .await
254            }
255            Statement::AlterTable(alter_table) => self.alter_table(alter_table, query_ctx).await,
256
257            Statement::AlterDatabase(alter_database) => {
258                self.alter_database(alter_database, query_ctx).await
259            }
260
261            Statement::DropTable(stmt) => {
262                let mut table_names = Vec::with_capacity(stmt.table_names().len());
263                for table_name_stmt in stmt.table_names() {
264                    let (catalog, schema, table) =
265                        table_idents_to_full_name(table_name_stmt, &query_ctx)
266                            .map_err(BoxedError::new)
267                            .context(ExternalSnafu)?;
268                    table_names.push(TableName::new(catalog, schema, table));
269                }
270                self.drop_tables(&table_names[..], stmt.drop_if_exists(), query_ctx.clone())
271                    .await
272            }
273            Statement::DropDatabase(stmt) => {
274                self.drop_database(
275                    query_ctx.current_catalog().to_string(),
276                    format_raw_object_name(stmt.name()),
277                    stmt.drop_if_exists(),
278                    query_ctx,
279                )
280                .await
281            }
282            Statement::TruncateTable(stmt) => {
283                let (catalog, schema, table) =
284                    table_idents_to_full_name(stmt.table_name(), &query_ctx)
285                        .map_err(BoxedError::new)
286                        .context(ExternalSnafu)?;
287                let table_name = TableName::new(catalog, schema, table);
288                self.truncate_table(table_name, query_ctx).await
289            }
290            Statement::CreateDatabase(stmt) => {
291                self.create_database(
292                    &format_raw_object_name(&stmt.name),
293                    stmt.if_not_exists,
294                    stmt.options.into_map(),
295                    query_ctx,
296                )
297                .await
298            }
299            Statement::ShowCreateDatabase(show) => {
300                let (catalog, database) =
301                    idents_to_full_database_name(&show.database_name, &query_ctx)
302                        .map_err(BoxedError::new)
303                        .context(ExternalSnafu)?;
304                let table_metadata_manager = self
305                    .catalog_manager
306                    .as_any()
307                    .downcast_ref::<KvBackendCatalogManager>()
308                    .map(|manager| manager.table_metadata_manager_ref().clone())
309                    .context(UpgradeCatalogManagerRefSnafu)?;
310                let opts: HashMap<String, String> = table_metadata_manager
311                    .schema_manager()
312                    .get(SchemaNameKey::new(&catalog, &database))
313                    .await
314                    .context(TableMetadataManagerSnafu)?
315                    .context(SchemaNotFoundSnafu {
316                        schema_info: &database,
317                    })?
318                    .into_inner()
319                    .into();
320
321                self.show_create_database(&database, opts.into()).await
322            }
323            Statement::ShowCreateTable(show) => {
324                let (catalog, schema, table) =
325                    table_idents_to_full_name(&show.table_name, &query_ctx)
326                        .map_err(BoxedError::new)
327                        .context(ExternalSnafu)?;
328
329                let table_ref = self
330                    .catalog_manager
331                    .table(&catalog, &schema, &table, Some(&query_ctx))
332                    .await
333                    .context(CatalogSnafu)?
334                    .context(TableNotFoundSnafu { table_name: &table })?;
335                let table_name = TableName::new(catalog, schema, table);
336
337                match show.variant {
338                    ShowCreateTableVariant::Original => {
339                        self.show_create_table(table_name, table_ref, query_ctx)
340                            .await
341                    }
342                    ShowCreateTableVariant::PostgresForeignTable => {
343                        self.show_create_table_for_pg(table_name, table_ref, query_ctx)
344                            .await
345                    }
346                }
347            }
348            Statement::ShowCreateFlow(show) => self.show_create_flow(show, query_ctx).await,
349            Statement::ShowCreateView(show) => self.show_create_view(show, query_ctx).await,
350            Statement::SetVariables(set_var) => self.set_variables(set_var, query_ctx),
351            Statement::ShowVariables(show_variable) => self.show_variable(show_variable, query_ctx),
352            Statement::ShowColumns(show_columns) => {
353                self.show_columns(show_columns, query_ctx).await
354            }
355            Statement::ShowIndex(show_index) => self.show_index(show_index, query_ctx).await,
356            Statement::ShowRegion(show_region) => self.show_region(show_region, query_ctx).await,
357            Statement::ShowStatus(_) => self.show_status(query_ctx).await,
358            Statement::ShowSearchPath(_) => self.show_search_path(query_ctx).await,
359            Statement::Use(db) => self.use_database(db, query_ctx).await,
360            Statement::Admin(admin) => self.execute_admin_command(admin, query_ctx).await,
361        }
362    }
363
364    pub async fn use_database(&self, db: String, query_ctx: QueryContextRef) -> Result<Output> {
365        let catalog = query_ctx.current_catalog();
366        ensure!(
367            self.catalog_manager
368                .schema_exists(catalog, db.as_ref(), Some(&query_ctx))
369                .await
370                .context(CatalogSnafu)?,
371            SchemaNotFoundSnafu { schema_info: &db }
372        );
373
374        query_ctx.set_current_schema(&db);
375
376        Ok(Output::new_with_record_batches(RecordBatches::empty()))
377    }
378
379    fn set_variables(&self, set_var: SetVariables, query_ctx: QueryContextRef) -> Result<Output> {
380        let var_name = set_var.variable.to_string().to_uppercase();
381        match var_name.as_str() {
382            "READ_PREFERENCE" => set_read_preference(set_var.value, query_ctx)?,
383
384            "TIMEZONE" | "TIME_ZONE" => set_timezone(set_var.value, query_ctx)?,
385
386            "BYTEA_OUTPUT" => set_bytea_output(set_var.value, query_ctx)?,
387
388            // Same as "bytea_output", we just ignore it here.
389            // Not harmful since it only relates to how date is viewed in client app's output.
390            // The tracked issue is https://github.com/GreptimeTeam/greptimedb/issues/3442.
391            "DATESTYLE" => set_datestyle(set_var.value, query_ctx)?,
392
393            "CLIENT_ENCODING" => validate_client_encoding(set_var)?,
394            "MAX_EXECUTION_TIME" => match query_ctx.channel() {
395                Channel::Mysql => set_query_timeout(set_var.value, query_ctx)?,
396                Channel::Postgres => {
397                    query_ctx.set_warning(format!("Unsupported set variable {}", var_name))
398                }
399                _ => {
400                    return NotSupportedSnafu {
401                        feat: format!("Unsupported set variable {}", var_name),
402                    }
403                    .fail()
404                }
405            },
406            "STATEMENT_TIMEOUT" => {
407                if query_ctx.channel() == Channel::Postgres {
408                    set_query_timeout(set_var.value, query_ctx)?
409                } else {
410                    return NotSupportedSnafu {
411                        feat: format!("Unsupported set variable {}", var_name),
412                    }
413                    .fail();
414                }
415            }
416            "SEARCH_PATH" => {
417                if query_ctx.channel() == Channel::Postgres {
418                    set_search_path(set_var.value, query_ctx)?
419                } else {
420                    return NotSupportedSnafu {
421                        feat: format!("Unsupported set variable {}", var_name),
422                    }
423                    .fail();
424                }
425            }
426            _ => {
427                // for postgres, we give unknown SET statements a warning with
428                //  success, this is prevent the SET call becoming a blocker
429                //  of connection establishment
430                //
431                if query_ctx.channel() == Channel::Postgres {
432                    query_ctx.set_warning(format!("Unsupported set variable {}", var_name));
433                } else {
434                    return NotSupportedSnafu {
435                        feat: format!("Unsupported set variable {}", var_name),
436                    }
437                    .fail();
438                }
439            }
440        }
441        Ok(Output::new_with_affected_rows(0))
442    }
443
444    #[tracing::instrument(skip_all)]
445    pub async fn plan(
446        &self,
447        stmt: &QueryStatement,
448        query_ctx: QueryContextRef,
449    ) -> Result<LogicalPlan> {
450        self.query_engine
451            .planner()
452            .plan(stmt, query_ctx)
453            .await
454            .context(PlanStatementSnafu)
455    }
456
457    /// Execute [`LogicalPlan`] directly.
458    #[tracing::instrument(skip_all)]
459    pub async fn exec_plan(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
460        self.query_engine
461            .execute(plan, query_ctx)
462            .await
463            .context(ExecLogicalPlanSnafu)
464    }
465
466    pub fn optimize_logical_plan(&self, plan: LogicalPlan) -> Result<LogicalPlan> {
467        self.query_engine
468            .planner()
469            .optimize(plan)
470            .context(PlanStatementSnafu)
471    }
472
473    #[tracing::instrument(skip_all)]
474    async fn plan_exec(&self, stmt: QueryStatement, query_ctx: QueryContextRef) -> Result<Output> {
475        let timeout = derive_timeout(&stmt, &query_ctx);
476        match timeout {
477            Some(timeout) => {
478                let start = tokio::time::Instant::now();
479                let output = tokio::time::timeout(timeout, self.plan_exec_inner(stmt, query_ctx))
480                    .await
481                    .context(StatementTimeoutSnafu)?;
482                // compute remaining timeout
483                let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default();
484                Ok(attach_timeout(output?, remaining_timeout))
485            }
486            None => self.plan_exec_inner(stmt, query_ctx).await,
487        }
488    }
489
490    async fn get_table(&self, table_ref: &TableReference<'_>) -> Result<TableRef> {
491        let TableReference {
492            catalog,
493            schema,
494            table,
495        } = table_ref;
496        self.catalog_manager
497            .table(catalog, schema, table, None)
498            .await
499            .context(CatalogSnafu)?
500            .with_context(|| TableNotFoundSnafu {
501                table_name: table_ref.to_string(),
502            })
503    }
504
505    async fn plan_exec_inner(
506        &self,
507        stmt: QueryStatement,
508        query_ctx: QueryContextRef,
509    ) -> Result<Output> {
510        let plan = self.plan(&stmt, query_ctx.clone()).await?;
511        self.exec_plan(plan, query_ctx).await
512    }
513}
514
515fn attach_timeout(output: Output, mut timeout: Duration) -> Output {
516    match output.data {
517        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
518        OutputData::Stream(mut stream) => {
519            let schema = stream.schema();
520            let s = Box::pin(stream! {
521                let start = tokio::time::Instant::now();
522                while let Some(item) = tokio::time::timeout(timeout, stream.next()).await.context(StreamTimeoutSnafu)? {
523                    yield item;
524                    timeout = timeout.checked_sub(tokio::time::Instant::now() - start).unwrap_or(Duration::ZERO);
525                }
526            }) as Pin<Box<dyn Stream<Item = _> + Send>>;
527            let stream = RecordBatchStreamWrapper {
528                schema,
529                stream: s,
530                output_ordering: None,
531                metrics: Default::default(),
532            };
533            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
534        }
535    }
536}
537
538/// If the relevant variables are set, the timeout is enforced for all PostgreSQL statements.
539/// For MySQL, it applies only to read-only statements.
540fn derive_timeout(stmt: &QueryStatement, query_ctx: &QueryContextRef) -> Option<Duration> {
541    let query_timeout = query_ctx.query_timeout()?;
542    match (query_ctx.channel(), stmt) {
543        (Channel::Mysql, QueryStatement::Sql(Statement::Query(_)))
544        | (Channel::Postgres, QueryStatement::Sql(_)) => Some(query_timeout),
545        (_, _) => None,
546    }
547}
548
549fn to_copy_query_request(stmt: CopyQueryToArgument) -> Result<CopyQueryToRequest> {
550    let CopyQueryToArgument {
551        with,
552        connection,
553        location,
554    } = stmt;
555
556    Ok(CopyQueryToRequest {
557        location,
558        with: with.into_map(),
559        connection: connection.into_map(),
560    })
561}
562
563fn to_copy_table_request(stmt: CopyTable, query_ctx: QueryContextRef) -> Result<CopyTableRequest> {
564    let direction = match stmt {
565        CopyTable::To(_) => CopyDirection::Export,
566        CopyTable::From(_) => CopyDirection::Import,
567    };
568
569    let CopyTableArgument {
570        location,
571        connection,
572        with,
573        table_name,
574        limit,
575        ..
576    } = match stmt {
577        CopyTable::To(arg) => arg,
578        CopyTable::From(arg) => arg,
579    };
580    let (catalog_name, schema_name, table_name) =
581        table_idents_to_full_name(&table_name, &query_ctx)
582            .map_err(BoxedError::new)
583            .context(ExternalSnafu)?;
584
585    let timestamp_range = timestamp_range_from_option_map(&with, &query_ctx)?;
586
587    let pattern = with
588        .get(common_datasource::file_format::FILE_PATTERN)
589        .cloned();
590
591    Ok(CopyTableRequest {
592        catalog_name,
593        schema_name,
594        table_name,
595        location,
596        with: with.into_map(),
597        connection: connection.into_map(),
598        pattern,
599        direction,
600        timestamp_range,
601        limit,
602    })
603}
604
605/// Converts [CopyDatabaseArgument] to [CopyDatabaseRequest].
606/// This function extracts the necessary info including catalog/database name, time range, etc.
607fn to_copy_database_request(
608    arg: CopyDatabaseArgument,
609    query_ctx: &QueryContextRef,
610) -> Result<CopyDatabaseRequest> {
611    let (catalog_name, database_name) = idents_to_full_database_name(&arg.database_name, query_ctx)
612        .map_err(BoxedError::new)
613        .context(ExternalSnafu)?;
614    let time_range = timestamp_range_from_option_map(&arg.with, query_ctx)?;
615
616    Ok(CopyDatabaseRequest {
617        catalog_name,
618        schema_name: database_name,
619        location: arg.location,
620        with: arg.with.into_map(),
621        connection: arg.connection.into_map(),
622        time_range,
623    })
624}
625
626/// Extracts timestamp range from OptionMap with keys `start_time` and `end_time`.
627/// The timestamp ranges should be a valid timestamp string as defined in [Timestamp::from_str].
628/// The timezone used for conversion will respect that inside `query_ctx`.
629fn timestamp_range_from_option_map(
630    options: &OptionMap,
631    query_ctx: &QueryContextRef,
632) -> Result<Option<TimestampRange>> {
633    let start_timestamp = extract_timestamp(options, COPY_DATABASE_TIME_START_KEY, query_ctx)?;
634    let end_timestamp = extract_timestamp(options, COPY_DATABASE_TIME_END_KEY, query_ctx)?;
635    let time_range = match (start_timestamp, end_timestamp) {
636        (Some(start), Some(end)) => Some(TimestampRange::new(start, end).with_context(|| {
637            error::InvalidTimestampRangeSnafu {
638                start: start.to_iso8601_string(),
639                end: end.to_iso8601_string(),
640            }
641        })?),
642        (Some(start), None) => Some(TimestampRange::from_start(start)),
643        (None, Some(end)) => Some(TimestampRange::until_end(end, false)), // exclusive end
644        (None, None) => None,
645    };
646    Ok(time_range)
647}
648
649/// Extracts timestamp from a [HashMap<String, String>] with given key.
650fn extract_timestamp(
651    map: &OptionMap,
652    key: &str,
653    query_ctx: &QueryContextRef,
654) -> Result<Option<Timestamp>> {
655    map.get(key)
656        .map(|v| {
657            Timestamp::from_str(v, Some(&query_ctx.timezone()))
658                .map_err(|_| error::InvalidCopyParameterSnafu { key, value: v }.build())
659        })
660        .transpose()
661}
662
663fn idents_to_full_database_name(
664    obj_name: &ObjectName,
665    query_ctx: &QueryContextRef,
666) -> Result<(String, String)> {
667    match &obj_name.0[..] {
668        [database] => Ok((
669            query_ctx.current_catalog().to_owned(),
670            database.value.clone(),
671        )),
672        [catalog, database] => Ok((catalog.value.clone(), database.value.clone())),
673        _ => InvalidSqlSnafu {
674            err_msg: format!(
675                "expect database name to be <catalog>.<database>, <database>, found: {obj_name}",
676            ),
677        }
678        .fail(),
679    }
680}
681
682#[cfg(test)]
683mod tests {
684    use std::assert_matches::assert_matches;
685    use std::collections::HashMap;
686
687    use common_time::range::TimestampRange;
688    use common_time::{Timestamp, Timezone};
689    use session::context::QueryContextBuilder;
690    use sql::statements::OptionMap;
691
692    use crate::error;
693    use crate::statement::copy_database::{
694        COPY_DATABASE_TIME_END_KEY, COPY_DATABASE_TIME_START_KEY,
695    };
696    use crate::statement::timestamp_range_from_option_map;
697
698    fn check_timestamp_range((start, end): (&str, &str)) -> error::Result<Option<TimestampRange>> {
699        let query_ctx = QueryContextBuilder::default()
700            .timezone(Timezone::from_tz_string("Asia/Shanghai").unwrap())
701            .build()
702            .into();
703        let map = OptionMap::from(
704            [
705                (COPY_DATABASE_TIME_START_KEY.to_string(), start.to_string()),
706                (COPY_DATABASE_TIME_END_KEY.to_string(), end.to_string()),
707            ]
708            .into_iter()
709            .collect::<HashMap<_, _>>(),
710        );
711        timestamp_range_from_option_map(&map, &query_ctx)
712    }
713
714    #[test]
715    fn test_timestamp_range_from_option_map() {
716        assert_eq!(
717            Some(
718                TimestampRange::new(
719                    Timestamp::new_second(1649635200),
720                    Timestamp::new_second(1649664000),
721                )
722                .unwrap(),
723            ),
724            check_timestamp_range(("2022-04-11 08:00:00", "2022-04-11 16:00:00"),).unwrap()
725        );
726
727        assert_matches!(
728            check_timestamp_range(("2022-04-11 08:00:00", "2022-04-11 07:00:00")).unwrap_err(),
729            error::Error::InvalidTimestampRange { .. }
730        );
731    }
732}