Skip to main content

sql_builder/backend/
json_path.rs

1//! JSON paths as every backend reads them: `$` followed by member and index
2//! steps.
3
4/// One step of a JSON path.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub enum JsonPathStep {
7    /// The member a key names.
8    Member(String),
9    /// The array element at an index.
10    Element(u64),
11}
12
13/// Whether `segment` is a plain identifier: an ASCII letter or `_`, then
14/// ASCII letters, digits or `_`.
15pub fn is_plain_identifier(segment: &str) -> bool {
16    let mut chars = segment.chars();
17    match chars.next() {
18        Some(ch) if ch == '_' || ch.is_ascii_alphabetic() => {}
19        _ => return false,
20    }
21
22    chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
23}
24
25/// The steps of a JSON path.
26///
27/// The path is `$` followed by `.key`, `."quoted key"`, `['quoted key']` or
28/// `[index]` steps; `None` for anything else, such as a wildcard or an
29/// unquoted key that is not a plain identifier.
30pub fn parse_json_path(path: &str) -> Option<Vec<JsonPathStep>> {
31    let chars: Vec<char> = path.chars().collect();
32    if chars.first().copied() != Some('$') {
33        return None;
34    }
35
36    let mut index = 1;
37    let mut steps = Vec::new();
38    while index < chars.len() {
39        let step = match chars[index] {
40            '.' => {
41                index += 1;
42                match chars.get(index) {
43                    Some('"' | '\'') => JsonPathStep::Member(quoted_segment(&chars, &mut index)?),
44                    Some(_) => {
45                        let start = index;
46                        while index < chars.len() && chars[index] != '.' && chars[index] != '[' {
47                            index += 1;
48                        }
49                        let segment: String = chars[start..index].iter().collect();
50                        if !is_plain_identifier(&segment) {
51                            return None;
52                        }
53                        JsonPathStep::Member(segment)
54                    }
55                    None => return None,
56                }
57            }
58            '[' => {
59                index += 1;
60                let step = match chars.get(index) {
61                    Some('"' | '\'') => JsonPathStep::Member(quoted_segment(&chars, &mut index)?),
62                    Some(ch) if ch.is_ascii_digit() => {
63                        let start = index;
64                        while index < chars.len() && chars[index].is_ascii_digit() {
65                            index += 1;
66                        }
67                        let digits: String = chars[start..index].iter().collect();
68                        JsonPathStep::Element(digits.parse().ok()?)
69                    }
70                    _ => return None,
71                };
72                if chars.get(index) != Some(&']') {
73                    return None;
74                }
75                index += 1;
76                step
77            }
78            _ => return None,
79        };
80        steps.push(step);
81    }
82
83    Some(steps)
84}
85
86/// A JSON path as MySQL, MariaDB and SQLite read it, every key quoted.
87pub fn json_path_text(steps: &[JsonPathStep]) -> String {
88    steps
89        .iter()
90        .fold(String::from("$"), |path, step| match step {
91            JsonPathStep::Member(key) => member_path(&path, key),
92            JsonPathStep::Element(index) => format!("{path}[{index}]"),
93        })
94}
95
96/// The JSON path of the member `key` below `path`, the key quoted.
97pub(crate) fn member_path(path: &str, key: &str) -> String {
98    format!("{path}.{}", serde_json::Value::from(key))
99}
100
101/// The quoted key starting at `index`, unescaped; `index` moves past it.
102fn quoted_segment(chars: &[char], index: &mut usize) -> Option<String> {
103    let quote = chars.get(*index).copied()?;
104    *index += 1;
105    let mut json = String::from("\"");
106    while *index < chars.len() {
107        let ch = chars[*index];
108        *index += 1;
109        if ch == quote {
110            json.push('"');
111            return serde_json::from_str(&json).ok();
112        }
113        if ch == '\\' {
114            let escaped = *chars.get(*index)?;
115            *index += 1;
116            if quote == '\'' && escaped == '\'' {
117                json.push('\'');
118            } else {
119                json.push('\\');
120                json.push(escaped);
121            }
122        } else {
123            if ch == '"' {
124                json.push('\\');
125            }
126            json.push(ch);
127        }
128    }
129    None
130}