Skip to main content

operator/statement/
copy_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 std::str::FromStr;
16use std::sync::Arc;
17
18use client::{Output, OutputData, OutputMeta};
19use common_catalog::format_full_table_name;
20use common_datasource::file_format::Format;
21use common_datasource::lister::{Lister, Source};
22use common_datasource::object_store::{
23    LocalFileAccess, RemoteStorageAccess, build_backend, build_backend_for_write,
24};
25use common_telemetry::{debug, error, info, tracing};
26use futures::future::try_join_all;
27use object_store::Entry;
28use regex::Regex;
29use session::context::QueryContextRef;
30use snafu::ResultExt;
31use table::TableRef;
32use table::requests::{CopyDatabaseRequest, CopyDirection, CopyTableRequest};
33use tokio::sync::Semaphore;
34
35use crate::error;
36use crate::statement::StatementExecutor;
37use crate::statement::database_copy::{
38    database_import_source, parse_parallelism_from_option_map, prepare_database_export_files,
39    validate_database_directory, validate_database_export_layout,
40};
41
42pub(crate) const COPY_DATABASE_TIME_START_KEY: &str = "start_time";
43pub(crate) const COPY_DATABASE_TIME_END_KEY: &str = "end_time";
44pub(crate) const CONTINUE_ON_ERROR_KEY: &str = "continue_on_error";
45
46impl StatementExecutor {
47    #[tracing::instrument(skip_all)]
48    pub(crate) async fn copy_database_to(
49        &self,
50        req: CopyDatabaseRequest,
51        ctx: QueryContextRef,
52    ) -> error::Result<Output> {
53        let tables = self
54            .capture_database_export_tables(&req, None, &ctx)
55            .await?;
56        self.copy_database_to_tables(req, tables, ctx).await
57    }
58
59    /// Exports the captured tables without enumerating the database again.
60    pub async fn copy_database_to_tables(
61        &self,
62        req: CopyDatabaseRequest,
63        tables: Vec<TableRef>,
64        ctx: QueryContextRef,
65    ) -> error::Result<Output> {
66        validate_database_export_layout(&req.with)?;
67        validate_database_directory(&req.location)?;
68        let parallelism = parse_parallelism_from_option_map(&req.with);
69        info!(
70            "Copy database {}.{} to dir: {}, time: {:?}, parallelism: {}",
71            req.catalog_name, req.schema_name, req.location, req.time_range, parallelism
72        );
73        let num_tables = tables.len();
74
75        let suffix = Format::try_from(&req.with)
76            .context(error::ParseFileFormatSnafu)?
77            .suffix();
78
79        let outputs = prepare_database_export_files(
80            &req.location,
81            tables.iter().map(|table| table.table_info().name.clone()),
82            suffix,
83            false,
84        )?;
85        build_backend_for_write(
86            &req.location,
87            &req.connection,
88            &self.local_file_access,
89            &self.remote_storage_access,
90        )
91        .await
92        .context(error::BuildBackendSnafu)?;
93
94        let mut tasks = Vec::with_capacity(num_tables);
95        let semaphore = Arc::new(Semaphore::new(parallelism));
96
97        for (i, (table, output)) in tables.into_iter().zip(outputs).enumerate() {
98            let table_name = table.table_info().name.clone();
99            let semaphore_moved = semaphore.clone();
100            let table_file = output.location;
101            let table_no = i + 1;
102            let moved_ctx = ctx.clone();
103            let full_table_name =
104                format_full_table_name(&req.catalog_name, &req.schema_name, &table_name);
105            let copy_table_req = CopyTableRequest {
106                catalog_name: req.catalog_name.clone(),
107                schema_name: req.schema_name.clone(),
108                table_name,
109                location: table_file.clone(),
110                with: req.with.clone(),
111                connection: req.connection.clone(),
112                pattern: None,
113                direction: CopyDirection::Export,
114                timestamp_range: req.time_range,
115                limit: None,
116            };
117
118            tasks.push(async move {
119                let _permit = semaphore_moved.acquire().await.unwrap();
120                info!(
121                    "Copy table({}/{}): {} to {}",
122                    table_no, num_tables, full_table_name, table_file
123                );
124                self.copy_captured_table_to(table, copy_table_req, moved_ctx)
125                    .await
126            });
127        }
128
129        let results = try_join_all(tasks).await?;
130        let exported_rows = results.into_iter().sum();
131        Ok(Output::new_with_affected_rows(exported_rows))
132    }
133
134    /// Imports data to database from a given location and returns total rows imported.
135    #[tracing::instrument(skip_all)]
136    pub(crate) async fn copy_database_from(
137        &self,
138        req: CopyDatabaseRequest,
139        ctx: QueryContextRef,
140    ) -> error::Result<Output> {
141        let requests = self.prepare_database_import(&req).await?;
142        self.copy_database_from_requests(req, requests, ctx).await
143    }
144
145    /// Lists and resolves all destination tables before importing any rows.
146    pub async fn prepare_database_import(
147        &self,
148        req: &CopyDatabaseRequest,
149    ) -> error::Result<Vec<CopyTableRequest>> {
150        if let Some(layout) = req.with.get("metric_data_layout") {
151            return error::InvalidCopyParameterSnafu {
152                key: "metric_data_layout",
153                value: layout,
154            }
155            .fail();
156        }
157        validate_database_directory(&req.location)?;
158
159        let suffix = Format::try_from(&req.with)
160            .context(error::ParseFileFormatSnafu)?
161            .suffix();
162
163        let entries = list_files_to_copy(
164            req,
165            suffix,
166            &self.local_file_access,
167            &self.remote_storage_access,
168        )
169        .await?;
170
171        let continue_on_error = req
172            .with
173            .get(CONTINUE_ON_ERROR_KEY)
174            .and_then(|v| bool::from_str(v).ok())
175            .unwrap_or(false);
176
177        let mut requests = Vec::with_capacity(entries.len());
178
179        for e in entries {
180            let (table_name, location) = match database_import_source(&req.location, e.path()) {
181                Ok(source) => source,
182                Err(err) => {
183                    if continue_on_error {
184                        error!(err; "Failed to import table from file: {:?}", e);
185                        continue;
186                    } else {
187                        return Err(err);
188                    }
189                }
190            };
191
192            requests.push(CopyTableRequest {
193                catalog_name: req.catalog_name.clone(),
194                schema_name: req.schema_name.clone(),
195                table_name,
196                location,
197                with: req.with.clone(),
198                connection: req.connection.clone(),
199                pattern: None,
200                direction: CopyDirection::Import,
201                timestamp_range: None,
202                limit: None,
203            });
204        }
205        Ok(requests)
206    }
207
208    /// Imports the prepared file requests without listing the source again.
209    pub async fn copy_database_from_requests(
210        &self,
211        req: CopyDatabaseRequest,
212        requests: Vec<CopyTableRequest>,
213        ctx: QueryContextRef,
214    ) -> error::Result<Output> {
215        let parallelism = parse_parallelism_from_option_map(&req.with);
216        info!(
217            "Copy database {}.{} from dir: {}, time: {:?}, parallelism: {}",
218            req.catalog_name, req.schema_name, req.location, req.time_range, parallelism
219        );
220        let continue_on_error = req
221            .with
222            .get(CONTINUE_ON_ERROR_KEY)
223            .and_then(|v| bool::from_str(v).ok())
224            .unwrap_or(false);
225        let mut tasks = Vec::with_capacity(requests.len());
226        let semaphore = Arc::new(Semaphore::new(parallelism));
227        for req in requests {
228            let moved_ctx = ctx.clone();
229            let moved_table_name = req.table_name.clone();
230            let moved_semaphore = semaphore.clone();
231            tasks.push(async move {
232                let _permit = moved_semaphore.acquire().await.unwrap();
233                debug!("Copy table, arg: {:?}", req);
234                match self.copy_table_from(req, moved_ctx).await {
235                    Ok(o) => {
236                        let (rows, cost) = o.extract_rows_and_cost();
237                        Ok((rows, cost))
238                    }
239                    Err(err) => {
240                        if continue_on_error {
241                            error!(err; "Failed to import file to table: {}", moved_table_name);
242                            Ok((0, 0))
243                        } else {
244                            Err(err)
245                        }
246                    }
247                }
248            });
249        }
250
251        let results = try_join_all(tasks).await?;
252        let (rows_inserted, insert_cost) = results
253            .into_iter()
254            .fold((0, 0), |(acc_rows, acc_cost), (rows, cost)| {
255                (acc_rows + rows, acc_cost + cost)
256            });
257
258        Ok(Output::new(
259            OutputData::AffectedRows(rows_inserted),
260            OutputMeta::new_with_cost(insert_cost),
261        ))
262    }
263}
264
265/// Lists all files with expected suffix that can be imported to database.
266async fn list_files_to_copy(
267    req: &CopyDatabaseRequest,
268    suffix: &str,
269    local_file_access: &LocalFileAccess,
270    remote_storage_access: &RemoteStorageAccess,
271) -> error::Result<Vec<Entry>> {
272    let object_store = build_backend(
273        &req.location,
274        &req.connection,
275        local_file_access,
276        remote_storage_access,
277    )
278    .await
279    .context(error::BuildBackendSnafu)?;
280
281    let pattern = Regex::try_from(format!(".*{}", suffix)).context(error::BuildRegexSnafu)?;
282    let lister = Lister::new(
283        object_store.clone(),
284        Source::Dir,
285        "/".to_string(),
286        Some(pattern),
287    );
288    lister.list().await.context(error::ListObjectsSnafu)
289}
290
291#[cfg(test)]
292mod tests {
293    use std::collections::HashSet;
294
295    use common_datasource::object_store::{LocalFileAccess, RemoteStorageAccess};
296    use object_store::ObjectStore;
297    use object_store::services::Fs;
298    use object_store::util::normalize_dir;
299    #[cfg(not(windows))]
300    use path_slash::PathExt;
301    use table::requests::CopyDatabaseRequest;
302
303    use crate::statement::copy_database::list_files_to_copy;
304    use crate::statement::database_copy::database_import_source;
305
306    #[tokio::test]
307    async fn test_list_files_and_parse_table_name() {
308        let dir = common_test_util::temp_dir::create_temp_dir("test_list_files_to_copy");
309        let store_dir = normalize_dir(dir.path().to_str().unwrap());
310        let builder = Fs::default().root(&store_dir);
311        let object_store = ObjectStore::new(builder).unwrap();
312        object_store.write("a.parquet", "").await.unwrap();
313        object_store.write("b.parquet", "").await.unwrap();
314        object_store.write("c.csv", "").await.unwrap();
315        object_store.write("d", "").await.unwrap();
316        object_store.write("e.f.parquet", "").await.unwrap();
317
318        #[cfg(not(windows))]
319        let location = normalize_dir(&dir.path().to_slash().unwrap());
320        #[cfg(windows)]
321        let location = format!("{}\\", dir.path().display());
322        let request = CopyDatabaseRequest {
323            catalog_name: "catalog_0".to_string(),
324            schema_name: "schema_0".to_string(),
325            location,
326            with: [("FORMAT".to_string(), "parquet".to_string())]
327                .into_iter()
328                .collect(),
329            connection: Default::default(),
330            time_range: None,
331        };
332        let local_file_access = LocalFileAccess::sandboxed(dir.path()).unwrap();
333        let listed = list_files_to_copy(
334            &request,
335            ".parquet",
336            &local_file_access,
337            &RemoteStorageAccess::unrestricted(),
338        )
339        .await
340        .unwrap()
341        .into_iter()
342        .map(|e| {
343            database_import_source(&request.location, e.path())
344                .unwrap()
345                .0
346        })
347        .collect::<HashSet<_>>();
348
349        assert_eq!(
350            ["a".to_string(), "b".to_string(), "e.f".to_string()]
351                .into_iter()
352                .collect::<HashSet<_>>(),
353            listed
354        );
355    }
356}