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
//! Command and query parser for mongosh
//!
//! This module provides a comprehensive parsing system for MongoDB shell commands
//! using a custom AST parser for MongoDB shell syntax and SQL query support.
//!
//! # Architecture
//!
//! The parser is split into multiple focused modules:
//! - `command`: Command type definitions (Command, QueryCommand, AdminCommand, etc.)
//! - `mongo_ast`: MongoDB shell AST structures
//! - `mongo_lexer`: MongoDB shell lexer for tokenization
//! - `mongo_parser`: MongoDB shell parser
//! - `mongo_operation`: Parser for db.collection.operation() syntax
//! - `mongo_converter`: MongoDB expression to BSON converter
//! - `shell_commands`: Parser for shell commands (show, use, help, etc.)
//! - `sql_*`: SQL query parsing modules
//!
//! # Examples
//!
//! ```no_run
//! use mongosh::parser::Parser;
//!
//! let mut parser = Parser::new();
//!
//! // Parse a find query
//! let cmd = parser.parse("db.users.find({ age: { $gt: 18 } })").unwrap();
//!
//! // Parse a shell command
//! let cmd = parser.parse("show dbs").unwrap();
//!
//! // Parse an aggregation
//! let cmd = parser.parse("db.logs.aggregate([{ $match: {} }])").unwrap();
//! ```

mod command;
mod mongo_ast;
mod mongo_converter;
mod mongo_lexer;
mod mongo_operation;
mod mongo_parser;
mod shell_commands;
mod sql_context;
mod sql_expr;
mod sql_lexer;
mod sql_parser;

// Re-export public API
pub use command::*;
pub use mongo_lexer::{MongoLexer, MongoToken, MongoTokenKind};
pub use sql_lexer::{SqlLexer, Token as SqlToken, TokenKind as SqlTokenKind};

use crate::error::{ParseError, Result};

/// Main parser for mongosh commands
///
/// This parser handles all types of MongoDB shell commands including:
/// - Database operations (CRUD, aggregation, etc.)
/// - Administrative commands (show, use, create, drop, etc.)
/// - Utility commands (print, help, etc.)
/// - Script execution
pub struct Parser {}

impl Parser {
    /// Create a new parser instance
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use mongosh::parser::Parser;
    ///
    /// let parser = Parser::new();
    /// ```
    pub fn new() -> Self {
        Self {}
    }

    /// Parse an input string into a Command
    ///
    /// This is the main entry point for parsing. It automatically detects
    /// the type of command and routes to the appropriate parser.
    ///
    /// # Arguments
    ///
    /// * `input` - The input string to parse
    ///
    /// # Returns
    ///
    /// * `Result<Command>` - The parsed command or an error
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use mongosh::parser::Parser;
    ///
    /// let mut parser = Parser::new();
    ///
    /// // Parse a query
    /// let cmd = parser.parse("db.users.find({ name: 'Alice' })").unwrap();
    ///
    /// // Parse a shell command
    /// let cmd = parser.parse("show collections").unwrap();
    /// ```
    pub fn parse(&mut self, input: &str) -> Result<Command> {
        // Trim whitespace and trailing semicolons
        let trimmed = input.trim().trim_end_matches(';').trim();

        // Handle empty input
        if trimmed.is_empty() {
            return Err(ParseError::InvalidCommand("Empty input".to_string()).into());
        }

        // Check for pipe operator |>
        if let Some(pipe_idx) = trimmed.find("|>") {
            let base_part = trimmed[..pipe_idx].trim();
            let pipe_part = trimmed[pipe_idx + 2..].trim();

            // Parse the base command
            let base_cmd = self.parse(base_part)?;

            // Parse the pipe command
            let pipe_cmd = self.parse_pipe_command(pipe_part)?;

            return Ok(Command::Pipe(Box::new(base_cmd), pipe_cmd));
        }

        // Check if it's a SQL SELECT command
        if sql_parser::SqlParser::is_sql_command(trimmed) {
            return sql_parser::SqlParser::parse_to_command(trimmed);
        }

        // Check if it's a shell command (show, use, help, exit, quit)
        if shell_commands::ShellCommandParser::is_shell_command(trimmed) {
            return shell_commands::ShellCommandParser::parse(trimmed);
        }

        // Check if it's a database operation (db.collection.operation)
        if trimmed.starts_with("db.") {
            return mongo_operation::DbOperationParser::parse(trimmed);
        }

        // If nothing matches, it's an invalid command
        Err(ParseError::InvalidCommand(trimmed.to_string()).into())
    }

    /// Parse pipe command (export or explain)
    fn parse_pipe_command(&self, input: &str) -> Result<PipeCommand> {
        let parts: Vec<&str> = input.split_whitespace().collect();

        if parts.is_empty() {
            return Err(ParseError::InvalidCommand("Empty pipe command".to_string()).into());
        }

        match parts[0] {
            "explain" => Ok(PipeCommand::Explain),
            "export" => {
                if parts.len() < 2 {
                    return Err(ParseError::InvalidCommand(
                        "export requires a format (jsonl or csv)".to_string(),
                    )
                    .into());
                }

                let format = match parts[1] {
                    "jsonl" | "json" => ExportFormat::JsonL,
                    "csv" => ExportFormat::Csv,
                    other => {
                        return Err(ParseError::InvalidCommand(format!(
                            "Unknown export format: {}. Use jsonl or csv",
                            other
                        ))
                        .into());
                    }
                };

                let file = if parts.len() > 2 {
                    Some(parts[2].to_string())
                } else {
                    None
                };

                Ok(PipeCommand::Export { format, file })
            }
            other => Err(
                ParseError::InvalidCommand(format!("Unknown pipe command '{}'", other)).into(),
            ),
        }
    }
}

impl Default for Parser {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parser_creation() {
        let _parser = Parser::new();
        // Parser created successfully
    }

    #[test]
    fn test_parse_exit() {
        let mut parser = Parser::new();
        let cmd = parser.parse("exit").unwrap();
        assert!(matches!(cmd, Command::Exit));

        let cmd = parser.parse("quit").unwrap();
        assert!(matches!(cmd, Command::Exit));
    }

    #[test]
    fn test_parse_help() {
        let mut parser = Parser::new();
        let cmd = parser.parse("help").unwrap();
        assert!(matches!(cmd, Command::Help(None)));

        let cmd = parser.parse("help find").unwrap();
        assert!(matches!(cmd, Command::Help(Some(_))));
    }

    #[test]
    fn test_parse_show_databases() {
        let mut parser = Parser::new();
        let cmd = parser.parse("show dbs").unwrap();
        assert!(matches!(cmd, Command::Admin(AdminCommand::ShowDatabases)));

        let cmd = parser.parse("show databases").unwrap();
        assert!(matches!(cmd, Command::Admin(AdminCommand::ShowDatabases)));
    }

    #[test]
    fn test_parse_show_collections() {
        let mut parser = Parser::new();
        let cmd = parser.parse("show collections").unwrap();
        assert!(matches!(cmd, Command::Admin(AdminCommand::ShowCollections)));
    }

    #[test]
    fn test_parse_use_database() {
        let mut parser = Parser::new();
        let cmd = parser.parse("use mydb").unwrap();
        if let Command::Admin(AdminCommand::UseDatabase(name)) = cmd {
            assert_eq!(name, "mydb");
        } else {
            panic!("Expected UseDatabase command");
        }
    }

    #[test]
    fn test_parse_find_empty() {
        let mut parser = Parser::new();
        let cmd = parser.parse("db.users.find()").unwrap();
        if let Command::Query(QueryCommand::Find {
            collection, filter, ..
        }) = cmd
        {
            assert_eq!(collection, "users");
            assert!(filter.is_empty());
        } else {
            panic!("Expected Find command");
        }
    }

    #[test]
    fn test_parse_find_with_filter() {
        let mut parser = Parser::new();
        let cmd = parser.parse("db.users.find({ age: 25 })").unwrap();
        if let Command::Query(QueryCommand::Find {
            collection, filter, ..
        }) = cmd
        {
            assert_eq!(collection, "users");
            assert_eq!(filter.get_i64("age").unwrap(), 25);
        } else {
            panic!("Expected Find command");
        }
    }

    #[test]
    fn test_parse_find_with_operators() {
        let mut parser = Parser::new();
        let cmd = parser.parse("db.users.find({ age: { $gt: 18 } })").unwrap();
        if let Command::Query(QueryCommand::Find {
            collection, filter, ..
        }) = cmd
        {
            assert_eq!(collection, "users");
            let age_cond = filter.get_document("age").unwrap();
            assert_eq!(age_cond.get_i64("$gt").unwrap(), 18);
        } else {
            panic!("Expected Find command");
        }
    }

    #[test]
    fn test_parse_insert_one() {
        let mut parser = Parser::new();
        let cmd = parser
            .parse("db.users.insertOne({ name: 'Alice', age: 30 })")
            .unwrap();
        if let Command::Query(QueryCommand::InsertOne {
            collection,
            document,
        }) = cmd
        {
            assert_eq!(collection, "users");
            assert_eq!(document.get_str("name").unwrap(), "Alice");
            assert_eq!(document.get_i64("age").unwrap(), 30);
        } else {
            panic!("Expected InsertOne command");
        }
    }

    #[test]
    fn test_parse_insert_many() {
        let mut parser = Parser::new();
        let cmd = parser
            .parse("db.users.insertMany([{ name: 'Alice' }, { name: 'Bob' }])")
            .unwrap();
        if let Command::Query(QueryCommand::InsertMany {
            collection,
            documents,
        }) = cmd
        {
            assert_eq!(collection, "users");
            assert_eq!(documents.len(), 2);
        } else {
            panic!("Expected InsertMany command");
        }
    }

    #[test]
    fn test_parse_update_one() {
        let mut parser = Parser::new();
        let cmd = parser
            .parse("db.users.updateOne({ name: 'Alice' }, { $set: { age: 31 } })")
            .unwrap();
        if let Command::Query(QueryCommand::UpdateOne {
            collection,
            filter,
            update,
            ..
        }) = cmd
        {
            assert_eq!(collection, "users");
            assert_eq!(filter.get_str("name").unwrap(), "Alice");
            let set_doc = update.get_document("$set").unwrap();
            assert_eq!(set_doc.get_i64("age").unwrap(), 31);
        } else {
            panic!("Expected UpdateOne command");
        }
    }

    #[test]
    fn test_parse_delete_one() {
        let mut parser = Parser::new();
        let cmd = parser
            .parse("db.users.deleteOne({ name: 'Alice' })")
            .unwrap();
        if let Command::Query(QueryCommand::DeleteOne {
            collection, filter, ..
        }) = cmd
        {
            assert_eq!(collection, "users");
            assert_eq!(filter.get_str("name").unwrap(), "Alice");
        } else {
            panic!("Expected DeleteOne command");
        }
    }

    #[test]
    fn test_parse_aggregate() {
        let mut parser = Parser::new();
        let cmd = parser
            .parse("db.users.aggregate([{ $match: { age: { $gt: 18 } } }])")
            .unwrap();
        if let Command::Query(QueryCommand::Aggregate {
            collection,
            pipeline,
            ..
        }) = cmd
        {
            assert_eq!(collection, "users");
            assert_eq!(pipeline.len(), 1);
        } else {
            panic!("Expected Aggregate command");
        }
    }

    #[test]
    fn test_parse_empty_input() {
        let mut parser = Parser::new();
        assert!(parser.parse("").is_err());
        assert!(parser.parse("   ").is_err());
        assert!(parser.parse(";;;").is_err());
    }

    #[test]
    fn test_parse_invalid_command() {
        let mut parser = Parser::new();
        assert!(parser.parse("invalid command").is_err());
        assert!(parser.parse("db.users.invalidOp()").is_err());
    }

    #[test]
    fn test_parse_with_semicolon() {
        let mut parser = Parser::new();
        let cmd = parser.parse("db.users.find();").unwrap();
        assert!(matches!(cmd, Command::Query(QueryCommand::Find { .. })));
    }

    #[test]
    fn test_parse_chained_limit() {
        let mut parser = Parser::new();
        let cmd = parser.parse("db.users.find().limit(1)").unwrap();
        if let Command::Query(QueryCommand::Find { options, .. }) = cmd {
            assert_eq!(options.limit, Some(1));
        } else {
            panic!("Expected Find command");
        }
    }

    #[test]
    fn test_parse_chained_skip_and_limit() {
        let mut parser = Parser::new();
        let cmd = parser
            .parse("db.users.find({ age: { $gt: 18 } }).limit(10).skip(5)")
            .unwrap();
        if let Command::Query(QueryCommand::Find {
            filter, options, ..
        }) = cmd
        {
            assert_eq!(options.limit, Some(10));
            assert_eq!(options.skip, Some(5));
            let age_cond = filter.get_document("age").unwrap();
            assert_eq!(age_cond.get_i64("$gt").unwrap(), 18);
        } else {
            panic!("Expected Find command");
        }
    }

    #[test]
    fn test_parse_chained_sort() {
        let mut parser = Parser::new();
        let cmd = parser
            .parse("db.users.find().sort({ name: 1, age: -1 })")
            .unwrap();
        if let Command::Query(QueryCommand::Find { options, .. }) = cmd {
            assert!(options.sort.is_some());
            let sort = options.sort.unwrap();
            assert_eq!(sort.get_i64("name").unwrap(), 1);
            assert_eq!(sort.get_i64("age").unwrap(), -1);
        } else {
            panic!("Expected Find command");
        }
    }

    #[test]
    fn test_parse_complex_chained_query() {
        let mut parser = Parser::new();
        let cmd = parser
            .parse("db.products.find({ category: 'electronics' }).sort({ price: -1 }).limit(20).skip(10)")
            .unwrap();
        if let Command::Query(QueryCommand::Find {
            collection,
            filter,
            options,
        }) = cmd
        {
            assert_eq!(collection, "products");
            assert_eq!(filter.get_str("category").unwrap(), "electronics");
            assert_eq!(options.limit, Some(20));
            assert_eq!(options.skip, Some(10));
            assert!(options.sort.is_some());
        } else {
            panic!("Expected Find command");
        }
    }
}