linkrs-query 0.1.0

Query engine, parser, and executor for Linkrs
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
//! Set operation evaluator
//!
//! Provide functionality for evaluating collection types, including index access, range access, and property access.

use crate::executor::expression::ExpressionError;
use linkrs_core::value::list::List;
use linkrs_core::Value;
use serde_json::Value as JsonValue;

/// Convert a serde_json::Value to a native Value
fn json_to_value_inline(json: &JsonValue) -> Value {
    match json {
        JsonValue::Null => Value::Null(linkrs_core::value::NullType::Null),
        JsonValue::Bool(b) => Value::Bool(*b),
        JsonValue::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::BigInt(i)
            } else if let Some(f) = n.as_f64() {
                Value::Double(f)
            } else {
                Value::Null(linkrs_core::value::NullType::Null)
            }
        }
        JsonValue::String(s) => Value::string(s.clone()),
        JsonValue::Array(arr) => {
            let values: Vec<Value> = arr.iter().map(json_to_value_inline).collect();
            Value::list(List::from(values))
        }
        JsonValue::Object(obj) => {
            let map: std::collections::HashMap<Value, Value> = obj
                .iter()
                .map(|(k, v)| (Value::string(k.clone()), json_to_value_inline(v)))
                .collect();
            Value::map(map)
        }
    }
}

/// Access a JSON value by subscript (string key for objects, integer index for arrays)
fn json_subscript_access(json: &JsonValue, index: &Value) -> Result<Value, ExpressionError> {
    match (json, index) {
        (JsonValue::Object(map), Value::String(key)) => map
            .get(key.as_str())
            .map(json_to_value_inline)
            .ok_or_else(|| ExpressionError::runtime_error(format!("JSON key not found: {}", key))),
        (JsonValue::Array(arr), Value::Int(i)) => {
            let idx = if *i < 0 { arr.len() as i32 + i } else { *i } as usize;
            arr.get(idx)
                .map(json_to_value_inline)
                .ok_or_else(|| ExpressionError::index_out_of_bounds(idx as isize, arr.len()))
        }
        (JsonValue::Array(arr), Value::BigInt(i)) => {
            let idx = if *i < 0 { arr.len() as i64 + i } else { *i } as usize;
            arr.get(idx)
                .map(json_to_value_inline)
                .ok_or_else(|| ExpressionError::index_out_of_bounds(idx as isize, arr.len()))
        }
        (JsonValue::Object(_), _) => Err(ExpressionError::type_error(
            "JSON object key must be a string",
        )),
        (JsonValue::Array(_), _) => Err(ExpressionError::type_error(
            "JSON array index must be an integer",
        )),
        _ => Err(ExpressionError::type_error(
            "Subscript not supported on this JSON type",
        )),
    }
}

/// Access a JSON value by property name (for property access syntax `obj.key`)
fn json_property_access(json: &JsonValue, property: &str) -> Result<Value, ExpressionError> {
    match json {
        JsonValue::Object(map) => Ok(map
            .get(property)
            .map(json_to_value_inline)
            .unwrap_or(Value::Null(linkrs_core::value::NullType::Null))),
        JsonValue::Array(arr) => {
            if let Ok(index) = property.parse::<isize>() {
                let idx = if index < 0 {
                    arr.len() as isize + index
                } else {
                    index
                } as usize;
                arr.get(idx)
                    .map(json_to_value_inline)
                    .ok_or_else(|| ExpressionError::index_out_of_bounds(idx as isize, arr.len()))
            } else {
                Err(ExpressionError::type_error(
                    "JSON array property must be an integer index",
                ))
            }
        }
        _ => Ok(Value::Null(linkrs_core::value::NullType::Null)),
    }
}

/// Set operation evaluator
pub struct CollectionOperationEvaluator;

impl CollectionOperationEvaluator {
    /// Try to convert the Value to an i64 index.
    fn value_to_i64(index: &Value) -> Option<i64> {
        match index {
            Value::SmallInt(i) => Some(*i as i64),
            Value::Int(i) => Some(*i as i64),
            Value::BigInt(i) => Some(*i),
            _ => None,
        }
    }

    /// Index access for evaluation
    pub fn eval_subscript_access(
        collection: &Value,
        index: &Value,
    ) -> Result<Value, ExpressionError> {
        if collection.is_null() || index.is_null() {
            return Ok(Value::Null(linkrs_core::value::NullType::Null));
        }

        match collection {
            Value::List(list) => {
                if let Some(i) = Self::value_to_i64(index) {
                    let adjusted_index = if i < 0 { list.len() as i64 + i } else { i };

                    if adjusted_index >= 0 && (adjusted_index as usize) < list.len() {
                        Ok(list[adjusted_index as usize].clone())
                    } else {
                        Err(ExpressionError::index_out_of_bounds(
                            adjusted_index as isize,
                            list.len(),
                        ))
                    }
                } else {
                    Err(ExpressionError::type_error(
                        "List subscripts must be integers",
                    ))
                }
            }
            Value::String(s) => {
                if let Some(i) = Self::value_to_i64(index) {
                    let chars: Vec<char> = s.chars().collect();
                    let adjusted_index = if i < 0 { chars.len() as i64 + i } else { i };

                    if adjusted_index >= 0 && (adjusted_index as usize) < chars.len() {
                        Ok(Value::string(chars[adjusted_index as usize].to_string()))
                    } else {
                        Err(ExpressionError::index_out_of_bounds(
                            adjusted_index as isize,
                            chars.len(),
                        ))
                    }
                } else {
                    Err(ExpressionError::type_error(
                        "String subscripts must be integers",
                    ))
                }
            }
            Value::Map(map) => {
                if let Value::String(key) = index {
                    map.get(&Value::string(key.clone()))
                        .cloned()
                        .ok_or_else(|| {
                            ExpressionError::runtime_error(format!(
                                "Mapping key does not exist: {}",
                                key
                            ))
                        })
                } else {
                    map.get(index).cloned().ok_or_else(|| {
                        ExpressionError::runtime_error(format!(
                            "Mapping key does not exist: {}",
                            index
                        ))
                    })
                }
            }
            Value::Struct(s) => {
                if let Value::String(key) = index {
                    s.fields
                        .iter()
                        .find(|(name, _)| name == key)
                        .map(|(_, value)| value.clone())
                        .ok_or_else(|| {
                            ExpressionError::runtime_error(format!(
                                "STRUCT field does not exist: {}",
                                key
                            ))
                        })
                } else {
                    Err(ExpressionError::type_error(
                        "STRUCT subscript key must be a string",
                    ))
                }
            }
            Value::Array(a) => {
                if let Some(i) = Self::value_to_i64(index) {
                    let adjusted_index = if i < 0 { a.values.len() as i64 + i } else { i };
                    if adjusted_index >= 0 && (adjusted_index as usize) < a.values.len() {
                        Ok(a.values[adjusted_index as usize].clone())
                    } else {
                        Err(ExpressionError::index_out_of_bounds(
                            adjusted_index as isize,
                            a.values.len(),
                        ))
                    }
                } else {
                    Err(ExpressionError::type_error(
                        "ARRAY subscripts must be integers",
                    ))
                }
            }
            Value::Json(j) => {
                let json_value = j
                    .to_value()
                    .map_err(|e| ExpressionError::type_error(format!("Invalid JSON: {}", e)))?;
                json_subscript_access(&json_value, index)
            }
            Value::JsonB(j) => json_subscript_access(j.as_value(), index),
            _ => Err(ExpressionError::type_error(
                "Types for which subscript access are not supported",
            )),
        }
    }

    /// Access to the evaluation range
    pub fn eval_range_access(
        collection: &Value,
        start: Option<&Value>,
        end: Option<&Value>,
    ) -> Result<Value, ExpressionError> {
        if collection.is_null() {
            return Ok(Value::Null(linkrs_core::value::NullType::Null));
        }

        if start.is_some_and(|v| v.is_null()) || end.is_some_and(|v| v.is_null()) {
            return Ok(Value::Null(linkrs_core::value::NullType::Null));
        }

        match collection {
            Value::List(list) => {
                let start_idx = start
                    .map(|v| {
                        if let Value::Int(i) = v {
                            if *i < 0 {
                                (list.len() as i32 + i) as usize
                            } else {
                                *i as usize
                            }
                        } else {
                            0
                        }
                    })
                    .unwrap_or(0);

                let end_idx = end
                    .map(|v| {
                        if let Value::Int(i) = v {
                            if *i < 0 {
                                (list.len() as i32 + i) as usize
                            } else {
                                *i as usize
                            }
                        } else {
                            list.len()
                        }
                    })
                    .unwrap_or(list.len());

                if start_idx <= end_idx && end_idx <= list.len() {
                    Ok(Value::list(List::from(list[start_idx..end_idx].to_vec())))
                } else {
                    Err(ExpressionError::index_out_of_bounds(
                        start_idx as isize,
                        list.len(),
                    ))
                }
            }
            Value::String(s) => {
                let chars: Vec<char> = s.chars().collect();
                let start_idx = start
                    .map(|v| {
                        if let Value::Int(i) = v {
                            if *i < 0 {
                                (chars.len() as i32 + i) as usize
                            } else {
                                *i as usize
                            }
                        } else {
                            0
                        }
                    })
                    .unwrap_or(0);

                let end_idx = end
                    .map(|v| {
                        if let Value::Int(i) = v {
                            if *i < 0 {
                                (chars.len() as i32 + i) as usize
                            } else {
                                *i as usize
                            }
                        } else {
                            chars.len()
                        }
                    })
                    .unwrap_or(chars.len());

                if start_idx <= end_idx && end_idx <= chars.len() {
                    let result: String = chars[start_idx..end_idx].iter().collect();
                    Ok(Value::string(result))
                } else {
                    Err(ExpressionError::index_out_of_bounds(
                        start_idx as isize,
                        chars.len(),
                    ))
                }
            }
            _ => Err(ExpressionError::type_error(
                "Types of scope access are not supported",
            )),
        }
    }

    /// Access to the evaluation attribute
    pub fn eval_property_access(object: &Value, property: &str) -> Result<Value, ExpressionError> {
        if object.is_null() {
            return Ok(Value::Null(linkrs_core::value::NullType::Null));
        }

        match object {
            Value::Vertex(vertex) => Ok(vertex
                .property_value(property)
                .unwrap_or_else(|| Value::Null(linkrs_core::value::NullType::Null))),
            Value::Edge(edge) => Ok(edge
                .properties()
                .get(property)
                .cloned()
                .unwrap_or(Value::Null(linkrs_core::value::NullType::Null))),
            Value::EdgeHeader(_) => Err(ExpressionError::type_error(
                "Property access on an edge identity reference is not supported: the reference carries no properties",
            )),
            Value::Map(map) => Ok(map
                .get(&Value::string(property))
                .cloned()
                .unwrap_or(Value::Null(linkrs_core::value::NullType::Null))),
            Value::Struct(s) => Ok(s
                .fields
                .iter()
                .find(|(name, _)| name == property)
                .map(|(_, value)| value.clone())
                .unwrap_or(Value::Null(linkrs_core::value::NullType::Null))),
            Value::List(list) => {
                if let Ok(index) = property.parse::<isize>() {
                    let adjusted_index = if index < 0 {
                        list.len() as isize + index
                    } else {
                        index
                    };

                    if adjusted_index >= 0 && adjusted_index < list.len() as isize {
                        Ok(list[adjusted_index as usize].clone())
                    } else {
                        Err(ExpressionError::index_out_of_bounds(
                            adjusted_index,
                            list.len(),
                        ))
                    }
                } else {
                    Err(ExpressionError::type_error("List index must be an integer"))
                }
            }
            Value::Json(j) => {
                let json_value = j
                    .to_value()
                    .map_err(|e| ExpressionError::type_error(format!("Invalid JSON: {}", e)))?;
                json_property_access(&json_value, property)
            }
            Value::JsonB(j) => json_property_access(j.as_value(), property),
            _ => Err(ExpressionError::type_error(
                "Types of property access are not supported",
            )),
        }
    }

    /// Access to evaluation attributes (Attribute operations, used for BinaryOperator::Attribute)
    /// Format the value on the right side as a string and use it as the attribute name.
    pub fn eval_attribute_access(
        object: &Value,
        attribute: &Value,
    ) -> Result<Value, ExpressionError> {
        let property = format!("{}", attribute);
        Self::eval_property_access(object, &property)
    }

    /// STRUCT field access (e.g. `addr.city`).
    ///
    /// Resolves a named field of a STRUCT value; missing fields yield NULL.
    /// Vertex/Edge/Map bases fall back to property-access semantics so
    /// tag-qualified paths such as `$$.Person.name` resolve correctly.
    pub fn eval_struct_field_access(object: &Value, field: &str) -> Result<Value, ExpressionError> {
        if object.is_null() {
            return Ok(Value::Null(linkrs_core::value::NullType::Null));
        }
        match object {
            Value::Struct(s) => Ok(s
                .fields
                .iter()
                .find(|(name, _)| name == field)
                .map(|(_, value)| value.clone())
                .unwrap_or(Value::Null(linkrs_core::value::NullType::Null))),
            _ => Self::eval_property_access(object, field),
        }
    }
}