sql_builder/backend/
json_path.rs1#[derive(Debug, Clone, PartialEq, Eq)]
6pub enum JsonPathStep {
7 Member(String),
9 Element(u64),
11}
12
13pub 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
25pub 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
86pub 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
96pub(crate) fn member_path(path: &str, key: &str) -> String {
98 format!("{path}.{}", serde_json::Value::from(key))
99}
100
101fn 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}