nodedb-sql 0.6.0

SQL parser, planner, and optimizer for NodeDB
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
// SPDX-License-Identifier: Apache-2.0

//! The recursive-descent scanner behind the object-literal entry points:
//! whitespace, identifiers, strings, numbers, nested objects, and arrays.

use std::collections::HashMap;

use nodedb_types::Value;

use crate::error::SqlError;

pub(super) fn skip_ws(chars: &[char], pos: &mut usize) {
    while *pos < chars.len() && chars[*pos].is_ascii_whitespace() {
        *pos += 1;
    }
}

fn parse_ident(chars: &[char], pos: &mut usize) -> String {
    let mut s = String::new();
    while *pos < chars.len() {
        let c = chars[*pos];
        if c.is_ascii_alphanumeric() || c == '_' || c == '.' {
            s.push(c);
            *pos += 1;
        } else {
            break;
        }
    }
    s
}

fn parse_string(chars: &[char], pos: &mut usize) -> Result<String, SqlError> {
    // Expect opening single-quote
    if *pos >= chars.len() || chars[*pos] != '\'' {
        return Err(SqlError::Parse {
            detail: format!(
                "expected single quote at position {}, found {:?}",
                pos,
                chars.get(*pos)
            ),
        });
    }
    *pos += 1; // consume opening quote
    let mut s = String::new();
    loop {
        if *pos >= chars.len() {
            return Err(SqlError::Parse {
                detail: "unterminated string literal".to_string(),
            });
        }
        if chars[*pos] == '\'' {
            *pos += 1; // consume quote
            // SQL escaped quote: '' → '
            if *pos < chars.len() && chars[*pos] == '\'' {
                s.push('\'');
                *pos += 1;
            } else {
                break; // end of string
            }
        } else {
            s.push(chars[*pos]);
            *pos += 1;
        }
    }
    Ok(s)
}

fn parse_double_quoted_string(chars: &[char], pos: &mut usize) -> Result<String, SqlError> {
    if *pos >= chars.len() || chars[*pos] != '"' {
        return Err(SqlError::Parse {
            detail: format!(
                "expected double quote at position {}, found {:?}",
                pos,
                chars.get(*pos)
            ),
        });
    }
    *pos += 1;
    let mut s = String::new();
    loop {
        if *pos >= chars.len() {
            return Err(SqlError::Parse {
                detail: "unterminated double-quoted string literal".to_string(),
            });
        }
        match chars[*pos] {
            '"' => {
                *pos += 1;
                if *pos < chars.len() && chars[*pos] == '"' {
                    s.push('"');
                    *pos += 1;
                } else {
                    break;
                }
            }
            c => {
                s.push(c);
                *pos += 1;
            }
        }
    }
    Ok(s)
}

fn parse_number(chars: &[char], pos: &mut usize) -> Result<Value, SqlError> {
    let start = *pos;
    if *pos < chars.len() && chars[*pos] == '-' {
        *pos += 1;
    }
    while *pos < chars.len() && chars[*pos].is_ascii_digit() {
        *pos += 1;
    }
    let is_float = *pos < chars.len() && chars[*pos] == '.';
    if is_float {
        *pos += 1; // consume '.'
        while *pos < chars.len() && chars[*pos].is_ascii_digit() {
            *pos += 1;
        }
    }
    let raw: String = chars[start..*pos].iter().collect();
    if is_float {
        raw.parse::<f64>()
            .map(Value::Float)
            .map_err(|_| SqlError::Parse {
                detail: format!("invalid float: {raw}"),
            })
    } else {
        raw.parse::<i64>()
            .map(Value::Integer)
            .map_err(|_| SqlError::Parse {
                detail: format!("invalid integer: {raw}"),
            })
    }
}

fn parse_array(chars: &[char], pos: &mut usize) -> Result<Vec<Value>, SqlError> {
    // Expect '['
    if *pos >= chars.len() || chars[*pos] != '[' {
        return Err(SqlError::Parse {
            detail: format!(
                "expected '[' at position {pos}, found {:?}",
                chars.get(*pos)
            ),
        });
    }
    *pos += 1; // consume '['
    let mut items = Vec::new();
    loop {
        skip_ws(chars, pos);
        if *pos >= chars.len() {
            return Err(SqlError::Parse {
                detail: "unterminated array literal".to_string(),
            });
        }
        if chars[*pos] == ']' {
            *pos += 1; // consume ']'
            break;
        }
        // trailing comma already consumed; skip it
        if chars[*pos] == ',' {
            *pos += 1;
            continue;
        }
        let val = parse_value(chars, pos)?;
        items.push(val);
        skip_ws(chars, pos);
        if *pos < chars.len() && chars[*pos] == ',' {
            *pos += 1; // consume ','
        }
    }
    Ok(items)
}

pub(super) fn parse_object(
    chars: &[char],
    pos: &mut usize,
) -> Result<HashMap<String, Value>, SqlError> {
    // Expect '{'
    if *pos >= chars.len() || chars[*pos] != '{' {
        return Err(SqlError::Parse {
            detail: format!(
                "expected '{{' at position {pos}, found {:?}",
                chars.get(*pos)
            ),
        });
    }
    *pos += 1; // consume '{'
    let mut map = HashMap::new();
    loop {
        skip_ws(chars, pos);
        if *pos >= chars.len() {
            return Err(SqlError::Parse {
                detail: "unterminated object literal".to_string(),
            });
        }
        if chars[*pos] == '}' {
            *pos += 1; // consume '}'
            break;
        }
        // Trailing comma: skip and re-check for '}'
        if chars[*pos] == ',' {
            *pos += 1;
            continue;
        }

        // Parse key (identifier or JSON-style quoted key).
        skip_ws(chars, pos);
        if *pos >= chars.len() {
            return Err(SqlError::Parse {
                detail: "expected key, reached end of input".to_string(),
            });
        }
        let key = if chars[*pos] == '"' {
            parse_double_quoted_string(chars, pos)?
        } else {
            let first = chars[*pos];
            if !(first.is_ascii_alphabetic() || first == '_') {
                return Err(SqlError::Parse {
                    detail: format!("expected identifier key at position {pos}, found '{first}'"),
                });
            }
            parse_ident(chars, pos)
        };
        if key.is_empty() {
            return Err(SqlError::Parse {
                detail: format!("expected non-empty key at position {pos}"),
            });
        }

        // Expect ':'
        skip_ws(chars, pos);
        if *pos >= chars.len() || chars[*pos] != ':' {
            return Err(SqlError::Parse {
                detail: format!(
                    "expected ':' after key '{key}' at position {pos}, found {:?}",
                    chars.get(*pos)
                ),
            });
        }
        *pos += 1; // consume ':'

        // Parse value
        skip_ws(chars, pos);
        if *pos >= chars.len() {
            return Err(SqlError::Parse {
                detail: format!("expected value for key '{key}', reached end of input"),
            });
        }
        if chars[*pos] == '}' || chars[*pos] == ',' {
            return Err(SqlError::Parse {
                detail: format!("expected value for key '{key}', found '{}'", chars[*pos]),
            });
        }
        let val = parse_value(chars, pos)?;
        map.insert(key, val);

        // Optional comma
        skip_ws(chars, pos);
        if *pos < chars.len() && chars[*pos] == ',' {
            *pos += 1;
        }
    }
    Ok(map)
}

fn parse_value(chars: &[char], pos: &mut usize) -> Result<Value, SqlError> {
    skip_ws(chars, pos);
    if *pos >= chars.len() {
        return Err(SqlError::Parse {
            detail: "unexpected end of input while parsing value".to_string(),
        });
    }
    match chars[*pos] {
        '\'' => parse_string(chars, pos).map(Value::String),
        '{' => parse_object(chars, pos).map(Value::Object),
        '[' => parse_array(chars, pos).map(Value::Array),
        '-' | '0'..='9' => parse_number(chars, pos),
        _ => {
            // bare word: true / false / null / identifier
            let word = parse_ident(chars, pos);
            match word.to_lowercase().as_str() {
                "true" => Ok(Value::Bool(true)),
                "false" => Ok(Value::Bool(false)),
                "null" => Ok(Value::Null),
                _ if word.is_empty() => Err(SqlError::Parse {
                    detail: format!("unexpected character '{}' at position {pos}", chars[*pos]),
                }),
                _ => Err(SqlError::Parse {
                    detail: format!("unknown bare word: '{word}'"),
                }),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::object_literal::{
        parse_object_literal, parse_object_literal_array, parse_object_literal_array_complete,
        parse_object_literal_complete,
    };

    fn parse(s: &str) -> HashMap<String, Value> {
        parse_object_literal(s).unwrap().unwrap()
    }

    /// The prefix parser tolerates trailing input BY DESIGN — the
    /// function-argument rewriter depends on it — so the tolerance is pinned
    /// here rather than left as an accident of the implementation.
    #[test]
    fn the_prefix_parser_stops_at_the_matching_brace() {
        let fields = parse("{ a: 1 } and then some");
        assert_eq!(fields.len(), 1);
    }

    /// …and the strict form reports what the prefix parser would have thrown
    /// away, naming it so the author can see which part was rejected.
    #[test]
    fn the_strict_parser_reports_trailing_input() {
        let error = parse_object_literal_complete("{ a: 1 } RETURNING *")
            .expect("input starts with a brace")
            .expect_err("trailing input must not be accepted");
        let detail = error.to_string();
        assert!(
            detail.contains("RETURNING *"),
            "the error must name the leftover, got: {detail}"
        );
    }

    /// A statement terminator is not content, so it does not trip the check.
    #[test]
    fn the_strict_parser_accepts_a_trailing_semicolon() {
        assert!(
            parse_object_literal_complete("{ a: 1 };")
                .expect("input starts with a brace")
                .is_ok()
        );
    }

    /// A `}` inside a quoted value belongs to the value, so it must not be
    /// mistaken for the end of the literal.
    #[test]
    fn the_strict_parser_ignores_a_brace_inside_a_string() {
        let fields = parse_object_literal_complete("{ note: '} not the end' }")
            .expect("input starts with a brace")
            .expect("a brace inside a string is part of the value");
        assert_eq!(fields.len(), 1);
    }

    /// The array form gets the same contract, measured against the real
    /// closing bracket rather than the last one in the input.
    #[test]
    fn the_strict_array_parser_reports_trailing_input() {
        assert!(
            parse_object_literal_array_complete("[{ a: 1 }] RETURNING *")
                .expect("input starts with a bracket")
                .is_err()
        );
        assert!(
            parse_object_literal_array_complete("[{ note: 'x]y' }]")
                .expect("input starts with a bracket")
                .is_ok(),
            "a bracket inside a string must not be read as the array's end"
        );
    }

    #[test]
    fn simple_string_and_int() {
        let m = parse("{ name: 'Alice', age: 30 }");
        assert_eq!(m["name"], Value::String("Alice".to_string()));
        assert_eq!(m["age"], Value::Integer(30));
    }

    #[test]
    fn nested_object() {
        let m = parse("{ addr: { city: 'NYC' } }");
        let inner = match &m["addr"] {
            Value::Object(o) => o,
            _ => panic!("expected Object"),
        };
        assert_eq!(inner["city"], Value::String("NYC".to_string()));
    }

    #[test]
    fn array_value() {
        let m = parse("{ tags: ['a', 'b'] }");
        assert_eq!(
            m["tags"],
            Value::Array(vec![
                Value::String("a".to_string()),
                Value::String("b".to_string()),
            ])
        );
    }

    #[test]
    fn mixed_types() {
        let m = parse("{ a: 'str', b: 42, c: 2.78, d: true, e: false, f: null }");
        assert_eq!(m["a"], Value::String("str".to_string()));
        assert_eq!(m["b"], Value::Integer(42));
        assert_eq!(m["c"], Value::Float(2.78));
        assert_eq!(m["d"], Value::Bool(true));
        assert_eq!(m["e"], Value::Bool(false));
        assert_eq!(m["f"], Value::Null);
    }

    #[test]
    fn escaped_quotes() {
        let m = parse("{ name: 'O''Brien' }");
        assert_eq!(m["name"], Value::String("O'Brien".to_string()));
    }

    #[test]
    fn empty_object() {
        let m = parse("{ }");
        assert!(m.is_empty());
    }

    #[test]
    fn trailing_comma() {
        let m = parse("{ name: 'Alice', }");
        assert_eq!(m["name"], Value::String("Alice".to_string()));
    }

    #[test]
    fn not_an_object_returns_none() {
        assert!(parse_object_literal("not an object").is_none());
    }

    #[test]
    fn missing_value_returns_err() {
        let result = parse_object_literal("{ name: }");
        assert!(matches!(result, Some(Err(_))));
    }

    #[test]
    fn missing_key_returns_err() {
        let result = parse_object_literal("{ : 'val' }");
        assert!(matches!(result, Some(Err(_))));
    }

    #[test]
    fn negative_numbers() {
        let m = parse("{ x: -42, y: -2.78 }");
        assert_eq!(m["x"], Value::Integer(-42));
        assert_eq!(m["y"], Value::Float(-2.78));
    }

    #[test]
    fn nested_array_in_object() {
        let m = parse("{ data: { items: [1, 2, 3] } }");
        let inner = match &m["data"] {
            Value::Object(o) => o,
            _ => panic!("expected Object"),
        };
        assert_eq!(
            inner["items"],
            Value::Array(vec![
                Value::Integer(1),
                Value::Integer(2),
                Value::Integer(3),
            ])
        );
    }

    #[test]
    fn dotted_key() {
        let m = parse("{ metadata.source: 'web' }");
        assert_eq!(m["metadata.source"], Value::String("web".to_string()));
    }

    #[test]
    fn parse_array_of_objects() {
        let result = parse_object_literal_array("[{ name: 'Alice' }, { name: 'Bob' }]")
            .unwrap()
            .unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0]["name"], Value::String("Alice".to_string()));
        assert_eq!(result[1]["name"], Value::String("Bob".to_string()));
    }

    #[test]
    fn parse_array_empty() {
        let result = parse_object_literal_array("[]").unwrap().unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn parse_array_not_array_returns_none() {
        assert!(parse_object_literal_array("{ name: 'Alice' }").is_none());
    }

    #[test]
    fn parse_array_non_object_element_returns_err() {
        let result = parse_object_literal_array("[42]");
        assert!(matches!(result, Some(Err(_))));
    }

    #[test]
    fn parse_array_trailing_comma() {
        let result = parse_object_literal_array("[{ a: 1 }, { b: 2 },]")
            .unwrap()
            .unwrap();
        assert_eq!(result.len(), 2);
    }
}