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