Skip to main content

frontend/instance/
export_database.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
15use auth::{
16    PermissionAction, PermissionChecker, PermissionCheckerRef, PermissionReq,
17    PermissionTableTarget, PermissionTableTargets,
18};
19use operator::statement::export_database::{DatabaseExportSummary, PreparedDatabaseExport};
20use session::context::QueryContextRef;
21use snafu::ResultExt;
22use sql::ast::{Ident, ObjectName};
23use sql::statements::copy::{Copy, CopyDatabase, CopyDatabaseArgument};
24use sql::statements::statement::Statement;
25use table::requests::CopyDatabaseRequest;
26use tokio_util::sync::CancellationToken;
27
28use crate::error::{PermissionSnafu, Result};
29use crate::instance::Instance;
30
31impl Instance {
32    #[allow(dead_code)]
33    async fn export_database(
34        &self,
35        req: CopyDatabaseRequest,
36        names: Option<&[String]>,
37        cancellation: &CancellationToken,
38        ctx: QueryContextRef,
39    ) -> Result<DatabaseExportSummary> {
40        if cancellation.is_cancelled() {
41            return Err(operator::error::DatabaseExportCancelledSnafu.build().into());
42        }
43        let plan = self.prepare_database_export(req, names, &ctx).await?;
44        Ok(self
45            .statement_executor
46            .export_database(plan, cancellation, ctx)
47            .await?)
48    }
49
50    /// Exercise the internal authenticated entry without exposing SQL/CLI activation.
51    #[cfg(any(test, feature = "testing"))]
52    pub async fn export_database_for_test(
53        &self,
54        req: CopyDatabaseRequest,
55        names: Option<&[String]>,
56        cancellation: &CancellationToken,
57        ctx: QueryContextRef,
58    ) -> Result<DatabaseExportSummary> {
59        self.export_database(req, names, cancellation, ctx).await
60    }
61
62    async fn prepare_database_export(
63        &self,
64        req: CopyDatabaseRequest,
65        names: Option<&[String]>,
66        ctx: &QueryContextRef,
67    ) -> Result<PreparedDatabaseExport> {
68        let stmt = Statement::Copy(Copy::CopyDatabase(CopyDatabase::To(CopyDatabaseArgument {
69            database_name: ObjectName::from(vec![
70                Ident::new(&req.catalog_name),
71                Ident::new(&req.schema_name),
72            ]),
73            with: req.with.clone().into(),
74            connection: req.connection.clone().into(),
75            location: req.location.clone(),
76        })));
77        self.plugins
78            .get::<PermissionCheckerRef>()
79            .as_ref()
80            .check_permission_with_context(
81                ctx.current_user(),
82                PermissionReq::SqlStatement(&stmt),
83                Some(&ctx.current_schema()),
84            )
85            .context(PermissionSnafu)?;
86        let tables = self
87            .statement_executor
88            .capture_database_export_tables(&req, names, ctx)
89            .await?;
90        let targets = PermissionTableTargets::resolved(
91            tables
92                .iter()
93                .map(|table| {
94                    let info = table.table_info();
95                    PermissionTableTarget::new(&info.catalog_name, &info.schema_name, &info.name)
96                })
97                .collect(),
98        );
99        self.check_table_permission(ctx, PermissionReq::SqlStatement(&stmt), targets.clone())
100            .context(PermissionSnafu)?;
101        // COPY is classified as a write by existing permission checkers.
102        self.check_table_permission(
103            ctx,
104            PermissionReq::Action(PermissionAction::read("database.export")),
105            targets,
106        )
107        .context(PermissionSnafu)?;
108        Ok(self
109            .statement_executor
110            .prepare_database_export(req, tables)
111            .await?)
112    }
113}