Skip to main content

cli/data/
export.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::collections::HashSet;
16use std::sync::Arc;
17use std::time::Duration;
18
19use async_trait::async_trait;
20use clap::{Parser, ValueEnum};
21use common_error::ext::BoxedError;
22use common_telemetry::{debug, info};
23use object_store::ObjectStore;
24use serde_json::Value;
25use snafu::{OptionExt, ResultExt};
26use tokio::sync::Semaphore;
27use tokio::time::Instant;
28
29use crate::common::{ObjectStoreConfig, new_fs_object_store};
30use crate::data::schema_export::append_schema_ddl;
31use crate::data::storage_export::{
32    AzblobBackend, FsBackend, GcsBackend, OssBackend, S3Backend, StorageExport, StorageType,
33};
34use crate::data::{COPY_PATH_PLACEHOLDER, collect_schema_job_results, default_database};
35use crate::database::{DatabaseClient, parse_proxy_opts};
36use crate::error::{
37    EmptyResultSnafu, Error, OpenDalSnafu, OutputDirNotSetSnafu, Result, SchemaNotFoundSnafu,
38};
39use crate::{Tool, database};
40
41type TableReference = (String, String, String);
42
43#[derive(Debug, Default, Clone, ValueEnum)]
44enum ExportTarget {
45    /// Export all table schemas, corresponding to `SHOW CREATE TABLE`.
46    Schema,
47    /// Export all table data, corresponding to `COPY DATABASE TO`.
48    Data,
49    /// Export all table schemas and data at once.
50    #[default]
51    All,
52}
53
54/// Command for exporting data from the GreptimeDB.
55#[derive(Debug, Default, Parser)]
56pub struct ExportCommand {
57    /// Server address to connect
58    #[clap(long)]
59    addr: String,
60
61    /// Directory to put the exported data. E.g.: /tmp/greptimedb-export
62    /// for local export.
63    #[clap(long)]
64    output_dir: Option<String>,
65
66    /// The name of the catalog to export.
67    #[clap(long, default_value_t = default_database())]
68    database: String,
69
70    /// The number of databases exported in parallel.
71    /// For example, if there are 20 databases and `db_parallelism` is 4,
72    /// 4 databases will be exported concurrently.
73    #[clap(long, short = 'j', default_value = "1", alias = "export-jobs")]
74    db_parallelism: usize,
75
76    /// The number of tables exported in parallel within a single database.
77    /// For example, if a database has 30 tables and `parallelism` is 8,
78    /// 8 tables will be exported concurrently.
79    #[clap(long, default_value = "4")]
80    table_parallelism: usize,
81
82    /// Max retry times for each job.
83    #[clap(long, default_value = "3")]
84    max_retry: usize,
85
86    /// Things to export
87    #[clap(long, short = 't', value_enum, default_value = "all")]
88    target: ExportTarget,
89
90    /// A half-open time range: [start_time, end_time).
91    /// The start of the time range (time-index column) for data export.
92    #[clap(long)]
93    start_time: Option<String>,
94
95    /// A half-open time range: [start_time, end_time).
96    /// The end of the time range (time-index column) for data export.
97    #[clap(long)]
98    end_time: Option<String>,
99
100    /// The basic authentication for connecting to the server
101    #[clap(long)]
102    auth_basic: Option<String>,
103
104    /// The timeout of invoking the database.
105    ///
106    /// It is used to override the server-side timeout setting.
107    /// The default behavior will disable server-side default timeout(i.e. `0s`).
108    #[clap(long, value_parser = humantime::parse_duration)]
109    timeout: Option<Duration>,
110
111    /// The proxy server address to connect.
112    ///
113    /// If set, it overrides the system proxy unless `--no-proxy` is specified.
114    /// If neither `--proxy` nor `--no-proxy` is set, system proxy (env) may be used.
115    #[clap(long)]
116    proxy: Option<String>,
117
118    /// Disable all proxy usage (ignores `--proxy` and system proxy).
119    ///
120    /// When set and `--proxy` is not provided, this explicitly disables system proxy.
121    #[clap(long)]
122    no_proxy: bool,
123
124    /// if both `ddl_local_dir` and remote storage are set, `ddl_local_dir` will be only used for
125    /// exported SQL files, and the data will be exported to remote storage.
126    ///
127    /// Note that `ddl_local_dir` export sql files to **LOCAL** file system, this is useful if export client don't have
128    /// direct access to remote storage.
129    ///
130    /// if remote storage is set but `ddl_local_dir` is not set, both SQL&data will be exported to remote storage.
131    #[clap(long)]
132    ddl_local_dir: Option<String>,
133
134    #[clap(flatten)]
135    storage: ObjectStoreConfig,
136}
137
138impl ExportCommand {
139    pub async fn build(&self) -> std::result::Result<Box<dyn Tool>, BoxedError> {
140        // Determine storage type
141        let (storage_type, operator) = if self.storage.enable_s3 {
142            (
143                StorageType::S3(S3Backend::new(self.storage.s3.clone())?),
144                self.storage.build_s3()?,
145            )
146        } else if self.storage.enable_oss {
147            (
148                StorageType::Oss(OssBackend::new(self.storage.oss.clone())?),
149                self.storage.build_oss()?,
150            )
151        } else if self.storage.enable_gcs {
152            (
153                StorageType::Gcs(GcsBackend::new(self.storage.gcs.clone())?),
154                self.storage.build_gcs()?,
155            )
156        } else if self.storage.enable_azblob {
157            (
158                StorageType::Azblob(AzblobBackend::new(self.storage.azblob.clone())?),
159                self.storage.build_azblob()?,
160            )
161        } else if let Some(output_dir) = &self.output_dir {
162            (
163                StorageType::Fs(FsBackend::new(output_dir.clone())),
164                new_fs_object_store(output_dir)?,
165            )
166        } else {
167            return Err(BoxedError::new(OutputDirNotSetSnafu {}.build()));
168        };
169
170        let (catalog, schema) =
171            database::split_database(&self.database).map_err(BoxedError::new)?;
172        let proxy = parse_proxy_opts(self.proxy.clone(), self.no_proxy)?;
173        let database_client = DatabaseClient::new(
174            self.addr.clone(),
175            catalog.clone(),
176            self.auth_basic.clone(),
177            // Treats `None` as `0s` to disable server-side default timeout.
178            self.timeout.unwrap_or_default(),
179            proxy,
180            self.no_proxy,
181        );
182
183        Ok(Box::new(Export {
184            catalog,
185            schema,
186            database_client,
187            export_jobs: self.db_parallelism,
188            target: self.target.clone(),
189            start_time: self.start_time.clone(),
190            end_time: self.end_time.clone(),
191            parallelism: self.table_parallelism,
192            storage_type,
193            ddl_local_dir: self.ddl_local_dir.clone(),
194            operator,
195        }))
196    }
197}
198
199#[derive(Clone)]
200pub struct Export {
201    catalog: String,
202    schema: Option<String>,
203    database_client: DatabaseClient,
204    export_jobs: usize,
205    target: ExportTarget,
206    start_time: Option<String>,
207    end_time: Option<String>,
208    parallelism: usize,
209    storage_type: StorageType,
210    ddl_local_dir: Option<String>,
211    operator: ObjectStore,
212}
213
214impl Export {
215    async fn get_db_names(&self) -> Result<Vec<String>> {
216        let db_names = self.all_db_names().await?;
217        let Some(schema) = &self.schema else {
218            return Ok(db_names);
219        };
220
221        // Check if the schema exists
222        db_names
223            .into_iter()
224            .find(|db_name| db_name.to_lowercase() == schema.to_lowercase())
225            .map(|name| vec![name])
226            .context(SchemaNotFoundSnafu {
227                catalog: &self.catalog,
228                schema,
229            })
230    }
231
232    /// Iterate over all db names.
233    async fn all_db_names(&self) -> Result<Vec<String>> {
234        let records = self
235            .database_client
236            .sql_in_public("SHOW DATABASES")
237            .await?
238            .context(EmptyResultSnafu)?;
239        let mut result = Vec::with_capacity(records.len());
240        for value in records {
241            let Value::String(schema) = &value[0] else {
242                unreachable!()
243            };
244            if schema == common_catalog::consts::INFORMATION_SCHEMA_NAME {
245                continue;
246            }
247            if schema == common_catalog::consts::PG_CATALOG_NAME {
248                continue;
249            }
250            result.push(schema.clone());
251        }
252        Ok(result)
253    }
254
255    /// Return a list of [`TableReference`] to be exported.
256    /// Includes all tables under the given `catalog` and `schema`.
257    async fn get_table_list(
258        &self,
259        catalog: &str,
260        schema: &str,
261    ) -> Result<(
262        Vec<TableReference>,
263        Vec<TableReference>,
264        Vec<TableReference>,
265    )> {
266        // Puts all metric table first
267        let sql = format!(
268            "SELECT table_catalog, table_schema, table_name \
269            FROM information_schema.columns \
270            WHERE column_name = '__tsid' \
271                and table_catalog = \'{catalog}\' \
272                and table_schema = \'{schema}\'"
273        );
274        let records = self
275            .database_client
276            .sql_in_public(&sql)
277            .await?
278            .context(EmptyResultSnafu)?;
279        let mut metric_physical_tables = HashSet::with_capacity(records.len());
280        for value in records {
281            let mut t = Vec::with_capacity(3);
282            for v in &value {
283                let Value::String(value) = v else {
284                    unreachable!()
285                };
286                t.push(value);
287            }
288            metric_physical_tables.insert((t[0].clone(), t[1].clone(), t[2].clone()));
289        }
290
291        let sql = format!(
292            "SELECT table_catalog, table_schema, table_name, table_type \
293            FROM information_schema.tables \
294            WHERE (table_type = \'BASE TABLE\' OR table_type = \'VIEW\') \
295                and table_catalog = \'{catalog}\' \
296                and table_schema = \'{schema}\'",
297        );
298        let records = self
299            .database_client
300            .sql_in_public(&sql)
301            .await?
302            .context(EmptyResultSnafu)?;
303
304        debug!("Fetched table/view list: {:?}", records);
305
306        if records.is_empty() {
307            return Ok((vec![], vec![], vec![]));
308        }
309
310        let mut remaining_tables = Vec::with_capacity(records.len());
311        let mut views = Vec::new();
312        for value in records {
313            let mut t = Vec::with_capacity(4);
314            for v in &value {
315                let Value::String(value) = v else {
316                    unreachable!()
317                };
318                t.push(value);
319            }
320            let table = (t[0].clone(), t[1].clone(), t[2].clone());
321            let table_type = t[3].as_str();
322            // Ignores the physical table
323            if !metric_physical_tables.contains(&table) {
324                if table_type == "VIEW" {
325                    views.push(table);
326                } else {
327                    remaining_tables.push(table);
328                }
329            }
330        }
331
332        Ok((
333            metric_physical_tables.into_iter().collect(),
334            remaining_tables,
335            views,
336        ))
337    }
338
339    async fn export_create_database(&self) -> Result<()> {
340        let timer = Instant::now();
341        let db_names = self.get_db_names().await?;
342        let db_count = db_names.len();
343        let operator = self.build_prefer_fs_operator().await?;
344
345        for schema in db_names {
346            let mut create_database = String::new();
347            append_schema_ddl(
348                &self.database_client,
349                &self.catalog,
350                &schema,
351                std::iter::once(("DATABASE", None)),
352                &mut create_database,
353            )
354            .await?;
355
356            let file_path = self.get_file_path(&schema, "create_database.sql");
357            self.write_to_storage(&operator, &file_path, create_database.into_bytes())
358                .await?;
359
360            info!(
361                "Exported {}.{} database creation SQL to {}",
362                self.catalog,
363                schema,
364                self.storage_type.format_output_path(&file_path)
365            );
366        }
367
368        let elapsed = timer.elapsed();
369        info!("Success {db_count} jobs, cost: {elapsed:?}");
370
371        Ok(())
372    }
373
374    async fn export_create_table(&self) -> Result<()> {
375        let timer = Instant::now();
376        let semaphore = Arc::new(Semaphore::new(self.export_jobs));
377        let db_names = self.get_db_names().await?;
378        let db_count = db_names.len();
379        let operator = Arc::new(self.build_prefer_fs_operator().await?);
380        let mut tasks = Vec::with_capacity(db_names.len());
381
382        for schema in &db_names {
383            let semaphore_moved = semaphore.clone();
384            let export_self = self.clone();
385            let operator = operator.clone();
386            tasks.push(async move {
387                let _permit = semaphore_moved.acquire().await.unwrap();
388                let (metric_physical_tables, remaining_tables, views) = export_self
389                    .get_table_list(&export_self.catalog, schema)
390                    .await?;
391
392                // Create directory if needed for file system storage
393                if !export_self.storage_type.is_remote_storage() {
394                    let db_dir = format!("{}/{}/", export_self.catalog, schema);
395                    operator.create_dir(&db_dir).await.context(OpenDalSnafu)?;
396                }
397
398                let file_path = export_self.get_file_path(schema, "create_tables.sql");
399                let mut content = String::new();
400                let objects = metric_physical_tables
401                    .iter()
402                    .chain(&remaining_tables)
403                    .map(|(_, _, table)| ("TABLE", Some(table.as_str())))
404                    .chain(
405                        views
406                            .iter()
407                            .map(|(_, _, view)| ("VIEW", Some(view.as_str()))),
408                    );
409                append_schema_ddl(
410                    &export_self.database_client,
411                    &export_self.catalog,
412                    schema,
413                    objects,
414                    &mut content,
415                )
416                .await?;
417
418                // Write to storage
419                export_self
420                    .write_to_storage(&operator, &file_path, content.into_bytes())
421                    .await?;
422
423                info!(
424                    "Finished exporting {}.{schema} with {} table schemas to path: {}",
425                    export_self.catalog,
426                    metric_physical_tables.len() + remaining_tables.len() + views.len(),
427                    export_self.storage_type.format_output_path(&file_path)
428                );
429
430                Ok::<(), Error>(())
431            });
432        }
433
434        let results = futures::future::join_all(tasks).await;
435        collect_schema_job_results(&self.catalog, &db_names, results, "export database schema")?;
436        let elapsed = timer.elapsed();
437        info!("Success {db_count} jobs, cost: {elapsed:?}");
438
439        Ok(())
440    }
441
442    async fn build_operator(&self) -> Result<ObjectStore> {
443        Ok(self.operator.clone())
444    }
445
446    /// build operator with preference for file system
447    async fn build_prefer_fs_operator(&self) -> Result<ObjectStore> {
448        if self.storage_type.is_remote_storage()
449            && let Some(ddl_local_dir) = &self.ddl_local_dir
450        {
451            let root = ddl_local_dir.clone();
452            let op = new_fs_object_store(&root).map_err(|e| Error::Other {
453                source: e,
454                location: snafu::location!(),
455            })?;
456            Ok(op)
457        } else {
458            Ok(self.operator.clone())
459        }
460    }
461
462    async fn export_database_data(&self) -> Result<()> {
463        let timer = Instant::now();
464        let semaphore = Arc::new(Semaphore::new(self.export_jobs));
465        let db_names = self.get_db_names().await?;
466        let db_count = db_names.len();
467        let mut tasks = Vec::with_capacity(db_count);
468        let operator = Arc::new(self.build_operator().await?);
469        let fs_first_operator = Arc::new(self.build_prefer_fs_operator().await?);
470        let with_options = build_with_options(&self.start_time, &self.end_time, self.parallelism);
471
472        for schema in &db_names {
473            let semaphore_moved = semaphore.clone();
474            let export_self = self.clone();
475            let with_options_clone = with_options.clone();
476            let operator = operator.clone();
477            let fs_first_operator = fs_first_operator.clone();
478
479            tasks.push(async move {
480                let _permit = semaphore_moved.acquire().await.unwrap();
481
482                // Create directory if not using remote storage
483                if !export_self.storage_type.is_remote_storage() {
484                    let db_dir = format!("{}/{}/", export_self.catalog, schema);
485                    operator.create_dir(&db_dir).await.context(OpenDalSnafu)?;
486                }
487
488                let (path, connection_part) = export_self
489                    .storage_type
490                    .get_storage_path(&export_self.catalog, schema);
491
492                // Execute COPY DATABASE TO command
493                let sql = format!(
494                    r#"COPY DATABASE "{}"."{}" TO '{}' WITH ({}){};"#,
495                    export_self.catalog, schema, path, with_options_clone, connection_part
496                );
497
498                // Log SQL command but mask sensitive information
499                let safe_sql = export_self.storage_type.mask_sensitive_info(&sql);
500                info!("Executing sql: {}", safe_sql);
501
502                export_self.database_client.sql_in_public(&sql).await?;
503                info!(
504                    "Finished exporting {}.{} data to {}",
505                    export_self.catalog, schema, path
506                );
507
508                // Create copy_from.sql file
509                let copy_database_from_sql = {
510                    let command_without_connection = format!(
511                        r#"COPY DATABASE "{}"."{}" FROM '{}' WITH ({});"#,
512                        export_self.catalog, schema, COPY_PATH_PLACEHOLDER, with_options_clone
513                    );
514
515                    if connection_part.is_empty() {
516                        command_without_connection
517                    } else {
518                        let command_with_connection = format!(
519                            r#"COPY DATABASE "{}"."{}" FROM '{}' WITH ({}){};"#,
520                            export_self.catalog, schema, path, with_options_clone, connection_part
521                        );
522
523                        format!(
524                            "-- {}\n{}",
525                            command_with_connection, command_without_connection
526                        )
527                    }
528                };
529
530                let copy_from_path = export_self.get_file_path(schema, "copy_from.sql");
531                export_self
532                    .write_to_storage(
533                        &fs_first_operator,
534                        &copy_from_path,
535                        copy_database_from_sql.into_bytes(),
536                    )
537                    .await?;
538
539                info!(
540                    "Finished exporting {}.{} copy_from.sql to {}",
541                    export_self.catalog,
542                    schema,
543                    export_self.storage_type.format_output_path(&copy_from_path)
544                );
545
546                Ok::<(), Error>(())
547            });
548        }
549
550        let results = futures::future::join_all(tasks).await;
551        collect_schema_job_results(&self.catalog, &db_names, results, "export database data")?;
552        let elapsed = timer.elapsed();
553        info!("Success {db_count} jobs, costs: {elapsed:?}");
554
555        Ok(())
556    }
557
558    fn get_file_path(&self, schema: &str, file_name: &str) -> String {
559        format!("{}/{}/{}", self.catalog, schema, file_name)
560    }
561
562    async fn write_to_storage(
563        &self,
564        op: &ObjectStore,
565        file_path: &str,
566        content: Vec<u8>,
567    ) -> Result<()> {
568        op.write(file_path, content)
569            .await
570            .context(OpenDalSnafu)
571            .map(|_| ())
572    }
573}
574
575#[async_trait]
576impl Tool for Export {
577    async fn do_work(&self) -> std::result::Result<(), BoxedError> {
578        match self.target {
579            ExportTarget::Schema => {
580                self.export_create_database()
581                    .await
582                    .map_err(BoxedError::new)?;
583                self.export_create_table().await.map_err(BoxedError::new)
584            }
585            ExportTarget::Data => self.export_database_data().await.map_err(BoxedError::new),
586            ExportTarget::All => {
587                self.export_create_database()
588                    .await
589                    .map_err(BoxedError::new)?;
590                self.export_create_table().await.map_err(BoxedError::new)?;
591                self.export_database_data().await.map_err(BoxedError::new)
592            }
593        }
594    }
595}
596
597/// Builds the WITH options string for SQL commands, assuming consistent syntax across S3 and local exports.
598fn build_with_options(
599    start_time: &Option<String>,
600    end_time: &Option<String>,
601    parallelism: usize,
602) -> String {
603    let mut options = vec!["format = 'parquet'".to_string()];
604    if let Some(start) = start_time {
605        options.push(format!("start_time = '{}'", start));
606    }
607    if let Some(end) = end_time {
608        options.push(format!("end_time = '{}'", end));
609    }
610    options.push(format!("parallelism = {}", parallelism));
611    options.join(", ")
612}
613
614#[cfg(test)]
615mod tests {
616    use clap::Parser;
617    use common_test_util::temp_dir::create_temp_dir;
618
619    use super::*;
620
621    const MOCK_AZBLOB_ACCOUNT_KEY_B64: &str = "dGVzdC1rZXk=";
622
623    // ==================== Basic Success Cases ====================
624
625    #[tokio::test]
626    async fn test_export_command_build_with_local_fs() {
627        let temp_dir = create_temp_dir("test_export_local_fs");
628        let output_dir = temp_dir.path().to_str().unwrap();
629
630        let cmd = ExportCommand::parse_from([
631            "export",
632            "--addr",
633            "127.0.0.1:4000",
634            "--output-dir",
635            output_dir,
636        ]);
637
638        let result = cmd.build().await;
639        assert!(result.is_ok());
640    }
641
642    #[tokio::test]
643    async fn test_export_command_build_with_s3_success() {
644        let cmd = ExportCommand::parse_from([
645            "export",
646            "--addr",
647            "127.0.0.1:4000",
648            "--s3",
649            "--s3-bucket",
650            "test-bucket",
651            "--s3-root",
652            "test-root",
653            "--s3-access-key-id",
654            "test-key",
655            "--s3-secret-access-key",
656            "test-secret",
657            // Optional fields
658            "--s3-region",
659            "us-west-2",
660            "--s3-endpoint",
661            "https://s3.amazonaws.com",
662        ]);
663
664        let result = cmd.build().await;
665        assert!(result.is_ok());
666    }
667
668    #[tokio::test]
669    async fn test_export_command_build_with_oss_success() {
670        let cmd = ExportCommand::parse_from([
671            "export",
672            "--addr",
673            "127.0.0.1:4000",
674            "--oss",
675            "--oss-bucket",
676            "test-bucket",
677            "--oss-root",
678            "test-root",
679            "--oss-access-key-id",
680            "test-key-id",
681            "--oss-access-key-secret",
682            "test-secret",
683            "--oss-endpoint",
684            "https://oss.example.com",
685        ]);
686
687        let result = cmd.build().await;
688        assert!(result.is_ok());
689    }
690
691    #[tokio::test]
692    async fn test_export_command_build_with_gcs_success() {
693        let cmd = ExportCommand::parse_from([
694            "export",
695            "--addr",
696            "127.0.0.1:4000",
697            "--gcs",
698            "--gcs-bucket",
699            "test-bucket",
700            "--gcs-root",
701            "test-root",
702            "--gcs-scope",
703            "test-scope",
704            "--gcs-credential",
705            "test-credential-content",
706            "--gcs-endpoint",
707            "https://storage.googleapis.com",
708        ]);
709
710        let result = cmd.build().await;
711        assert!(result.is_ok());
712    }
713
714    #[tokio::test]
715    async fn test_export_command_build_with_gcs_adc_success() {
716        // Test GCS with Application Default Credentials (no explicit credentials provided)
717        let cmd = ExportCommand::parse_from([
718            "export",
719            "--addr",
720            "127.0.0.1:4000",
721            "--gcs",
722            "--gcs-bucket",
723            "test-bucket",
724            "--gcs-root",
725            "test-root",
726            "--gcs-scope",
727            "test-scope",
728            // No credential
729            // No endpoint (optional)
730        ]);
731
732        let result = cmd.build().await;
733        assert!(result.is_ok());
734    }
735
736    #[tokio::test]
737    async fn test_export_command_build_with_azblob_success() {
738        let cmd = ExportCommand::parse_from([
739            "export",
740            "--addr",
741            "127.0.0.1:4000",
742            "--azblob",
743            "--azblob-container",
744            "test-container",
745            "--azblob-root",
746            "test-root",
747            "--azblob-account-name",
748            "test-account",
749            "--azblob-account-key",
750            MOCK_AZBLOB_ACCOUNT_KEY_B64,
751            "--azblob-endpoint",
752            "https://account.blob.core.windows.net",
753        ]);
754
755        let result = cmd.build().await;
756        assert!(result.is_ok());
757    }
758
759    #[tokio::test]
760    async fn test_export_command_build_with_azblob_with_sas_token() {
761        // Test Azure Blob with SAS token
762        let cmd = ExportCommand::parse_from([
763            "export",
764            "--addr",
765            "127.0.0.1:4000",
766            "--azblob",
767            "--azblob-container",
768            "test-container",
769            "--azblob-root",
770            "test-root",
771            "--azblob-account-name",
772            "test-account",
773            "--azblob-account-key",
774            MOCK_AZBLOB_ACCOUNT_KEY_B64,
775            "--azblob-endpoint",
776            "https://account.blob.core.windows.net",
777            "--azblob-sas-token",
778            "test-sas-token",
779        ]);
780
781        let result = cmd.build().await;
782        assert!(result.is_ok());
783    }
784
785    // ==================== Gap 1: Parse-time dependency checks ====================
786
787    #[test]
788    fn test_export_command_build_with_conflict() {
789        // Try to enable both S3 and OSS
790        let result =
791            ExportCommand::try_parse_from(["export", "--addr", "127.0.0.1:4000", "--s3", "--oss"]);
792
793        assert!(result.is_err());
794        let err = result.unwrap_err();
795        // clap error for conflicting arguments
796        assert!(err.kind() == clap::error::ErrorKind::ArgumentConflict);
797    }
798
799    #[tokio::test]
800    async fn test_export_command_build_with_s3_no_enable_flag() {
801        // Test that providing S3 config without --s3 flag fails
802        let result = ExportCommand::try_parse_from([
803            "export",
804            "--addr",
805            "127.0.0.1:4000",
806            // Note: no --s3 flag
807            "--s3-bucket",
808            "test-bucket",
809            "--s3-access-key-id",
810            "test-key",
811            "--output-dir",
812            "/tmp/test",
813        ]);
814
815        assert!(result.is_err());
816        let err = result.unwrap_err();
817        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
818        assert!(err.to_string().contains("--s3"));
819    }
820
821    #[tokio::test]
822    async fn test_export_command_build_with_oss_no_enable_flag() {
823        // Test that providing OSS config without --oss flag fails at parse time
824        let result = ExportCommand::try_parse_from([
825            "export",
826            "--addr",
827            "127.0.0.1:4000",
828            "--oss-bucket",
829            "test-bucket",
830            "--output-dir",
831            "/tmp/test",
832        ]);
833
834        assert!(result.is_err());
835        let err = result.unwrap_err();
836        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
837        assert!(err.to_string().contains("--oss"));
838    }
839
840    #[tokio::test]
841    async fn test_export_command_build_with_gcs_no_enable_flag() {
842        // Test that providing GCS config without --gcs flag fails at parse time
843        let result = ExportCommand::try_parse_from([
844            "export",
845            "--addr",
846            "127.0.0.1:4000",
847            "--gcs-bucket",
848            "test-bucket",
849            "--output-dir",
850            "/tmp/test",
851        ]);
852
853        assert!(result.is_err());
854        let err = result.unwrap_err();
855        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
856        assert!(err.to_string().contains("--gcs"));
857    }
858
859    #[tokio::test]
860    async fn test_export_command_build_with_azblob_no_enable_flag() {
861        // Test that providing Azure Blob config without --azblob flag fails at parse time
862        let result = ExportCommand::try_parse_from([
863            "export",
864            "--addr",
865            "127.0.0.1:4000",
866            "--azblob-container",
867            "test-container",
868            "--output-dir",
869            "/tmp/test",
870        ]);
871
872        assert!(result.is_err());
873        let err = result.unwrap_err();
874        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
875        assert!(err.to_string().contains("--azblob"));
876    }
877
878    // ==================== Gap 2: Empty string vs missing tests ====================
879
880    #[tokio::test]
881    async fn test_export_command_build_with_s3_empty_root() {
882        // Empty root should be allowed (it's optional path component)
883        let cmd = ExportCommand::parse_from([
884            "export",
885            "--addr",
886            "127.0.0.1:4000",
887            "--s3",
888            "--s3-bucket",
889            "test-bucket",
890            "--s3-root",
891            "", // Empty root is OK
892            "--s3-access-key-id",
893            "test-key",
894            "--s3-secret-access-key",
895            "test-secret",
896            "--s3-region",
897            "us-west-2",
898        ]);
899
900        let result = cmd.build().await;
901        // Should succeed because root is not a required field
902        assert!(
903            result.is_ok(),
904            "Expected success but got: {:?}",
905            result.err()
906        );
907    }
908
909    #[tokio::test]
910    async fn test_export_command_build_with_oss_empty_access_key_id() {
911        // Test OSS with empty access_key_id (empty string, not missing)
912        let cmd = ExportCommand::parse_from([
913            "export",
914            "--addr",
915            "127.0.0.1:4000",
916            "--oss",
917            "--oss-bucket",
918            "test-bucket",
919            "--oss-access-key-id",
920            "", // Empty string
921            "--oss-access-key-secret",
922            "test-secret",
923            "--oss-endpoint",
924            "https://oss.example.com",
925        ]);
926
927        let result = cmd.build().await;
928        assert!(result.is_err());
929        if let Err(err) = result {
930            assert!(
931                err.to_string().contains("OSS access key ID must be set"),
932                "Actual error: {}",
933                err
934            );
935        }
936    }
937
938    #[tokio::test]
939    async fn test_export_command_build_with_oss_missing_endpoint() {
940        // Missing endpoint
941        let cmd = ExportCommand::parse_from([
942            "export",
943            "--addr",
944            "127.0.0.1:4000",
945            "--oss",
946            "--oss-bucket",
947            "test-bucket",
948            "--oss-root",
949            "test-root",
950            "--oss-access-key-id",
951            "test-key-id",
952            "--oss-access-key-secret",
953            "test-secret",
954        ]);
955
956        let result = cmd.build().await;
957        assert!(result.is_err());
958        if let Err(err) = result {
959            assert!(
960                err.to_string().contains("OSS endpoint must be set"),
961                "Actual error: {}",
962                err
963            );
964        }
965    }
966
967    #[tokio::test]
968    async fn test_export_command_build_with_oss_multiple_missing_fields() {
969        // Test OSS with multiple missing required fields
970        let cmd = ExportCommand::parse_from([
971            "export",
972            "--addr",
973            "127.0.0.1:4000",
974            "--oss",
975            "--oss-bucket",
976            "test-bucket",
977            // Missing: root, access_key_id, access_key_secret, endpoint
978        ]);
979
980        let result = cmd.build().await;
981        assert!(result.is_err());
982        if let Err(err) = result {
983            let err_str = err.to_string();
984            // Should mention multiple missing fields
985            assert!(
986                err_str.contains("OSS"),
987                "Error should mention OSS: {}",
988                err_str
989            );
990            assert!(
991                err_str.contains("must be set"),
992                "Error should mention required fields: {}",
993                err_str
994            );
995        }
996    }
997
998    #[tokio::test]
999    async fn test_export_command_build_with_gcs_empty_bucket() {
1000        // Test GCS with empty bucket
1001        let cmd = ExportCommand::parse_from([
1002            "export",
1003            "--addr",
1004            "127.0.0.1:4000",
1005            "--gcs",
1006            "--gcs-bucket",
1007            "", // Empty bucket
1008            "--gcs-root",
1009            "test-root",
1010            "--gcs-scope",
1011            "test-scope",
1012        ]);
1013
1014        let result = cmd.build().await;
1015        assert!(result.is_err());
1016        if let Err(err) = result {
1017            assert!(
1018                err.to_string().contains("GCS bucket must be set"),
1019                "Actual error: {}",
1020                err
1021            );
1022        }
1023    }
1024
1025    #[tokio::test]
1026    async fn test_export_command_build_with_gcs_empty_root() {
1027        // Test GCS when root is missing (should fail as it's required)
1028        let cmd = ExportCommand::parse_from([
1029            "export",
1030            "--addr",
1031            "127.0.0.1:4000",
1032            "--gcs",
1033            "--gcs-bucket",
1034            "test-bucket",
1035            "--gcs-root",
1036            "", // Empty root
1037            "--gcs-scope",
1038            "test-scope",
1039            "--gcs-credential",
1040            "test-credential",
1041            "--gcs-endpoint",
1042            "https://storage.googleapis.com",
1043        ]);
1044
1045        let result = cmd.build().await;
1046        assert!(result.is_err());
1047        if let Err(err) = result {
1048            assert!(
1049                err.to_string().contains("GCS root must be set"),
1050                "Actual error: {}",
1051                err
1052            );
1053        }
1054    }
1055
1056    #[tokio::test]
1057    async fn test_export_command_build_with_azblob_empty_account_name() {
1058        // account_name is optional for Azure Blob validation
1059        let cmd = ExportCommand::parse_from([
1060            "export",
1061            "--addr",
1062            "127.0.0.1:4000",
1063            "--azblob",
1064            "--azblob-container",
1065            "test-container",
1066            "--azblob-account-name",
1067            "", // Empty account name
1068            "--azblob-endpoint",
1069            "https://account.blob.core.windows.net",
1070        ]);
1071
1072        let result = cmd.build().await;
1073        assert!(result.is_ok(), "Empty account_name should succeed");
1074    }
1075
1076    #[tokio::test]
1077    async fn test_export_command_build_with_azblob_missing_account_key() {
1078        // account_key is optional for Azure Blob validation
1079        let cmd = ExportCommand::parse_from([
1080            "export",
1081            "--addr",
1082            "127.0.0.1:4000",
1083            "--azblob",
1084            "--azblob-container",
1085            "test-container",
1086            "--azblob-endpoint",
1087            "https://account.blob.core.windows.net",
1088        ]);
1089
1090        let result = cmd.build().await;
1091        assert!(result.is_ok(), "Missing account_key should succeed");
1092    }
1093
1094    // ==================== Gap 3: Boundary cases ====================
1095
1096    #[tokio::test]
1097    async fn test_export_command_build_with_no_storage() {
1098        // No output-dir and no backend - should fail
1099        let cmd = ExportCommand::parse_from(["export", "--addr", "127.0.0.1:4000"]);
1100
1101        let result = cmd.build().await;
1102        assert!(result.is_err());
1103        if let Err(err) = result {
1104            assert!(
1105                err.to_string().contains("Output directory not set"),
1106                "Actual error: {}",
1107                err
1108            );
1109        }
1110    }
1111
1112    #[tokio::test]
1113    async fn test_export_command_build_with_s3_minimal_config() {
1114        // S3 with only required fields (no optional fields)
1115        let cmd = ExportCommand::parse_from([
1116            "export",
1117            "--addr",
1118            "127.0.0.1:4000",
1119            "--s3",
1120            "--s3-bucket",
1121            "test-bucket",
1122            "--s3-access-key-id",
1123            "test-key",
1124            "--s3-secret-access-key",
1125            "test-secret",
1126            "--s3-region",
1127            "us-west-2",
1128            // No root, endpoint, or enable_virtual_host_style
1129        ]);
1130
1131        let result = cmd.build().await;
1132        assert!(result.is_ok(), "Minimal S3 config should succeed");
1133    }
1134
1135    #[tokio::test]
1136    async fn test_export_command_build_with_oss_minimal_config() {
1137        // OSS with only required fields
1138        let cmd = ExportCommand::parse_from([
1139            "export",
1140            "--addr",
1141            "127.0.0.1:4000",
1142            "--oss",
1143            "--oss-bucket",
1144            "test-bucket",
1145            "--oss-access-key-id",
1146            "test-key-id",
1147            "--oss-access-key-secret",
1148            "test-secret",
1149            "--oss-endpoint",
1150            "https://oss.example.com",
1151            // No root
1152        ]);
1153
1154        let result = cmd.build().await;
1155        assert!(result.is_ok(), "Minimal OSS config should succeed");
1156    }
1157
1158    #[tokio::test]
1159    async fn test_export_command_build_with_gcs_minimal_config() {
1160        // GCS with only required fields (using ADC)
1161        let cmd = ExportCommand::parse_from([
1162            "export",
1163            "--addr",
1164            "127.0.0.1:4000",
1165            "--gcs",
1166            "--gcs-bucket",
1167            "test-bucket",
1168            "--gcs-root",
1169            "test-root",
1170            "--gcs-scope",
1171            "test-scope",
1172            // No credential, or endpoint
1173        ]);
1174
1175        let result = cmd.build().await;
1176        assert!(result.is_ok(), "Minimal GCS config should succeed");
1177    }
1178
1179    #[tokio::test]
1180    async fn test_export_command_build_with_azblob_minimal_config() {
1181        // Azure Blob with only required fields
1182        let cmd = ExportCommand::parse_from([
1183            "export",
1184            "--addr",
1185            "127.0.0.1:4000",
1186            "--azblob",
1187            "--azblob-container",
1188            "test-container",
1189            "--azblob-endpoint",
1190            "https://account.blob.core.windows.net",
1191        ]);
1192
1193        let result = cmd.build().await;
1194        assert!(result.is_ok(), "Minimal AzBlob config should succeed");
1195    }
1196
1197    #[tokio::test]
1198    async fn test_export_command_build_with_azblob_missing_endpoint() {
1199        let cmd = ExportCommand::parse_from([
1200            "export",
1201            "--addr",
1202            "127.0.0.1:4000",
1203            "--azblob",
1204            "--azblob-container",
1205            "test-container",
1206        ]);
1207
1208        let result = cmd.build().await;
1209        assert!(result.is_err());
1210        if let Err(err) = result {
1211            assert!(
1212                err.to_string().contains("AzBlob endpoint must be set"),
1213                "Actual error: {}",
1214                err
1215            );
1216        }
1217    }
1218
1219    #[tokio::test]
1220    async fn test_export_command_build_with_azblob_missing_container() {
1221        let cmd = ExportCommand::parse_from([
1222            "export",
1223            "--addr",
1224            "127.0.0.1:4000",
1225            "--azblob",
1226            "--azblob-endpoint",
1227            "https://account.blob.core.windows.net",
1228        ]);
1229
1230        let result = cmd.build().await;
1231        assert!(result.is_err());
1232        if let Err(err) = result {
1233            assert!(
1234                err.to_string().contains("AzBlob container must be set"),
1235                "Actual error: {}",
1236                err
1237            );
1238        }
1239    }
1240
1241    #[tokio::test]
1242    async fn test_export_command_build_with_local_and_s3() {
1243        // Both output-dir and S3 - S3 should take precedence
1244        let temp_dir = create_temp_dir("test_export_local_and_s3");
1245        let output_dir = temp_dir.path().to_str().unwrap();
1246
1247        let cmd = ExportCommand::parse_from([
1248            "export",
1249            "--addr",
1250            "127.0.0.1:4000",
1251            "--output-dir",
1252            output_dir,
1253            "--s3",
1254            "--s3-bucket",
1255            "test-bucket",
1256            "--s3-access-key-id",
1257            "test-key",
1258            "--s3-secret-access-key",
1259            "test-secret",
1260            "--s3-region",
1261            "us-west-2",
1262        ]);
1263
1264        let result = cmd.build().await;
1265        assert!(
1266            result.is_ok(),
1267            "S3 should be selected when both are provided"
1268        );
1269    }
1270
1271    // ==================== Gap 4: Custom validation (Azure Blob) ====================
1272
1273    #[tokio::test]
1274    async fn test_export_command_build_with_azblob_only_sas_token() {
1275        // Azure Blob with sas_token but no credentials - should still succeed
1276        let cmd = ExportCommand::parse_from([
1277            "export",
1278            "--addr",
1279            "127.0.0.1:4000",
1280            "--azblob",
1281            "--azblob-container",
1282            "test-container",
1283            "--azblob-endpoint",
1284            "https://account.blob.core.windows.net",
1285            "--azblob-sas-token",
1286            "test-sas-token",
1287        ]);
1288
1289        let result = cmd.build().await;
1290        assert!(
1291            result.is_ok(),
1292            "AzBlob with only sas_token should succeed: {:?}",
1293            result.err()
1294        );
1295    }
1296
1297    #[tokio::test]
1298    async fn test_export_command_build_with_azblob_empty_account_key_with_sas() {
1299        // Azure Blob with empty account_key but valid sas_token - should succeed
1300        let cmd = ExportCommand::parse_from([
1301            "export",
1302            "--addr",
1303            "127.0.0.1:4000",
1304            "--azblob",
1305            "--azblob-container",
1306            "test-container",
1307            "--azblob-account-key",
1308            "", // Empty account_key is OK if sas_token is provided
1309            "--azblob-endpoint",
1310            "https://account.blob.core.windows.net",
1311            "--azblob-sas-token",
1312            "test-sas-token",
1313        ]);
1314
1315        let result = cmd.build().await;
1316        assert!(
1317            result.is_ok(),
1318            "AzBlob with empty account_key but sas_token should succeed: {:?}",
1319            result.err()
1320        );
1321    }
1322}