turso_core 0.6.1

The Turso database library
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
use crate::bail_parse_error;
use std::borrow::Cow;

#[derive(Clone, Debug, PartialEq)]
enum PPState {
    Start,
    AfterRoot,
    InKey,
    InArrayIndex,
    ExpectDotOrBracket,
}

#[derive(Clone, Debug, PartialEq)]
enum ArrayIndexState {
    Start,
    AfterHash,
    CollectingNumbers,
    IsMax,
}

/// Describes a JSON path, which is a sequence of keys and/or array locators.
#[derive(Clone, Debug)]
pub struct JsonPath<'a> {
    pub elements: Vec<PathElement<'a>>,
}

type RawString = bool;

/// PathElement describes a single element of a JSON path.
#[derive(Clone, Debug, PartialEq)]
pub enum PathElement<'a> {
    /// Root element: '$'
    Root(),
    /// JSON key
    Key(Cow<'a, str>, RawString),
    /// Array locator, eg. [2], [#-5]
    ArrayLocator(Option<i32>),
    /// Bracket-quoted key (e.g. `$["key"]`). Parsed without error for SQLite
    /// compatibility but never matches during extraction — SQLite returns NULL
    /// for bracket-notation on non-array nodes.
    BracketQuotedKey(Cow<'a, str>),
}

type IsMaxNumber = bool;

fn collect_num(current: i128, adding: i128, negative: bool) -> (i128, IsMaxNumber) {
    let ten = 10i128;

    let result = if negative {
        current.saturating_mul(ten).saturating_sub(adding)
    } else {
        current.saturating_mul(ten).saturating_add(adding)
    };

    let is_max = result == i128::MAX || result == i128::MIN;
    (result, is_max)
}

fn estimate_path_capacity(input: &str) -> usize {
    // After $ we need either . or [ for each component
    // So divide remaining length by 2 (minimum chars per component)
    // Add 1 for the root component
    1 + (input.len() - 1) / 2
}

/// Parses path into a Vec of Strings, where each string is a key or an array locator.
pub fn json_path(path: &str) -> crate::Result<JsonPath<'_>> {
    if path.is_empty() {
        bail_parse_error!("Bad json path: {}", path)
    }
    let mut parser_state = PPState::Start;
    let mut index_state = ArrayIndexState::Start;
    let mut key_start = 0;
    let mut index_buffer: i128 = 0;
    let mut path_components = Vec::with_capacity(estimate_path_capacity(path));
    let mut path_iter = path.char_indices();

    while let Some(ch) = path_iter.next() {
        match parser_state {
            PPState::Start => {
                handle_start(ch, &mut parser_state, &mut path_components, path)?;
            }
            PPState::AfterRoot => {
                handle_after_root(
                    ch,
                    &mut parser_state,
                    &mut index_state,
                    &mut key_start,
                    &mut index_buffer,
                    path,
                )?;
            }
            PPState::InKey => {
                handle_in_key(
                    ch,
                    &mut parser_state,
                    &mut index_state,
                    &mut key_start,
                    &mut index_buffer,
                    &mut path_components,
                    &mut path_iter,
                    path,
                )?;
            }
            PPState::InArrayIndex => {
                handle_array_index(
                    ch,
                    &mut parser_state,
                    &mut index_state,
                    &mut index_buffer,
                    &mut path_components,
                    &mut path_iter,
                    path,
                )?;
            }
            PPState::ExpectDotOrBracket => {
                handle_expect_dot_or_bracket(
                    ch,
                    &mut parser_state,
                    &mut index_state,
                    &mut key_start,
                    &mut index_buffer,
                    path,
                )?;
            }
        }
    }

    finalize_path(parser_state, key_start, path, &mut path_components)?;
    Ok(JsonPath {
        elements: path_components,
    })
}

fn handle_start(
    ch: (usize, char),
    parser_state: &mut PPState,
    path_components: &mut Vec<PathElement>,
    path: &str,
) -> crate::Result<()> {
    match ch {
        (_, '$') => {
            path_components.push(PathElement::Root());
            *parser_state = PPState::AfterRoot;
            Ok(())
        }
        (_, _) => bail_parse_error!("Bad json path: {}", path),
    }
}

fn handle_after_root(
    ch: (usize, char),
    parser_state: &mut PPState,
    index_state: &mut ArrayIndexState,
    key_start: &mut usize,
    index_buffer: &mut i128,
    path: &str,
) -> crate::Result<()> {
    match ch {
        (idx, '.') => {
            *parser_state = PPState::InKey;
            *key_start = idx + ch.1.len_utf8();
            Ok(())
        }
        (_, '[') => {
            *index_state = ArrayIndexState::Start;
            *parser_state = PPState::InArrayIndex;
            *index_buffer = 0;
            Ok(())
        }
        (_, _) => bail_parse_error!("Bad json path: {}", path),
    }
}

#[allow(clippy::too_many_arguments)]
fn handle_in_key<'a>(
    ch: (usize, char),
    parser_state: &mut PPState,
    index_state: &mut ArrayIndexState,
    key_start: &mut usize,
    index_buffer: &mut i128,
    path_components: &mut Vec<PathElement<'a>>,
    path_iter: &mut std::str::CharIndices,
    path: &'a str,
) -> crate::Result<()> {
    match ch {
        (idx, '.' | '[') => {
            let key_end = idx;
            if key_end > *key_start {
                let key = &path[*key_start..key_end];
                if ch.1 == '[' {
                    *index_state = ArrayIndexState::Start;
                    *parser_state = PPState::InArrayIndex;
                    *index_buffer = 0;
                } else {
                    *key_start = idx + ch.1.len_utf8();
                }
                path_components.push(PathElement::Key(Cow::Borrowed(key), false));
            } else {
                bail_parse_error!("Bad json path: {}", path)
            }
        }
        (idx, '"') => {
            handle_quoted_key(parser_state, idx, path_components, path_iter, path)?;
        }
        (_, _) => (),
    }
    Ok(())
}

fn handle_quoted_key<'a>(
    parser_state: &mut PPState,
    quote_start: usize,
    path_components: &mut Vec<PathElement<'a>>,
    path_iter: &mut std::str::CharIndices,
    path: &'a str,
) -> crate::Result<()> {
    // quote_start is the byte index of the opening '"'
    // The key content starts after the opening quote (1 byte for '"')
    let key_content_start = quote_start + 1;
    while let Some((idx, ch)) = path_iter.next() {
        match ch {
            '\\' => {
                path_iter.next();
            }
            '"' => {
                if key_content_start <= idx {
                    let key = &path[key_content_start..idx];
                    path_components.push(PathElement::Key(Cow::Borrowed(key), true));
                    *parser_state = PPState::ExpectDotOrBracket;
                    return Ok(());
                }
            }
            _ => continue,
        }
    }
    Ok(())
}

fn handle_array_index<'a>(
    ch: (usize, char),
    parser_state: &mut PPState,
    index_state: &mut ArrayIndexState,
    index_buffer: &mut i128,
    path_components: &mut Vec<PathElement<'a>>,
    path_iter: &mut std::str::CharIndices,
    path: &'a str,
) -> crate::Result<()> {
    match (&index_state, ch.1) {
        (ArrayIndexState::Start, '#') => {
            *index_state = ArrayIndexState::AfterHash;
        }
        (ArrayIndexState::Start, '0'..='9') => {
            *index_buffer = ch.1.to_digit(10).ok_or_else(|| {
                crate::LimboError::ParseError(format!("failed to parse digit: {ch}", ch = ch.1))
            })? as i128;
            *index_state = ArrayIndexState::CollectingNumbers;
        }
        // Bracket-notation quoted key, e.g. $["key with spaces"] or $['key'].
        // Issue #6099: previously this fell through to the catch-all and produced
        // a "Bad json path" parse error. Dispatch to a dedicated helper that
        // consumes the quoted string and the closing `]`.
        (ArrayIndexState::Start, q @ ('"' | '\'')) => {
            handle_bracket_quoted_key(q, ch.0, parser_state, path_components, path_iter, path)?;
        }
        (ArrayIndexState::AfterHash, '-') => {
            handle_negative_index(index_state, index_buffer, path_iter, path)?;
        }
        (ArrayIndexState::AfterHash, ']') => {
            *parser_state = PPState::ExpectDotOrBracket;
            path_components.push(PathElement::ArrayLocator(None));
        }
        (ArrayIndexState::CollectingNumbers, '0'..='9') => {
            let (new_num, is_max) = collect_num(
                *index_buffer,
                ch.1.to_digit(10).ok_or_else(|| {
                    crate::LimboError::ParseError(format!("failed to parse digit: {ch}", ch = ch.1))
                })? as i128,
                *index_buffer < 0,
            );
            if is_max {
                *index_state = ArrayIndexState::IsMax;
            }
            *index_buffer = new_num;
        }
        (ArrayIndexState::IsMax, '0'..='9') => (),
        (ArrayIndexState::CollectingNumbers | ArrayIndexState::IsMax, ']') => {
            *parser_state = PPState::ExpectDotOrBracket;
            path_components.push(PathElement::ArrayLocator(Some(*index_buffer as i32)));
        }
        (_, _) => bail_parse_error!("Bad json path: {}", path),
    }
    Ok(())
}

/// Handle bracket-notation with a quoted key, e.g. `$["key with spaces"]` or `$['key']`.
/// The opening bracket and the opening quote have already been consumed by
/// `handle_array_index`; `quote_start` is the byte index of the opening quote.
/// After the closing quote we require a `]`.
///
/// Escape handling mirrors `handle_quoted_key` (raw bytes preserved, no decoding)
/// so the dot-quoted form `$."key"` and the bracket-quoted form behave the same.
fn handle_bracket_quoted_key<'a>(
    quote_char: char,
    quote_start: usize,
    parser_state: &mut PPState,
    path_components: &mut Vec<PathElement<'a>>,
    path_iter: &mut std::str::CharIndices,
    path: &'a str,
) -> crate::Result<()> {
    // The quote character is always 1 byte (ASCII '"' or '\''), so the key
    // content begins at quote_start + 1.
    let key_content_start = quote_start + 1;
    let mut key_end: Option<usize> = None;

    while let Some((idx, ch)) = path_iter.next() {
        match ch {
            '\\' => {
                // Skip the escaped character (matches handle_quoted_key's behavior).
                path_iter.next();
            }
            c if c == quote_char => {
                key_end = Some(idx);
                break;
            }
            _ => {}
        }
    }

    let Some(key_end) = key_end else {
        bail_parse_error!("Bad json path: {}", path)
    };

    // Expect the closing bracket immediately after the closing quote.
    match path_iter.next() {
        Some((_, ']')) => {
            let key = &path[key_content_start..key_end];
            path_components.push(PathElement::BracketQuotedKey(Cow::Borrowed(key)));
            *parser_state = PPState::ExpectDotOrBracket;
            Ok(())
        }
        _ => bail_parse_error!("Bad json path: {}", path),
    }
}

fn handle_negative_index(
    index_state: &mut ArrayIndexState,
    index_buffer: &mut i128,
    path_iter: &mut std::str::CharIndices,
    path: &str,
) -> crate::Result<()> {
    if let Some((_, next_c)) = path_iter.next() {
        if next_c.is_ascii_digit() {
            *index_buffer = -(next_c.to_digit(10).ok_or_else(|| {
                crate::LimboError::ParseError(format!("failed to parse digit: {next_c}"))
            })? as i128);
            *index_state = ArrayIndexState::CollectingNumbers;
            Ok(())
        } else {
            bail_parse_error!("Bad json path: {}", path)
        }
    } else {
        bail_parse_error!("Bad json path: {}", path)
    }
}

fn handle_expect_dot_or_bracket(
    ch: (usize, char),
    parser_state: &mut PPState,
    index_state: &mut ArrayIndexState,
    key_start: &mut usize,
    index_buffer: &mut i128,
    path: &str,
) -> crate::Result<()> {
    match ch {
        (idx, '.') => {
            *key_start = idx + ch.1.len_utf8();
            *parser_state = PPState::InKey;
            Ok(())
        }
        (_, '[') => {
            *index_state = ArrayIndexState::Start;
            *parser_state = PPState::InArrayIndex;
            *index_buffer = 0;
            Ok(())
        }
        (_, _) => bail_parse_error!("Bad json path: {}", path),
    }
}

fn finalize_path<'a>(
    parser_state: PPState,
    key_start: usize,
    path: &'a str,
    path_components: &mut Vec<PathElement<'a>>,
) -> crate::Result<()> {
    match parser_state {
        PPState::InArrayIndex => bail_parse_error!("Bad json path: {}", path),
        PPState::InKey => {
            if key_start < path.len() {
                let key = &path[key_start..];
                if key.starts_with('"') && !key.ends_with('"') && key.len() > 1
                    || (key.starts_with('"') && key.ends_with('"') && key.len() == 1)
                {
                    bail_parse_error!("Bad json path: {}", path)
                }
                path_components.push(PathElement::Key(Cow::Borrowed(key), false));
            } else {
                bail_parse_error!("Bad json path: {}", path)
            }
        }
        _ => (),
    }
    Ok(())
}

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

    #[test]
    fn test_json_path_root() {
        let path = json_path("$").unwrap();
        assert_eq!(path.elements.len(), 1);
        assert_eq!(path.elements[0], PathElement::Root());
    }

    #[test]
    fn test_json_path_single_locator() {
        let path = json_path("$.x").unwrap();
        assert_eq!(path.elements.len(), 2);
        assert_eq!(path.elements[0], PathElement::Root());
        assert_eq!(
            path.elements[1],
            PathElement::Key(Cow::Borrowed("x"), false)
        );
    }

    #[test]
    fn test_json_path_single_array_locator() {
        let path = json_path("$[0]").unwrap();
        assert_eq!(path.elements.len(), 2);
        assert_eq!(path.elements[0], PathElement::Root());
        assert_eq!(path.elements[1], PathElement::ArrayLocator(Some(0)));
    }

    #[test]
    fn test_json_path_single_negative_array_locator() {
        let path = json_path("$[#-2]").unwrap();
        assert_eq!(path.elements.len(), 2);
        assert_eq!(path.elements[0], PathElement::Root());
        assert_eq!(path.elements[1], PathElement::ArrayLocator(Some(-2)));
    }

    #[test]
    fn test_json_path_invalid() {
        let invalid_values = vec![
            "", "$$$", "$.", "$ ", "$[", "$]", "$[-1]", "x", "[]", "$[0", "$[0x]", "$\"",
        ];

        for value in invalid_values {
            let path = json_path(value);

            match path {
                Err(crate::error::LimboError::ParseError(_)) => {
                    // happy path
                }
                _ => panic!("Expected error for: {value:?}, got: {path:?}"),
            }
        }
    }

    #[test]
    fn test_json_path() {
        let path = json_path("$.store.book[0].title").unwrap();
        assert_eq!(path.elements.len(), 5);
        assert_eq!(path.elements[0], PathElement::Root());
        assert_eq!(
            path.elements[1],
            PathElement::Key(Cow::Borrowed("store"), false)
        );
        assert_eq!(
            path.elements[2],
            PathElement::Key(Cow::Borrowed("book"), false)
        );
        assert_eq!(path.elements[3], PathElement::ArrayLocator(Some(0)));
        assert_eq!(
            path.elements[4],
            PathElement::Key(Cow::Borrowed("title"), false)
        );
    }

    #[test]
    fn test_large_index_wrapping() {
        let path = json_path("$[4294967296]").unwrap();
        assert_eq!(path.elements[1], PathElement::ArrayLocator(Some(0)));

        let path = json_path("$[4294967297]").unwrap();
        assert_eq!(path.elements[1], PathElement::ArrayLocator(Some(1)));
    }

    #[test]
    fn test_deeply_nested_path() {
        let path = json_path("$[0][1][2].key[3].other").unwrap();
        assert_eq!(path.elements.len(), 7);
        assert_eq!(path.elements[0], PathElement::Root());
        assert_eq!(path.elements[1], PathElement::ArrayLocator(Some(0)));
        assert_eq!(path.elements[2], PathElement::ArrayLocator(Some(1)));
        assert_eq!(path.elements[3], PathElement::ArrayLocator(Some(2)));
        assert_eq!(
            path.elements[4],
            PathElement::Key(Cow::Borrowed("key"), false)
        );
        assert_eq!(path.elements[5], PathElement::ArrayLocator(Some(3)));
    }

    #[test]
    fn test_edge_cases() {
        // Empty key
        assert!(json_path("$.").is_err());

        // Multiple dots
        assert!(json_path("$..key").is_err());

        // Unclosed brackets
        assert!(json_path("$[0").is_err());
        assert!(json_path("$[").is_err());

        // Invalid negative index format
        assert!(json_path("$[-1]").is_err()); // should be $[#-1]
    }

    #[test]
    fn test_path_capacity() {
        // Test that our capacity estimation is reasonable
        let short_path = "$[0]";
        assert!(estimate_path_capacity(short_path) >= 2);

        let long_path = "$.a.b.c.d.e.f.g[0][1][2]";
        assert!(estimate_path_capacity(long_path) >= 11);
    }

    #[test]
    fn test_quoted_keys() {
        let path = json_path(r#"$."key""#).unwrap();
        assert_eq!(
            path.elements[1],
            PathElement::Key(Cow::Borrowed("key"), true)
        );

        let path = json_path(r#"$."key.with.dots""#).unwrap();
        assert_eq!(
            path.elements[1],
            PathElement::Key(Cow::Borrowed("key.with.dots"), true)
        );

        let path = json_path(r#"$."key[0]""#).unwrap();
        assert_eq!(
            path.elements[1],
            PathElement::Key(Cow::Borrowed("key[0]"), true)
        );
    }

    #[test]
    fn test_empty_quoted_key() {
        assert!(json_path(r#"$."""#).is_ok());
    }

    #[test]
    fn test_quoted_key_after_multibyte_utf8_chars() {
        // Regression test for issue #5028
        // The path contains multi-byte UTF-8 chars before a quoted key.
        // This should not panic with "byte index is not a char boundary".
        // '՜' is a 2-byte UTF-8 character (bytes 2-3 in the path).
        // The important thing is that it doesn't panic - the result
        // (valid parse or parse error) is less important.
        let _ = json_path(r#"$.՜O'"R"RE"#);

        // Also test a simpler case where UTF-8 chars appear before a quoted key
        // $.世界"key" - Chinese characters followed by a quoted key
        let _ = json_path(r#"$.世界"key""#);

        // Test with a valid quoted key containing UTF-8 chars
        let path = json_path(r#"$."世界""#).unwrap();
        assert_eq!(path.elements.len(), 2);
        assert_eq!(
            path.elements[1],
            PathElement::Key(Cow::Borrowed("世界"), true)
        );
    }

    #[test]
    fn test_bracket_quoted_key() {
        // Issue #6099: bracket notation with double-quoted key.
        // Parsed successfully but produces BracketQuotedKey (never matches
        // during extraction — SQLite compat, always returns NULL).
        let path = json_path(r#"$["key"]"#).unwrap();
        assert_eq!(path.elements.len(), 2);
        assert_eq!(path.elements[0], PathElement::Root());
        assert_eq!(
            path.elements[1],
            PathElement::BracketQuotedKey(Cow::Borrowed("key"))
        );

        // Key containing spaces (the original issue example).
        let path = json_path(r#"$["key with spaces"]"#).unwrap();
        assert_eq!(
            path.elements[1],
            PathElement::BracketQuotedKey(Cow::Borrowed("key with spaces"))
        );

        // Key containing dots.
        let path = json_path(r#"$["key.with.dots"]"#).unwrap();
        assert_eq!(
            path.elements[1],
            PathElement::BracketQuotedKey(Cow::Borrowed("key.with.dots"))
        );

        // Key containing brackets.
        let path = json_path(r#"$["key[0]"]"#).unwrap();
        assert_eq!(
            path.elements[1],
            PathElement::BracketQuotedKey(Cow::Borrowed("key[0]"))
        );

        // Single-quoted variant.
        let path = json_path(r#"$['key']"#).unwrap();
        assert_eq!(
            path.elements[1],
            PathElement::BracketQuotedKey(Cow::Borrowed("key"))
        );

        // Empty quoted key.
        let path = json_path(r#"$[""]"#).unwrap();
        assert_eq!(
            path.elements[1],
            PathElement::BracketQuotedKey(Cow::Borrowed(""))
        );

        // Mixed with dot notation and array indices.
        let path = json_path(r#"$.outer["inner key"][2]"#).unwrap();
        assert_eq!(path.elements.len(), 4);
        assert_eq!(
            path.elements[1],
            PathElement::Key(Cow::Borrowed("outer"), false)
        );
        assert_eq!(
            path.elements[2],
            PathElement::BracketQuotedKey(Cow::Borrowed("inner key"))
        );
        assert_eq!(path.elements[3], PathElement::ArrayLocator(Some(2)));
    }

    #[test]
    fn test_bracket_quoted_key_invalid() {
        // Unclosed quote.
        assert!(json_path(r#"$["key"#).is_err());
        // Closing quote but no closing bracket.
        assert!(json_path(r#"$["key""#).is_err());
        // Mismatched quote characters (single quote inside double-quoted key
        // is fine; this case has the wrong closing quote).
        assert!(json_path(r#"$["key']"#).is_err());
        // Trailing junk between closing quote and bracket.
        assert!(json_path(r#"$["key"x]"#).is_err());
    }
}