Skip to main content

babbel_core/query/
mod.rs

1//! RFC 9535 JSONPath universal query engine.
2//!
3//! Provides query expression parsing, compilation, and evaluation over [`Value`] AST.
4
5pub mod ast;
6pub mod eval;
7pub mod parser;
8pub mod transform;
9
10use crate::error::BabbelError;
11use crate::model::Value;
12use alloc::string::{String, ToString};
13use alloc::vec::Vec;
14pub use ast::{
15    ComparisonOp, FilterExpr, FilterOperand, LocatedNode, PathQuery, QueryPath, Segment,
16};
17pub use parser::JsonPathParser;
18pub use transform::transform;
19
20/// A compiled RFC 9535 JSONPath expression.
21#[derive(Debug, Clone, PartialEq)]
22pub struct JsonPath {
23    raw: String,
24    path: QueryPath,
25}
26
27impl JsonPath {
28    /// Parse and compile a JSONPath expression string into a reusable `JsonPath` instance.
29    pub fn parse(expr: &str) -> Result<Self, BabbelError> {
30        let mut parser = JsonPathParser::new(expr);
31        let path = parser.parse()?;
32        Ok(Self {
33            raw: expr.to_string(),
34            path,
35        })
36    }
37
38    /// Query borrowed references from a `Value` root node.
39    #[inline]
40    pub fn query<'a>(&self, root: &'a Value) -> Vec<&'a Value> {
41        eval::evaluate(&self.path, root)
42    }
43
44    /// Query matched nodes alongside their RFC 9535 normalized paths and RFC 6901 JSON Pointers.
45    #[inline]
46    pub fn query_located<'a>(&self, root: &'a Value) -> Vec<LocatedNode<'a>> {
47        eval::evaluate_located(&self.path, root)
48    }
49
50    /// Query mutable references from a mutable `Value` root node.
51    #[inline]
52    pub fn query_mut<'a>(&self, root: &'a mut Value) -> Vec<&'a mut Value> {
53        eval::evaluate_mut(&self.path, root)
54    }
55
56    /// Returns the raw JSONPath expression string.
57    #[inline]
58    pub fn as_str(&self) -> &str {
59        &self.raw
60    }
61
62    /// Returns reference to internal `QueryPath` AST.
63    #[inline]
64    pub fn ast(&self) -> &QueryPath {
65        &self.path
66    }
67}
68
69/// Convenience function to compile and evaluate a JSONPath expression on a `Value` in one step.
70pub fn query<'a>(root: &'a Value, expr: &str) -> Result<Vec<&'a Value>, BabbelError> {
71    let path = JsonPath::parse(expr)?;
72    Ok(path.query(root))
73}
74
75/// Convenience function to compile and evaluate a JSONPath expression returning located nodes.
76pub fn query_located<'a>(root: &'a Value, expr: &str) -> Result<Vec<LocatedNode<'a>>, BabbelError> {
77    let path = JsonPath::parse(expr)?;
78    Ok(path.query_located(root))
79}
80
81/// Convenience function to compile and evaluate a mutable JSONPath expression on a `Value` in one step.
82pub fn query_mut<'a>(root: &'a mut Value, expr: &str) -> Result<Vec<&'a mut Value>, BabbelError> {
83    let path = JsonPath::parse(expr)?;
84    Ok(path.query_mut(root))
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90    use alloc::string::ToString;
91    use alloc::vec;
92
93    fn sample_bookstore() -> Value {
94        Value::Object(vec![(
95            "store".to_string(),
96            Value::Object(vec![
97                (
98                    "books".to_string(),
99                    Value::Array(vec![
100                        Value::Object(vec![
101                            (
102                                "category".to_string(),
103                                Value::String("reference".to_string()),
104                            ),
105                            (
106                                "author".to_string(),
107                                Value::String("Nigel Rees".to_string()),
108                            ),
109                            (
110                                "title".to_string(),
111                                Value::String("Sayings of the Century".to_string()),
112                            ),
113                            ("price".to_string(), Value::Float(8.95)),
114                            ("active".to_string(), Value::Bool(true)),
115                        ]),
116                        Value::Object(vec![
117                            ("category".to_string(), Value::String("fiction".to_string())),
118                            (
119                                "author".to_string(),
120                                Value::String("Evelyn Waugh".to_string()),
121                            ),
122                            (
123                                "title".to_string(),
124                                Value::String("Sword of Honour".to_string()),
125                            ),
126                            ("price".to_string(), Value::Float(12.99)),
127                            ("active".to_string(), Value::Bool(false)),
128                        ]),
129                        Value::Object(vec![
130                            ("category".to_string(), Value::String("fiction".to_string())),
131                            (
132                                "author".to_string(),
133                                Value::String("Herman Melville".to_string()),
134                            ),
135                            ("title".to_string(), Value::String("Moby Dick".to_string())),
136                            (
137                                "isbn".to_string(),
138                                Value::String("0-553-21311-3".to_string()),
139                            ),
140                            ("price".to_string(), Value::Float(8.99)),
141                            ("active".to_string(), Value::Bool(true)),
142                        ]),
143                        Value::Object(vec![
144                            ("category".to_string(), Value::String("fiction".to_string())),
145                            (
146                                "author".to_string(),
147                                Value::String("J. R. R. Tolkien".to_string()),
148                            ),
149                            (
150                                "title".to_string(),
151                                Value::String("The Lord of the Rings".to_string()),
152                            ),
153                            (
154                                "isbn".to_string(),
155                                Value::String("0-395-19395-8".to_string()),
156                            ),
157                            ("price".to_string(), Value::Float(22.99)),
158                            ("active".to_string(), Value::Bool(true)),
159                        ]),
160                    ]),
161                ),
162                (
163                    "bicycle".to_string(),
164                    Value::Object(vec![
165                        ("color".to_string(), Value::String("red".to_string())),
166                        ("price".to_string(), Value::Float(19.95)),
167                    ]),
168                ),
169            ]),
170        )])
171    }
172
173    #[test]
174    fn test_dot_and_bracket_navigation() {
175        let root = sample_bookstore();
176        let bicycle_color = query(&root, "$.store.bicycle.color").unwrap();
177        assert_eq!(bicycle_color.len(), 1);
178        assert_eq!(bicycle_color[0].as_str(), Some("red"));
179
180        let bicycle_color_bracket = query(&root, "$['store']['bicycle']['color']").unwrap();
181        assert_eq!(bicycle_color_bracket.len(), 1);
182        assert_eq!(bicycle_color_bracket[0].as_str(), Some("red"));
183    }
184
185    #[test]
186    fn test_wildcard_and_array_indexing() {
187        let root = sample_bookstore();
188        let all_authors = query(&root, "$.store.books[*].author").unwrap();
189        assert_eq!(all_authors.len(), 4);
190        assert_eq!(all_authors[0].as_str(), Some("Nigel Rees"));
191        assert_eq!(all_authors[3].as_str(), Some("J. R. R. Tolkien"));
192
193        let first_author = query(&root, "$.store.books[0].author").unwrap();
194        assert_eq!(first_author.len(), 1);
195        assert_eq!(first_author[0].as_str(), Some("Nigel Rees"));
196
197        let last_author = query(&root, "$.store.books[-1].author").unwrap();
198        assert_eq!(last_author.len(), 1);
199        assert_eq!(last_author[0].as_str(), Some("J. R. R. Tolkien"));
200    }
201
202    #[test]
203    fn test_slice_operations() {
204        let numbers = Value::Array(vec![
205            Value::Integer(10),
206            Value::Integer(20),
207            Value::Integer(30),
208            Value::Integer(40),
209            Value::Integer(50),
210        ]);
211
212        let slice_0_2 = query(&numbers, "$[0:2]").unwrap();
213        assert_eq!(slice_0_2.len(), 2);
214        assert_eq!(slice_0_2[0].as_i64(), Some(10));
215        assert_eq!(slice_0_2[1].as_i64(), Some(20));
216
217        let slice_step = query(&numbers, "$[::2]").unwrap();
218        assert_eq!(slice_step.len(), 3);
219        assert_eq!(slice_step[0].as_i64(), Some(10));
220        assert_eq!(slice_step[1].as_i64(), Some(30));
221        assert_eq!(slice_step[2].as_i64(), Some(50));
222    }
223
224    #[test]
225    fn test_recursive_descent() {
226        let root = sample_bookstore();
227        let all_titles = query(&root, "$..title").unwrap();
228        assert_eq!(all_titles.len(), 4);
229
230        let all_prices = query(&root, "$..price").unwrap();
231        // 4 books + 1 bicycle = 5 prices
232        assert_eq!(all_prices.len(), 5);
233    }
234
235    #[test]
236    fn test_filter_expressions() {
237        let root = sample_bookstore();
238
239        // Books with price < 10
240        let cheap_books = query(&root, "$.store.books[?(@.price < 10.0)].title").unwrap();
241        assert_eq!(cheap_books.len(), 2);
242        assert_eq!(cheap_books[0].as_str(), Some("Sayings of the Century"));
243        assert_eq!(cheap_books[1].as_str(), Some("Moby Dick"));
244
245        // Books with isbn property
246        let books_with_isbn = query(&root, "$.store.books[?(@.isbn)].title").unwrap();
247        assert_eq!(books_with_isbn.len(), 2);
248
249        // Books where active is true and category == 'fiction'
250        let active_fiction = query(
251            &root,
252            "$.store.books[?(@.active == true && @.category == 'fiction')].title",
253        )
254        .unwrap();
255        assert_eq!(active_fiction.len(), 2);
256        assert_eq!(active_fiction[0].as_str(), Some("Moby Dick"));
257        assert_eq!(active_fiction[1].as_str(), Some("The Lord of the Rings"));
258    }
259
260    #[test]
261    fn test_mutable_query() {
262        let mut root = sample_bookstore();
263        {
264            let mut matches = query_mut(&mut root, "$.store.bicycle.color").unwrap();
265            assert_eq!(matches.len(), 1);
266            *matches[0] = Value::String("blue".to_string());
267        }
268
269        let updated_color = query(&root, "$.store.bicycle.color").unwrap();
270        assert_eq!(updated_color[0].as_str(), Some("blue"));
271    }
272
273    #[test]
274    fn test_mutable_query_with_filter() {
275        let mut root = sample_bookstore();
276        {
277            let mut cheap = query_mut(&mut root, "$.store.books[?(@.price < 10.0)].price").unwrap();
278            assert_eq!(cheap.len(), 2);
279            for p in &mut cheap {
280                **p = Value::Float(5.0);
281            }
282        }
283        let still_under_6 = query(&root, "$.store.books[?(@.price < 6.0)].title").unwrap();
284        assert_eq!(still_under_6.len(), 2);
285    }
286
287    #[test]
288    fn test_rfc9535_functions_match_search_value() {
289        let root = sample_bookstore();
290        let matched = query(&root, "$.store.books[?match(@.author, '^Evelyn.*')].title").unwrap();
291        assert_eq!(matched.len(), 1);
292        assert_eq!(matched[0].as_str(), Some("Sword of Honour"));
293
294        let searched = query(&root, "$.store.books[?search(@.title, 'Lord|Dick')].author").unwrap();
295        assert_eq!(searched.len(), 2);
296        assert_eq!(searched[0].as_str(), Some("Herman Melville"));
297        assert_eq!(searched[1].as_str(), Some("J. R. R. Tolkien"));
298
299        let val_fn = query(
300            &root,
301            "$.store.books[?(value(@.category) == 'reference')].author",
302        )
303        .unwrap();
304        assert_eq!(val_fn.len(), 1);
305        assert_eq!(val_fn[0].as_str(), Some("Nigel Rees"));
306    }
307
308    #[test]
309    fn test_located_query_and_union() {
310        let root = sample_bookstore();
311        let located = query_located(&root, "$.store.books[0, 2].title").unwrap();
312        assert_eq!(located.len(), 2);
313        assert_eq!(located[0].path, "$['store']['books'][0]['title']");
314        assert_eq!(located[0].pointer, "/store/books/0/title");
315        assert_eq!(located[0].value.as_str(), Some("Sayings of the Century"));
316        assert_eq!(located[1].path, "$['store']['books'][2]['title']");
317        assert_eq!(located[1].pointer, "/store/books/2/title");
318        assert_eq!(located[1].value.as_str(), Some("Moby Dick"));
319    }
320
321    #[test]
322    fn test_transform_pipeline() {
323        let root = sample_bookstore();
324        let avg_price = transform(&root, "$.store.books[*].price | sum").unwrap();
325        assert!((avg_price.as_f64().unwrap() - 53.92).abs() < 1e-6);
326
327        let sorted_titles = transform(
328            &root,
329            "$.store.books[*] | select(.category == 'fiction') | sort_by(.price) | map(.title)",
330        )
331        .unwrap();
332        let arr = sorted_titles.as_array().unwrap();
333        assert_eq!(arr.len(), 3);
334        assert_eq!(arr[0].as_str(), Some("Moby Dick"));
335        assert_eq!(arr[1].as_str(), Some("Sword of Honour"));
336        assert_eq!(arr[2].as_str(), Some("The Lord of the Rings"));
337    }
338}