mongosh 0.9.0

A high-performance MongoDB Shell implementation in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
//! Command router for dispatching commands to executors
//!
//! This module provides the CommandRouter which dispatches parsed commands
//! to the appropriate executor based on command type:
//! - Query commands → QueryExecutor
//! - Admin commands → AdminExecutor
//! - Utility commands → UtilityExecutor

use std::collections::HashMap;
use std::fs;
use std::time::Instant;
use tabled::{builder::Builder, settings::Style};
use tracing::debug;

use crate::config::{Config, OutputFormat};
use crate::error::{ExecutionError, Result};
use crate::parser::{Command, ConfigCommand, ExportFormat, PipeCommand, QueryMode};

use super::admin::AdminExecutor;
use super::context::ExecutionContext;
use super::export::{CsvWriter, ExportCoordinator, FormatWriter, JsonLWriter, ProgressTracker};
use super::query::QueryExecutor;
use super::result::{ExecutionResult, ExecutionStats, ResultData};
use super::utility::UtilityExecutor;

/// Command router that dispatches commands to appropriate executors
pub struct CommandRouter {
    /// Execution context
    context: ExecutionContext,
}

impl CommandRouter {
    /// Create a new command router
    ///
    /// # Arguments
    /// * `context` - Execution context
    ///
    /// # Returns
    /// * `Result<Self>` - New router or error
    pub async fn new(context: ExecutionContext) -> Result<Self> {
        Ok(Self { context })
    }

    /// Route command to appropriate executor
    ///
    /// # Arguments
    /// * `command` - Parsed command
    ///
    /// # Returns
    /// * `Result<ExecutionResult>` - Execution result or error
    pub async fn route(&self, command: Command) -> Result<ExecutionResult> {
        debug!("Routing command: {:?}", command);

        let start = Instant::now();

        let result = match command {
            Command::Query(query_cmd) => {
                let executor = QueryExecutor::new(self.context.clone()).await?;
                executor.execute(query_cmd, QueryMode::default()).await
            }
            Command::Admin(admin_cmd) => {
                let executor = AdminExecutor::new(self.context.clone()).await?;
                executor.execute(admin_cmd).await
            }
            Command::Utility(util_cmd) => {
                let executor = UtilityExecutor::new(self.context.clone());
                executor.execute(util_cmd).await
            }
            Command::Config(config_cmd) => self.execute_config(config_cmd).await,
            Command::Pipe(base_cmd, pipe_cmd) => self.execute_pipe(*base_cmd, pipe_cmd).await,
            Command::Help(topic) => self.execute_help(topic).await,
            Command::Exit => Ok(ExecutionResult {
                success: true,
                data: ResultData::Message("Exiting...".to_string()),
                stats: ExecutionStats::default(),
                error: None,
            }),
        };

        let elapsed = start.elapsed().as_millis() as u64;
        debug!("Command executed in {}ms", elapsed);

        result
    }

    /// Execute piped command (query |> export/explain)
    ///
    /// # Arguments
    /// * `base_cmd` - Base command to execute
    /// * `pipe_cmd` - Pipe operation to apply
    ///
    /// # Returns
    /// * `Result<ExecutionResult>` - Execution result or error
    fn execute_pipe(
        &self,
        base_cmd: Command,
        pipe_cmd: PipeCommand,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ExecutionResult>> + Send + '_>>
    {
        Box::pin(async move {
            match pipe_cmd {
                PipeCommand::Export { format, file } => {
                    // Execute query in streaming mode for export
                    let result = if let Command::Query(query_cmd) = base_cmd {
                        let executor = QueryExecutor::new(self.context.clone()).await?;
                        executor.execute(query_cmd, QueryMode::Streaming { batch_size: 1000 }).await?
                    } else {
                        return Err(ExecutionError::InvalidOperation(
                            "Export can only be used with query commands".to_string()
                        ).into());
                    };

                    // Extract streaming query from result
                    let query = match result.data {
                        ResultData::Stream(stream) => stream,
                        _ => {
                            return Err(ExecutionError::InvalidOperation(
                                "Query did not return streaming data for export".to_string()
                            ).into());
                        }
                    };

                    // Generate filename if not provided
                    let filename = file.unwrap_or_else(|| {
                        use chrono::Local;
                        let timestamp = Local::now().format("%Y-%m-%d_%H-%M-%S");
                        match format {
                            ExportFormat::JsonL => format!("export-{}.jsonl", timestamp),
                            ExportFormat::Csv => format!("export-{}.csv", timestamp),
                        }
                    });

                    // Create format writer
                    let writer: Box<dyn FormatWriter> = match format {
                        ExportFormat::JsonL => Box::new(JsonLWriter::new(&filename).await?),
                        ExportFormat::Csv => Box::new(CsvWriter::new(&filename).await?),
                    };

                    // Create progress tracker
                    let tracker = ProgressTracker::new(None, true);

                    // Create cancellation token and setup Ctrl+C handler
                    let cancel_token = tokio_util::sync::CancellationToken::new();
                    let cancel_token_clone = cancel_token.clone();

                    // Setup Ctrl+C handler for cancellation
                    tokio::spawn(async move {
                        match tokio::signal::ctrl_c().await {
                            Ok(()) => {
                                cancel_token_clone.cancel();
                            }
                            Err(err) => {
                                eprintln!("Failed to listen for Ctrl+C: {}", err);
                            }
                        }
                    });

                    // Create coordinator and execute export with cancellation support
                    let mut coordinator = ExportCoordinator::new(query, tracker, writer)
                        .with_cancellation(cancel_token);
                    let export_result = coordinator.execute().await?;

                    // Format result message based on cancellation status
                    let message = if export_result.cancelled {
                        format!(
                            "Export cancelled. Exported {} documents to {} ({:.2} MB) before cancellation",
                            export_result.documents_exported,
                            filename,
                            export_result.file_size_bytes as f64 / 1024.0 / 1024.0
                        )
                    } else {
                        format!(
                            "Exported {} documents to {} ({:.2} MB) in {:.2}s",
                            export_result.documents_exported,
                            filename,
                            export_result.file_size_bytes as f64 / 1024.0 / 1024.0,
                            export_result.elapsed_ms as f64 / 1000.0
                        )
                    };

                    Ok(ExecutionResult {
                        success: true,
                        data: ResultData::Message(message),
                        stats: ExecutionStats {
                            execution_time_ms: export_result.elapsed_ms,
                            documents_returned: 0,
                            documents_affected: Some(export_result.documents_exported),
                        },
                        error: None,
                    })
                }
                PipeCommand::Explain => {
                    // Execute base command normally for explain
                    let result = self.route(base_cmd).await?;

                    // For explain, we would need to execute the query with explain flag
                    // This is a placeholder for now
                    Ok(ExecutionResult {
                        success: true,
                        data: ResultData::Message(
                            "Explain functionality not yet implemented".to_string(),
                        ),
                        stats: result.stats,
                        error: None,
                    })
                }
            }
        })
    }

    /// Execute help command
    ///
    /// # Arguments
    /// * `topic` - Optional help topic
    ///
    /// # Returns
    /// * `Result<ExecutionResult>` - Help text
    async fn execute_help(&self, topic: Option<String>) -> Result<ExecutionResult> {
        let help_text = if let Some(t) = topic {
            format!("Help for: {}\n(Not yet implemented)", t)
        } else {
            r#"MongoDB Shell Commands:

Configuration:
  format [shell|json|json-pretty|table|compact] - Set/get output format
  color [on|off]                                - Enable/disable color output
  config                                        - Show current configuration

Named Queries:
  query                                       - List all named queries
  query <name> [args...]                      - Execute a named query with arguments
  query save <name> <query>                   - Save a new named query
  query delete <name>                         - Delete a named query

  Parameter substitution:
    '$1', '$2'...                             - String parameters (with quotes in template)
    $1, $2...                                 - Numeric/raw parameters (no quotes in template)
    $*                                        - Raw aggregation: 18, 25, 30
    $@                                        - String aggregation: 'admin', 'user'

  Examples:
    query save user "db.users.find({name: '\$1', age: \$2})"
    query user John 25                        -> {name: 'John', age: 25}

Utility:
  help                                        - Show this help
  help <command>                              - Show help for specific command
  exit / quit                                 - Exit shell
"#
            .to_string()
        };

        Ok(ExecutionResult {
            success: true,
            data: ResultData::Message(help_text),
            stats: ExecutionStats::default(),
            error: None,
        })
    }

    /// Execute config command
    ///
    /// # Arguments
    /// * `cmd` - Config command to execute
    ///
    /// # Returns
    /// * `Result<ExecutionResult>` - Config result
    async fn execute_config(&self, cmd: ConfigCommand) -> Result<ExecutionResult> {
        let shared_state = &self.context.shared_state;

        let message = match cmd {
            ConfigCommand::SetFormat(format_str) => {
                let format = match format_str.to_lowercase().as_str() {
                    "shell" => OutputFormat::Shell,
                    "json" => OutputFormat::Json,
                    "json-pretty" | "jsonpretty" => OutputFormat::JsonPretty,
                    "table" => OutputFormat::Table,
                    "compact" => OutputFormat::Compact,
                    _ => {
                        return Ok(ExecutionResult {
                            success: false,
                            data: ResultData::Message(format!(
                                "Invalid format: '{}'\n\nSupported formats: shell, json, json-pretty, table, compact",
                                format_str
                            )),
                            stats: ExecutionStats::default(),
                            error: Some("Invalid format".to_string()),
                        });
                    }
                };

                shared_state.set_format(format);
                format!("Output format set to: {}", format_str)
            }
            ConfigCommand::GetFormat => {
                let format = shared_state.get_format();
                let format_str = match format {
                    OutputFormat::Shell => "shell",
                    OutputFormat::Json => "json",
                    OutputFormat::JsonPretty => "json-pretty",
                    OutputFormat::Table => "table",
                    OutputFormat::Compact => "compact",
                };
                format!(
                    "Current format: {}\n\nSupported formats: shell, json, json-pretty, table, compact",
                    format_str
                )
            }
            ConfigCommand::SetColor(enabled) => {
                shared_state.set_color_enabled(enabled);
                format!(
                    "Color output {}",
                    if enabled { "enabled" } else { "disabled" }
                )
            }
            ConfigCommand::GetColor => {
                let enabled = shared_state.get_color_enabled();
                format!(
                    "Color output: {}",
                    if enabled { "enabled" } else { "disabled" }
                )
            }
            ConfigCommand::ShowConfig => {
                let format = shared_state.get_format();
                let format_str = match format {
                    OutputFormat::Shell => "shell",
                    OutputFormat::Json => "json",
                    OutputFormat::JsonPretty => "json-pretty",
                    OutputFormat::Table => "table",
                    OutputFormat::Compact => "compact",
                };
                let color = if shared_state.get_color_enabled() {
                    "enabled"
                } else {
                    "disabled"
                };

                format!(
                    r#"Current Configuration:
  format: {}
  color: {}

Available Commands:
  format [shell|json|json-pretty|table|compact]   - Set/get output format
  color [on|off]                                  - Set/get color output
  config                                          - Show this configuration"#,
                    format_str, color
                )
            }
            ConfigCommand::ListNamedQueries => {
                return self.list_named_query().await;
            }
            ConfigCommand::ExecuteNamedQuery { name, args } => {
                return self.execute_named_query(&name, &args).await;
            }
            ConfigCommand::SaveNamedQuery { name, query } => {
                return self.save_named_query(&name, &query).await;
            }
            ConfigCommand::DeleteNamedQuery(name) => {
                return self.delete_named_query(&name).await;
            }
        };

        Ok(ExecutionResult {
            success: true,
            data: ResultData::Message(message),
            stats: ExecutionStats::default(),
            error: None,
        })
    }

    /// Load named query from config file
    async fn load_named_query(&self) -> Result<HashMap<String, String>> {
        let config_path = self
            .context
            .config_path
            .as_ref()
            .map(|p| p.clone())
            .unwrap_or_else(|| Config::default_config_path());

        if !config_path.exists() {
            return Ok(HashMap::new());
        }

        let content = fs::read_to_string(&config_path).map_err(|e| {
            crate::error::MongoshError::Config(crate::error::ConfigError::Generic(format!(
                "Failed to read config file: {}",
                e
            )))
        })?;

        let config: Config = toml::from_str(&content).map_err(|e| {
            crate::error::MongoshError::Config(crate::error::ConfigError::Generic(format!(
                "Failed to parse config file: {}",
                e
            )))
        })?;

        Ok(config.named_query)
    }

    /// Save config with updated named query
    async fn save_config_with_query(&self, query: HashMap<String, String>) -> Result<()> {
        let config_path = self
            .context
            .config_path
            .as_ref()
            .map(|p| p.clone())
            .unwrap_or_else(|| Config::default_config_path());

        let mut config = if config_path.exists() {
            let content = fs::read_to_string(&config_path).map_err(|e| {
                crate::error::MongoshError::Config(crate::error::ConfigError::Generic(format!(
                    "Failed to read config file: {}",
                    e
                )))
            })?;
            toml::from_str(&content).unwrap_or_else(|_| Config::default())
        } else {
            Config::default()
        };

        config.named_query = query;
        config.save_to_file(Some(&config_path))?;

        Ok(())
    }

    /// List all named query
    async fn list_named_query(&self) -> Result<ExecutionResult> {
        let query = self.load_named_query().await?;

        if query.is_empty() {
            return Ok(ExecutionResult {
                success: true,
                data: ResultData::Message("No named queries defined.".to_string()),
                stats: ExecutionStats::default(),
                error: None,
            });
        }

        // Build table using tabled library
        let mut builder = Builder::default();

        // Add header row
        builder.push_record(vec!["Name", "Query"]);

        // Add data rows
        for (name, q) in query.iter() {
            builder.push_record(vec![name.as_str(), q.as_str()]);
        }

        let mut table = builder.build();
        table.with(Style::ascii());

        Ok(ExecutionResult {
            success: true,
            data: ResultData::Message(table.to_string()),
            stats: ExecutionStats::default(),
            error: None,
        })
    }

    /// Execute a named query with parameter substitution
    async fn execute_named_query(&self, name: &str, args: &[String]) -> Result<ExecutionResult> {
        let query = self.load_named_query().await?;

        let query_template = query.get(name).ok_or_else(|| {
            crate::error::MongoshError::Config(crate::error::ConfigError::Generic(format!(
                "Named query '{}' not found",
                name
            )))
        })?;

        // Substitute parameters
        let substituted_query = self.substitute_parameters(query_template, args);

        // Parse and execute the query
        let mut parser = crate::parser::Parser::new();
        let command = parser.parse(&substituted_query)?;
        Box::pin(self.route(command)).await
    }

    /// Substitute parameters in query template
    fn substitute_parameters(&self, template: &str, args: &[String]) -> String {
        let mut result = template.to_string();

        // First, handle positional parameters ($1, $2, $3, etc.)
        // We need to be careful about whether the parameter is in quotes or not
        for (i, arg) in args.iter().enumerate() {
            let placeholder = format!("${}", i + 1);
            let quoted_placeholder = format!("'{}'", placeholder);
            let double_quoted_placeholder = format!("\"{}\"", placeholder);

            // If parameter is in quotes, keep it as string (remove the placeholder quotes)
            if result.contains(&quoted_placeholder) {
                result = result.replace(&quoted_placeholder, &format!("'{}'", arg));
            } else if result.contains(&double_quoted_placeholder) {
                result = result.replace(&double_quoted_placeholder, &format!("\"{}\"", arg));
            } else {
                // Not in quotes - use raw value (could be number or unquoted string)
                result = result.replace(&placeholder, arg);
            }
        }

        // Then handle aggregation parameters
        if result.contains("$@") {
            // String aggregation: quote each argument
            let quoted_args: Vec<String> = args.iter().map(|s| format!("'{}'", s)).collect();
            let aggregated = quoted_args.join(", ");
            result = result.replace("$@", &aggregated);
        }

        if result.contains("$*") {
            // Raw aggregation: no quotes (for numeric arrays)
            let aggregated = args.join(", ");
            result = result.replace("$*", &aggregated);
        }

        result
    }

    /// Save a named query
    async fn save_named_query(&self, name: &str, query: &str) -> Result<ExecutionResult> {
        let mut query_map = self.load_named_query().await?;
        query_map.insert(name.to_string(), query.to_string());
        self.save_config_with_query(query_map).await?;

        Ok(ExecutionResult {
            success: true,
            data: ResultData::Message(format!("Named query '{}' saved", name)),
            stats: ExecutionStats::default(),
            error: None,
        })
    }

    /// Delete a named query
    async fn delete_named_query(&self, name: &str) -> Result<ExecutionResult> {
        let mut query = self.load_named_query().await?;

        if query.remove(name).is_none() {
            return Ok(ExecutionResult {
                success: false,
                data: ResultData::Message(format!("Named query '{}' not found", name)),
                stats: ExecutionStats::default(),
                error: Some(format!("Query '{}' does not exist", name)),
            });
        }

        self.save_config_with_query(query).await?;

        Ok(ExecutionResult {
            success: true,
            data: ResultData::Message(format!("{}: Deleted", name)),
            stats: ExecutionStats::default(),
            error: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_substitute_parameters_with_numbers() {
        let router = CommandRouter {
            context: ExecutionContext::new(
                crate::connection::ConnectionManager::new(
                    "mongodb://localhost:27017".to_string(),
                    crate::config::ConnectionConfig::default(),
                ),
                crate::repl::SharedState::new("test".to_string()),
            ),
        };

        // Numeric parameter without quotes
        let template = "db.users.find({age: $1})";
        let result = router.substitute_parameters(template, &["18".to_string()]);
        assert_eq!(result, "db.users.find({age: 18})");

        // Numeric parameter with quotes (should keep quotes)
        let template = "db.users.find({age: '$1'})";
        let result = router.substitute_parameters(template, &["18".to_string()]);
        assert_eq!(result, "db.users.find({age: '18'})");

        // String parameter with quotes
        let template = "db.users.findOne({name: '$1'})";
        let result = router.substitute_parameters(template, &["davin".to_string()]);
        assert_eq!(result, "db.users.findOne({name: 'davin'})");

        // Multiple parameters mixed (string and number)
        let template = "db.users.find({name: '$1', age: $2})";
        let result =
            router.substitute_parameters(template, &["davin".to_string(), "25".to_string()]);
        assert_eq!(result, "db.users.find({name: 'davin', age: 25})");

        // Complex scenario: multiple mixed types
        let template = "db.users.find({name: '$1', age: $2, city: '$3', active: $4})";
        let result = router.substitute_parameters(
            template,
            &[
                "John".to_string(),
                "30".to_string(),
                "New York".to_string(),
                "true".to_string(),
            ],
        );
        assert_eq!(
            result,
            "db.users.find({name: 'John', age: 30, city: 'New York', active: true})"
        );
    }

    #[test]
    fn test_substitute_parameters_with_aggregation() {
        let router = CommandRouter {
            context: ExecutionContext::new(
                crate::connection::ConnectionManager::new(
                    "mongodb://localhost:27017".to_string(),
                    crate::config::ConnectionConfig::default(),
                ),
                crate::repl::SharedState::new("test".to_string()),
            ),
        };

        // Raw aggregation (numeric)
        let template = "db.users.find({age: {$in: [$*]}})";
        let result = router.substitute_parameters(
            template,
            &["18".to_string(), "25".to_string(), "30".to_string()],
        );
        assert_eq!(result, "db.users.find({age: {$in: [18, 25, 30]}})");

        // String aggregation (quoted)
        let template = "db.users.find({category: {$in: [$@]}})";
        let result =
            router.substitute_parameters(template, &["admin".to_string(), "user".to_string()]);
        assert_eq!(
            result,
            "db.users.find({category: {$in: ['admin', 'user']}})"
        );
    }

    #[tokio::test]
    async fn test_command_router_help() {
        // This is a placeholder test - would need proper setup with ConnectionManager
        // and SharedState to fully test
    }
}