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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! SQL context and AST definitions
//!
//! This module defines the SQL AST (Abstract Syntax Tree) and context
//! models used for parsing, autocomplete, and error reporting.

#![allow(dead_code)]

use std::ops::Range;

/// Field path representation supporting nested fields and array access
#[derive(Debug, Clone, PartialEq)]
pub enum FieldPath {
    /// Simple field: `name`
    Simple(String),

    /// Nested field: `address.city`
    Nested { base: Box<FieldPath>, field: String },

    /// Array index access: `tags[0]` or `tags[-1]`
    ArrayIndex {
        base: Box<FieldPath>,
        index: ArrayIndex,
    },

    /// Array slice: `tags[0:5]` or `tags[:10:2]`
    ArraySlice {
        base: Box<FieldPath>,
        slice: ArraySlice,
    },
}

impl FieldPath {
    /// Create a simple field path
    pub fn simple(name: String) -> Self {
        FieldPath::Simple(name)
    }

    /// Create a nested field path
    pub fn nested(base: FieldPath, field: String) -> Self {
        FieldPath::Nested {
            base: Box::new(base),
            field,
        }
    }

    /// Create an array index path
    pub fn index(base: FieldPath, index: ArrayIndex) -> Self {
        FieldPath::ArrayIndex {
            base: Box::new(base),
            index,
        }
    }

    /// Create an array slice path
    pub fn slice(base: FieldPath, slice: ArraySlice) -> Self {
        FieldPath::ArraySlice {
            base: Box::new(base),
            slice,
        }
    }

    /// Convert to MongoDB dot notation path (for simple cases)
    pub fn to_mongodb_path(&self) -> Option<String> {
        match self {
            FieldPath::Simple(name) => Some(name.clone()),
            FieldPath::Nested { base, field } => {
                base.to_mongodb_path().map(|b| format!("{}.{}", b, field))
            }
            // Array access requires aggregation pipeline
            FieldPath::ArrayIndex { .. } | FieldPath::ArraySlice { .. } => None,
        }
    }

    /// Check if this path requires aggregation pipeline
    pub fn requires_aggregation(&self) -> bool {
        match self {
            FieldPath::Simple(_) => false,
            FieldPath::Nested { base, .. } => base.requires_aggregation(),
            FieldPath::ArrayIndex { .. } | FieldPath::ArraySlice { .. } => true,
        }
    }

    /// Get the base field name (for simple optimization)
    pub fn base_field(&self) -> String {
        match self {
            FieldPath::Simple(name) => name.clone(),
            FieldPath::Nested { base, .. }
            | FieldPath::ArrayIndex { base, .. }
            | FieldPath::ArraySlice { base, .. } => base.base_field(),
        }
    }
}

/// Array index (positive or negative)
#[derive(Debug, Clone, PartialEq)]
pub enum ArrayIndex {
    /// Positive index: `arr[0]`, `arr[5]`
    Positive(i64),

    /// Negative index: `arr[-1]`, `arr[-2]`
    Negative(i64),
}

impl ArrayIndex {
    /// Create a positive index
    pub fn positive(index: i64) -> Self {
        ArrayIndex::Positive(index)
    }

    /// Create a negative index
    pub fn negative(index: i64) -> Self {
        ArrayIndex::Negative(index.abs())
    }

    /// Resolve to MongoDB array index
    pub fn resolve(&self, array_len: Option<usize>) -> Option<usize> {
        match (self, array_len) {
            (ArrayIndex::Positive(idx), _) if *idx >= 0 => Some(*idx as usize),
            (ArrayIndex::Negative(idx), Some(len)) if *idx <= len as i64 => {
                Some(len - (*idx as usize))
            }
            _ => None,
        }
    }
}

/// Array slice specification
#[derive(Debug, Clone, PartialEq)]
pub struct ArraySlice {
    /// Start index (inclusive, optional)
    pub start: Option<SliceIndex>,

    /// End index (exclusive, optional)
    pub end: Option<SliceIndex>,

    /// Step size (default 1)
    pub step: Option<i64>,
}

impl ArraySlice {
    /// Create a new slice
    pub fn new(start: Option<SliceIndex>, end: Option<SliceIndex>, step: Option<i64>) -> Self {
        Self { start, end, step }
    }

    /// Create a full slice `[:]`
    pub fn full() -> Self {
        Self::new(None, None, None)
    }

    /// Create a slice to end `[:n]`
    pub fn to(end: SliceIndex) -> Self {
        Self::new(None, Some(end), None)
    }

    /// Create a slice from start `[n:]`
    pub fn from(start: SliceIndex) -> Self {
        Self::new(Some(start), None, None)
    }
}

/// Slice index (can be positive or negative)
#[derive(Debug, Clone, PartialEq)]
pub enum SliceIndex {
    Positive(i64),
    Negative(i64),
}

/// SQL parsing context - tracks where we are in the parse tree
#[derive(Debug, Clone, PartialEq)]
pub struct SqlContext {
    /// Current SQL clause being parsed
    pub clause: SqlClause,

    /// Current position in the input
    pub position: usize,

    /// What tokens/constructs are expected next
    pub expected: Vec<Expected>,

    /// Partial input being parsed
    pub partial_input: String,
}

impl SqlContext {
    /// Create a new SQL context
    pub fn new(clause: SqlClause, position: usize, expected: Vec<Expected>) -> Self {
        Self {
            clause,
            position,
            expected,
            partial_input: String::new(),
        }
    }
}

/// SQL clause types
#[derive(Debug, Clone, PartialEq)]
pub enum SqlClause {
    /// In SELECT clause
    Select,

    /// In FROM clause
    From,

    /// In WHERE clause
    Where,

    /// In GROUP BY clause
    GroupBy,

    /// In ORDER BY clause
    OrderBy,

    /// In LIMIT clause
    Limit,

    /// In OFFSET clause
    Offset,
}

/// Expected token or construct (for autocomplete and error messages)
#[derive(Debug, Clone, PartialEq)]
pub enum Expected {
    /// Specific keyword
    Keyword(&'static str),

    /// Table/collection name
    TableName,

    /// Column/field name
    ColumnName,

    /// Expression
    Expression,

    /// Operator
    Operator,

    /// Aggregate function (COUNT, SUM, etc.)
    AggregateFunction,

    /// Order direction (ASC/DESC)
    OrderDirection,

    /// Number literal
    Number,

    /// String literal
    String,

    /// Star (*)
    Star,

    /// End of statement
    EndOfStatement,
}

impl Expected {
    /// Convert to human-readable description
    pub fn description(&self) -> &str {
        match self {
            Expected::Keyword(kw) => kw,
            Expected::TableName => "table name",
            Expected::ColumnName => "column name",
            Expected::Expression => "expression",
            Expected::Operator => "operator",
            Expected::AggregateFunction => "aggregate function",
            Expected::OrderDirection => "ASC or DESC",
            Expected::Number => "number",
            Expected::String => "string",
            Expected::Star => "*",
            Expected::EndOfStatement => "end of statement",
        }
    }
}

/// Parse result - can be complete, partial, or error
#[derive(Debug, Clone, PartialEq)]
pub enum ParseResult<T> {
    /// Successful complete parse
    Ok(T),

    /// Partial parse with expectations for completion
    Partial(T, Vec<Expected>),

    /// Parse error
    Error(ParseError),
}

impl<T> ParseResult<T> {
    /// Check if result is ok
    pub fn is_ok(&self) -> bool {
        matches!(self, ParseResult::Ok(_))
    }

    /// Check if result is partial
    pub fn is_partial(&self) -> bool {
        matches!(self, ParseResult::Partial(_, _))
    }

    /// Check if result is error
    pub fn is_error(&self) -> bool {
        matches!(self, ParseResult::Error(_))
    }

    /// Get the value if ok or partial
    pub fn value(self) -> Option<T> {
        match self {
            ParseResult::Ok(v) | ParseResult::Partial(v, _) => Some(v),
            ParseResult::Error(_) => None,
        }
    }
}

/// Parse error with context
#[derive(Debug, Clone, PartialEq)]
pub struct ParseError {
    /// Error message
    pub message: String,

    /// Position in input where error occurred
    pub span: Range<usize>,

    /// What was expected at this position
    pub expected: Vec<Expected>,

    /// Optional hint for fixing the error
    pub hint: Option<String>,
}

impl ParseError {
    /// Create a new parse error
    pub fn new(message: String, span: Range<usize>) -> Self {
        Self {
            message,
            span,
            expected: Vec::new(),
            hint: None,
        }
    }

    /// Create an error with expected tokens
    pub fn with_expected(message: String, span: Range<usize>, expected: Vec<Expected>) -> Self {
        Self {
            message,
            span,
            expected,
            hint: None,
        }
    }

    /// Add a hint to the error
    pub fn with_hint(mut self, hint: String) -> Self {
        self.hint = Some(hint);
        self
    }
}

/// SQL SELECT statement AST
#[derive(Debug, Clone, PartialEq)]
pub struct SqlSelect {
    /// Selected columns
    pub columns: Vec<SqlColumn>,

    /// Table name (optional for partial parses)
    pub table: Option<String>,

    /// WHERE clause filter
    pub where_clause: Option<SqlExpr>,

    /// GROUP BY columns
    pub group_by: Option<Vec<String>>,

    /// ORDER BY clauses
    pub order_by: Option<Vec<SqlOrderBy>>,

    /// LIMIT count
    pub limit: Option<usize>,

    /// OFFSET count
    pub offset: Option<usize>,
}

impl SqlSelect {
    /// Create a new empty SELECT statement
    pub fn new() -> Self {
        Self {
            columns: Vec::new(),
            table: None,
            where_clause: None,
            group_by: None,
            order_by: None,
            limit: None,
            offset: None,
        }
    }

    /// Check if this select needs aggregation pipeline
    pub fn needs_aggregate(&self) -> bool {
        self.group_by.is_some()
            || self.columns.iter().any(|c| match c {
                SqlColumn::Aggregate { .. } => true,
                SqlColumn::Field { alias, .. } => alias.is_some(),
                _ => false,
            })
    }
}

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

/// SQL column specification
#[derive(Debug, Clone, PartialEq)]
pub enum SqlColumn {
    /// SELECT *
    Star,

    /// SELECT column_name [AS alias]
    Field {
        path: FieldPath,
        alias: Option<String>,
    },

    /// SELECT COUNT(*), SUM(col), COUNT(DISTINCT col), etc.
    Aggregate {
        func: String,
        field: Option<FieldPath>,
        alias: Option<String>,
        distinct: bool,
    },
}

impl SqlColumn {
    /// Create a simple field column
    pub fn field(path: FieldPath) -> Self {
        SqlColumn::Field { path, alias: None }
    }

    /// Create an aggregate column
    pub fn aggregate(func: String, field: Option<FieldPath>) -> Self {
        SqlColumn::Aggregate {
            func,
            field,
            alias: None,
            distinct: false,
        }
    }
}

/// SQL expression
#[derive(Debug, Clone, PartialEq)]
pub enum SqlExpr {
    /// Literal value
    Literal(SqlLiteral),

    /// Field path reference (supports nested fields and array access)
    FieldPath(FieldPath),

    /// Binary operation (comparison)
    BinaryOp {
        left: Box<SqlExpr>,
        op: SqlOperator,
        right: Box<SqlExpr>,
    },

    /// Logical operation (AND, OR, NOT)
    LogicalOp {
        left: Box<SqlExpr>,
        op: SqlLogicalOperator,
        right: Box<SqlExpr>,
    },

    /// Function call
    Function { name: String, args: Vec<SqlExpr> },

    /// IN operator
    In {
        expr: Box<SqlExpr>,
        values: Vec<SqlExpr>,
    },

    /// LIKE pattern matching
    Like { expr: Box<SqlExpr>, pattern: String },

    /// IS NULL / IS NOT NULL
    IsNull { expr: Box<SqlExpr>, negated: bool },
}

/// SQL literal value
#[derive(Debug, Clone, PartialEq)]
pub enum SqlLiteral {
    /// String literal
    String(String),

    /// Number literal (stored as f64)
    Number(f64),

    /// Boolean literal
    Boolean(bool),

    /// NULL literal
    Null,
}

/// SQL comparison operators
#[derive(Debug, Clone, PartialEq)]
pub enum SqlOperator {
    /// =
    Eq,

    /// != or <>
    Ne,

    /// >
    Gt,

    /// <
    Lt,

    /// >=
    Ge,

    /// <=
    Le,
}

impl SqlOperator {
    /// Get operator precedence for Pratt parsing
    pub fn binding_power(&self) -> (u8, u8) {
        match self {
            SqlOperator::Eq | SqlOperator::Ne => (3, 4),
            SqlOperator::Gt | SqlOperator::Lt | SqlOperator::Ge | SqlOperator::Le => (5, 6),
        }
    }
}

/// SQL logical operators
#[derive(Debug, Clone, PartialEq)]
pub enum SqlLogicalOperator {
    /// AND
    And,

    /// OR
    Or,

    /// NOT
    Not,
}

impl SqlLogicalOperator {
    /// Get operator precedence for Pratt parsing
    pub fn binding_power(&self) -> (u8, u8) {
        match self {
            SqlLogicalOperator::Or => (1, 2),
            SqlLogicalOperator::And => (3, 4),
            SqlLogicalOperator::Not => (7, 8),
        }
    }
}

/// ORDER BY clause
#[derive(Debug, Clone, PartialEq)]
pub struct SqlOrderBy {
    /// Field path
    pub path: FieldPath,

    /// Ascending (true) or descending (false)
    pub asc: bool,
}

impl SqlOrderBy {
    /// Create a new ORDER BY clause
    pub fn new(path: FieldPath, asc: bool) -> Self {
        Self { path, asc }
    }
}

/// Array access error types
#[derive(Debug, Clone, PartialEq)]
pub enum ArrayAccessError {
    /// Empty index brackets
    EmptyIndex,

    /// Invalid index type (not a number)
    InvalidIndexType(String),

    /// Missing closing bracket
    MissingCloseBracket,

    /// Invalid slice syntax
    InvalidSliceSyntax(String),

    /// Zero step size in slice
    ZeroStepSize,

    /// Unsupported feature
    UnsupportedFeature(String),
}

impl ArrayAccessError {
    /// Convert to user-friendly error message
    pub fn to_user_message(&self) -> String {
        match self {
            ArrayAccessError::EmptyIndex => {
                "Empty array index. Use arr[0] for first element or arr[-1] for last element."
                    .to_string()
            }
            ArrayAccessError::InvalidIndexType(val) => {
                format!("Invalid array index '{}'. Index must be a number.", val)
            }
            ArrayAccessError::MissingCloseBracket => {
                "Missing closing bracket ']' for array access.".to_string()
            }
            ArrayAccessError::InvalidSliceSyntax(msg) => {
                format!("Invalid array slice syntax: {}", msg)
            }
            ArrayAccessError::ZeroStepSize => "Array slice step cannot be zero.".to_string(),
            ArrayAccessError::UnsupportedFeature(feature) => {
                format!("Unsupported feature: {}", feature)
            }
        }
    }
}

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

    #[test]
    fn test_sql_select_needs_aggregate() {
        let mut select = SqlSelect::new();
        assert!(!select.needs_aggregate());

        select.group_by = Some(vec!["category".to_string()]);
        assert!(select.needs_aggregate());

        let mut select2 = SqlSelect::new();
        select2.columns.push(SqlColumn::Aggregate {
            func: "COUNT".to_string(),
            field: None,
            alias: None,
            distinct: false,
        });
        assert!(select2.needs_aggregate());
    }

    #[test]
    fn test_expected_description() {
        assert_eq!(Expected::Keyword("SELECT").description(), "SELECT");
        assert_eq!(Expected::TableName.description(), "table name");
        assert_eq!(Expected::ColumnName.description(), "column name");
    }

    #[test]
    fn test_parse_result_checks() {
        let ok_result: ParseResult<i32> = ParseResult::Ok(42);
        assert!(ok_result.is_ok());
        assert!(!ok_result.is_partial());
        assert!(!ok_result.is_error());

        let partial_result: ParseResult<i32> = ParseResult::Partial(42, vec![]);
        assert!(!partial_result.is_ok());
        assert!(partial_result.is_partial());
        assert!(!partial_result.is_error());

        let error_result: ParseResult<i32> =
            ParseResult::Error(ParseError::new("error".to_string(), 0..1));
        assert!(!error_result.is_ok());
        assert!(!error_result.is_partial());
        assert!(error_result.is_error());
    }
}