Skip to main content

frontend/instance/
copy_in.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 api::v1::RowInsertRequests;
16use async_trait::async_trait;
17use auth::{
18    PermissionChecker, PermissionCheckerRef, PermissionReq, PermissionTableTarget,
19    PermissionTableTargets,
20};
21use common_error::ext::BoxedError;
22use common_query::Output;
23use query::query_engine::options::{QueryOptions, validate_catalog_and_schema};
24use servers::error::{AuthSnafu, ExecuteGrpcRequestSnafu, ExecuteQuerySnafu, Result};
25use servers::query_handler::CopyInHandler;
26use session::context::QueryContextRef;
27use snafu::ResultExt;
28use table::metadata::TableInfoRef;
29
30use crate::instance::Instance;
31
32impl Instance {
33    /// Whether cross-catalog access is disabled for this instance —
34    /// mirrors SQL INSERT's catalog restriction (see `check_permission`).
35    fn cross_catalog_restricted(&self) -> bool {
36        self.plugins
37            .get::<QueryOptions>()
38            .map(|opts| opts.disallow_cross_catalog_query)
39            .unwrap_or_default()
40    }
41}
42
43#[async_trait]
44impl CopyInHandler for Instance {
45    async fn copy_in_validate_scope(
46        &self,
47        catalog: &str,
48        schema: &str,
49        query_ctx: QueryContextRef,
50    ) -> Result<()> {
51        // Runs against the ORIGINAL session context — callers switch the
52        // context to the target scope afterwards, so nothing downstream
53        // would catch it.
54        if self.cross_catalog_restricted() {
55            validate_catalog_and_schema(catalog, schema, &query_ctx)
56                .map_err(BoxedError::new)
57                .context(ExecuteQuerySnafu)?;
58        }
59        Ok(())
60    }
61
62    async fn copy_in_table(
63        &self,
64        catalog: &str,
65        schema: &str,
66        table: &str,
67        query_ctx: QueryContextRef,
68    ) -> Result<Option<TableInfoRef>> {
69        // Mirror SQL INSERT's catalog restriction (see `check_permission`):
70        // when cross-catalog queries are disallowed, a COPY may only
71        // target the current catalog. This must run against the ORIGINAL
72        // query context — `begin_copy_in` switches the context to the
73        // target catalog afterwards, so nothing downstream would catch
74        // it.
75        if self.cross_catalog_restricted() {
76            validate_catalog_and_schema(catalog, schema, &query_ctx)
77                .map_err(BoxedError::new)
78                .context(ExecuteQuerySnafu)?;
79        }
80
81        // A COPY writes rows like a SQL INSERT; check the write permission
82        // before the client starts streaming data.
83        self.plugins
84            .get::<PermissionCheckerRef>()
85            .as_ref()
86            .check_permission(
87                query_ctx.current_user(),
88                PermissionReq::BulkInsert {
89                    catalog,
90                    schema,
91                    table,
92                },
93            )
94            .context(AuthSnafu)?;
95
96        let table_info = self
97            .catalog_manager()
98            .table(catalog, schema, table, None)
99            .await
100            .map(|table| table.map(|table| table.table_info()))
101            .map_err(servers::error::Error::from)?;
102        let target = PermissionTableTarget::new(catalog, schema, table).with_physical_metric_table(
103            table_info
104                .as_ref()
105                .is_some_and(|info| info.is_physical_table()),
106        );
107        self.check_table_permission(
108            &query_ctx,
109            PermissionReq::BulkInsert {
110                catalog,
111                schema,
112                table,
113            },
114            PermissionTableTargets::resolved(vec![target]),
115        )
116        .context(AuthSnafu)?;
117        Ok(table_info)
118    }
119
120    fn copy_in_arrow(
121        &self,
122        stream: servers::grpc::flight::PutRecordBatchRequestStream,
123        query_ctx: QueryContextRef,
124    ) -> Result<
125        futures::stream::BoxStream<'static, Result<common_grpc::flight::do_put::DoPutResponse>>,
126    > {
127        Ok(
128            servers::query_handler::grpc::GrpcQueryHandler::handle_put_record_batch_stream(
129                self, stream, query_ctx,
130            ),
131        )
132    }
133
134    async fn copy_in_insert(
135        &self,
136        requests: RowInsertRequests,
137        query_ctx: QueryContextRef,
138    ) -> Result<Output> {
139        self.handle_row_inserts(requests, query_ctx, false, false)
140            .await
141            .map_err(BoxedError::new)
142            .context(ExecuteGrpcRequestSnafu)
143    }
144}