Skip to main content

operator/statement/
database_copy.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
15//! Shared selection and destination rules for database COPY and prepared exports.
16
17use std::collections::HashMap;
18
19use common_datasource::object_store::{FILE_SCHEMA, FS_SCHEMA, parse_url};
20use common_stat::get_total_cpu_cores;
21use session::context::QueryContextRef;
22use snafu::{OptionExt, ResultExt, ensure};
23use store_api::metric_engine_consts::{LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME};
24use table::TableRef;
25use table::metadata::TableType;
26use table::requests::CopyDatabaseRequest;
27use table::table_reference::TableReference;
28use tokio::sync::Semaphore;
29use url::Url;
30
31use crate::error::{self, Result};
32use crate::statement::StatementExecutor;
33
34fn is_directory_location(location: &str) -> bool {
35    if location.ends_with('/') {
36        return true;
37    }
38
39    #[cfg(windows)]
40    {
41        location.ends_with(std::path::MAIN_SEPARATOR)
42            && matches!(
43                parse_url(location),
44                Ok((schema, _, _)) if schema.eq_ignore_ascii_case(FS_SCHEMA)
45            )
46    }
47
48    #[cfg(not(windows))]
49    false
50}
51
52/// Get parallelism from options, default to total CPU cores.
53pub(crate) fn parse_parallelism_from_option_map(options: &HashMap<String, String>) -> usize {
54    options
55        .get("parallelism")
56        .and_then(|v| v.parse::<usize>().ok())
57        .unwrap_or_else(get_total_cpu_cores)
58        .clamp(1, Semaphore::MAX_PERMITS)
59}
60
61/// Rejects layouts unsupported by the per-table export path.
62pub(crate) fn validate_database_export_layout(options: &HashMap<String, String>) -> Result<()> {
63    if let Some(layout) = options.get("metric_data_layout") {
64        return error::InvalidCopyParameterSnafu {
65            key: "metric_data_layout",
66            value: layout,
67        }
68        .fail();
69    }
70    Ok(())
71}
72
73pub(crate) fn validate_database_directory(location: &str) -> Result<()> {
74    ensure!(
75        is_directory_location(location),
76        error::InvalidCopyDatabasePathSnafu { value: location }
77    );
78    #[cfg(windows)]
79    if common_datasource::object_store::handle_windows_path(location).is_some() {
80        return Ok(());
81    }
82    let parsed_directory = match Url::parse(location) {
83        Ok(url) => {
84            url.query().is_none() && url.fragment().is_none() && is_directory_location(url.path())
85        }
86        Err(_) => true,
87    };
88    ensure!(
89        parsed_directory,
90        error::InvalidCopyDatabasePathSnafu { value: location }
91    );
92    Ok(())
93}
94
95/// The writer key and its externally reported location, resolved together.
96pub(crate) struct DatabaseExportFile {
97    pub(crate) path: String,
98    pub(crate) location: String,
99}
100
101impl DatabaseExportFile {
102    pub(crate) fn new(directory: &str, name: &str, suffix: &str) -> Result<Self> {
103        let filename = format!("{name}{suffix}");
104        #[cfg(windows)]
105        if common_datasource::object_store::handle_windows_path(directory).is_some() {
106            return Ok(Self {
107                location: format!("{directory}{filename}"),
108                path: filename,
109            });
110        }
111        match Url::parse(directory) {
112            Ok(mut url) => {
113                url.path_segments_mut()
114                    .map_err(|_| error::InvalidCopyDatabasePathSnafu { value: directory }.build())?
115                    .pop_if_empty()
116                    .push(&filename);
117                // File URLs are decoded by the filesystem backend; object-store
118                // backends use the encoded URL path as their key.
119                let path = if url.scheme().eq_ignore_ascii_case(FILE_SCHEMA) {
120                    filename
121                } else {
122                    url.path()
123                        .rsplit('/')
124                        .next()
125                        .unwrap_or_default()
126                        .to_string()
127                };
128                Ok(Self {
129                    path,
130                    location: url.into(),
131                })
132            }
133            Err(url::ParseError::RelativeUrlWithoutBase) => Ok(Self {
134                location: format!("{directory}{filename}"),
135                path: filename,
136            }),
137            Err(source) => Err(source)
138                .context(common_datasource::error::InvalidUrlSnafu { url: directory })
139                .context(error::BuildBackendSnafu),
140        }
141    }
142}
143
144/// Resolves every output before any writer starts. Packed exports use generated
145/// object names instead of table names on disk.
146pub(crate) fn prepare_database_export_files(
147    directory: &str,
148    names: impl IntoIterator<Item = String>,
149    suffix: &str,
150    packed: bool,
151) -> Result<Vec<DatabaseExportFile>> {
152    let (scheme, _, _) = parse_url(directory).context(error::BuildBackendSnafu)?;
153    let local = scheme.eq_ignore_ascii_case(FS_SCHEMA) || scheme.eq_ignore_ascii_case(FILE_SCHEMA);
154    let mut filenames = HashMap::new();
155    let mut outputs = Vec::new();
156    for name in names {
157        let output = DatabaseExportFile::new(directory, &name, suffix)?;
158        if cfg!(windows) && local && !packed {
159            common_datasource::object_store::validate_windows_file_name(&output.path).map_err(
160                |reason| {
161                    error::InvalidDatabaseExportSnafu {
162                        reason: format!("table {name}: {reason}"),
163                    }
164                    .build()
165                },
166            )?;
167        }
168        // Use platform defaults for per-table files. This does not model
169        // filesystem-specific Unicode equivalences such as APFS normalization.
170        let key = if local && !packed && cfg!(any(windows, target_os = "macos")) {
171            output.path.to_lowercase()
172        } else {
173            output.path.clone()
174        };
175        if let Some(previous) = filenames.insert(key, name.clone()) {
176            return error::InvalidDatabaseExportSnafu {
177                reason: format!(
178                    "duplicate output name: {name} conflicts with {previous} ({})",
179                    output.path
180                ),
181            }
182            .fail();
183        }
184        outputs.push(output);
185    }
186    Ok(outputs)
187}
188
189/// Resolve a listed writer key back to its table name and COPY input location.
190pub(crate) fn database_import_source(directory: &str, path: &str) -> Result<(String, String)> {
191    let mut filename = path.rsplit('/').next().unwrap_or(path).to_string();
192    let mut location = format!("{directory}{path}");
193    #[cfg(windows)]
194    let literal_path = common_datasource::object_store::handle_windows_path(directory).is_some();
195    #[cfg(not(windows))]
196    let literal_path = false;
197    if !literal_path && let Ok(mut url) = Url::parse(directory) {
198        if url.scheme().eq_ignore_ascii_case(FILE_SCHEMA) {
199            url.path_segments_mut()
200                .map_err(|_| error::InvalidCopyDatabasePathSnafu { value: directory }.build())?
201                .pop_if_empty()
202                .extend(path.split('/'));
203        } else {
204            // Listed object keys already contain the export URL's escaping.
205            url.set_path(&format!("{}{path}", url.path()));
206            filename = percent_encoding::percent_decode_str(&filename)
207                .decode_utf8()
208                .ok()
209                .context(error::InvalidTableNameSnafu { table_name: path })?
210                .into_owned();
211        }
212        location = url.into();
213    }
214    let table_name = filename
215        .rsplit_once('.')
216        .map(|(stem, _)| stem)
217        .filter(|stem| !stem.is_empty())
218        .context(error::InvalidTableNameSnafu { table_name: path })?
219        .to_string();
220    Ok((table_name, location))
221}
222
223impl StatementExecutor {
224    /// Capture each selected data table once. Views, temporary and Metric physical
225    /// tables do not have data outputs. `None` selects the whole schema.
226    pub async fn capture_database_export_tables(
227        &self,
228        req: &CopyDatabaseRequest,
229        names: Option<&[String]>,
230        ctx: &QueryContextRef,
231    ) -> Result<Vec<TableRef>> {
232        let mut names = match names {
233            Some(names) => names.to_vec(),
234            None => self
235                .catalog_manager
236                .table_names(&req.catalog_name, &req.schema_name, Some(ctx))
237                .await
238                .context(error::CatalogSnafu)?,
239        };
240        names.sort();
241        let mut tables = Vec::new();
242        for name in names {
243            let table = self
244                .get_table(&TableReference::full(
245                    &req.catalog_name,
246                    &req.schema_name,
247                    &name,
248                ))
249                .await?;
250            let info = table.table_info();
251            if table.table_type() == TableType::Base
252                && (info.meta.engine != METRIC_ENGINE_NAME
253                    || info
254                        .meta
255                        .options
256                        .extra_options
257                        .contains_key(LOGICAL_TABLE_METADATA_KEY))
258            {
259                tables.push(table);
260            }
261        }
262        Ok(tables)
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn database_export_file_names_are_distinct() {
272        for directory in ["backup/", "file:///copy/backup/"] {
273            for names in [["Events", "events"], ["Éa", "éa"]] {
274                for packed in [false, true] {
275                    let result = prepare_database_export_files(
276                        directory,
277                        names.map(String::from),
278                        ".parquet",
279                        packed,
280                    );
281                    if !packed && cfg!(any(windows, target_os = "macos")) {
282                        assert!(matches!(result,
283                            Err(error::Error::InvalidDatabaseExport { reason })
284                            if names.iter().all(|name| reason.contains(name))));
285                    } else {
286                        assert_eq!(result.unwrap().len(), 2);
287                    }
288                }
289            }
290        }
291        let overlong_name = "z".repeat(252);
292        for name in [
293            "job:rate5m",
294            "a:b",
295            ":leading",
296            "con",
297            "nul.part",
298            &overlong_name,
299        ] {
300            let local = prepare_database_export_files("backup/", [name.into()], ".parquet", false);
301            assert_eq!(local.is_err(), cfg!(windows), "{name}");
302            prepare_database_export_files("backup/", [name.into()], ".parquet", true).unwrap();
303        }
304        let remote = prepare_database_export_files(
305            "s3://bucket/backup/",
306            [
307                "Events".into(),
308                "events".into(),
309                "job:rate5m".into(),
310                "con".into(),
311                overlong_name,
312            ],
313            ".parquet",
314            false,
315        )
316        .unwrap();
317        assert_eq!(remote.len(), 5);
318    }
319
320    #[test]
321    fn directory_url_components_cannot_capture_output_names() {
322        for location in [
323            "file:///copy/fresh?attempt=/",
324            "file:///copy/fresh#attempt/",
325            "s3://bucket/fresh?attempt=/",
326            "s3://bucket/fresh#attempt/",
327            "file:///copy/fresh",
328        ] {
329            assert!(validate_database_directory(location).is_err(), "{location}");
330        }
331        for location in ["/copy/fresh/", "file:///copy/fresh/", "s3://bucket/fresh/"] {
332            validate_database_directory(location).unwrap();
333        }
334    }
335
336    #[cfg(windows)]
337    #[test]
338    fn windows_directory_names_are_literal_paths() {
339        for location in ["C:/copy/fresh#1/", r"C:\copy\fresh#1\"] {
340            validate_database_directory(location).unwrap();
341        }
342        assert!(validate_database_directory("C:/copy/fresh#1").is_err());
343    }
344
345    #[tokio::test]
346    async fn output_locations_resolve_to_writer_keys() {
347        use common_datasource::object_store::{
348            LocalFileAccess, RemoteStorageAccess, build_backend_for_write_with_path,
349        };
350
351        let dir = common_test_util::temp_dir::create_temp_dir("database_export_paths");
352        let access = LocalFileAccess::sandboxed(dir.path()).unwrap();
353        let file_url = Url::from_directory_path(dir.path()).unwrap().to_string();
354        let connection = HashMap::from([
355            ("region".into(), "us-east-1".into()),
356            ("access_key_id".into(), "test-key".into()),
357            ("secret_access_key".into(), "test-secret".into()),
358        ]);
359        for directory in [
360            format!("{}/", dir.path().display()),
361            file_url,
362            "s3://export-bucket/data/".into(),
363        ] {
364            for name in ["a#b", "a:b"] {
365                if cfg!(windows) && name.contains(':') && !directory.starts_with("s3:") {
366                    continue;
367                }
368                let file = DatabaseExportFile::new(&directory, name, ".parquet").unwrap();
369                let backend = build_backend_for_write_with_path(
370                    &file.location,
371                    &connection,
372                    &access,
373                    &RemoteStorageAccess::unrestricted(),
374                )
375                .await
376                .unwrap();
377                assert_eq!(backend.object_path.as_deref(), Some(file.path.as_str()));
378                let (table_name, input_location) =
379                    database_import_source(&directory, &file.path).unwrap();
380                assert_eq!(table_name, name);
381                assert_eq!(input_location, file.location);
382                let (table_name, nested_location) =
383                    database_import_source(&directory, &format!("nested/{}", file.path)).unwrap();
384                assert_eq!(table_name, name);
385                assert_eq!(
386                    nested_location,
387                    file.location
388                        .replace(&directory, &format!("{directory}nested/"))
389                );
390                if !directory.starts_with("s3:") {
391                    backend
392                        .object_store
393                        .write(&file.path, "test")
394                        .await
395                        .unwrap();
396                    assert_eq!(
397                        std::fs::read(dir.path().join(format!("{name}.parquet"))).unwrap(),
398                        b"test"
399                    );
400                } else {
401                    assert_eq!(
402                        file.path,
403                        if name == "a#b" {
404                            "a%23b.parquet"
405                        } else {
406                            "a:b.parquet"
407                        }
408                    );
409                }
410            }
411        }
412    }
413
414    #[test]
415    fn test_parse_parallelism_from_option_map() {
416        let options = HashMap::new();
417        assert_eq!(
418            parse_parallelism_from_option_map(&options),
419            get_total_cpu_cores()
420        );
421
422        let options = HashMap::from([("parallelism".to_string(), "0".to_string())]);
423        assert_eq!(parse_parallelism_from_option_map(&options), 1);
424
425        let options = HashMap::from([("parallelism".to_string(), usize::MAX.to_string())]);
426        assert_eq!(
427            parse_parallelism_from_option_map(&options),
428            Semaphore::MAX_PERMITS
429        );
430    }
431}