nodedb-query 0.1.1

Shared query evaluation engine for NodeDB — expressions, filters, functions, aggregations, window functions
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
// SPDX-License-Identifier: Apache-2.0

//! Geospatial SQL function evaluation.
//!
//! All ST_* predicates, geometry operations, and geo_* utility functions.
//! Called from `functions::eval_function` for any geo-prefixed or ST_-prefixed name.

use crate::value_ops::{to_value_number, value_to_f64};
use nodedb_types::Value;

/// Try to evaluate a geo/spatial function. Returns `Some(result)` if the
/// function name matched, `None` if unrecognized (caller falls through).
pub fn eval_geo_function(name: &str, args: &[Value]) -> Option<Value> {
    let result = match name {
        "geo_distance" | "haversine_distance" => {
            let lng1 = num_arg(args, 0).unwrap_or(0.0);
            let lat1 = num_arg(args, 1).unwrap_or(0.0);
            let lng2 = num_arg(args, 2).unwrap_or(0.0);
            let lat2 = num_arg(args, 3).unwrap_or(0.0);
            to_value_number(nodedb_types::geometry::haversine_distance(
                lng1, lat1, lng2, lat2,
            ))
        }
        "geo_bearing" | "haversine_bearing" => {
            let lng1 = num_arg(args, 0).unwrap_or(0.0);
            let lat1 = num_arg(args, 1).unwrap_or(0.0);
            let lng2 = num_arg(args, 2).unwrap_or(0.0);
            let lat2 = num_arg(args, 3).unwrap_or(0.0);
            to_value_number(nodedb_types::geometry::haversine_bearing(
                lng1, lat1, lng2, lat2,
            ))
        }
        "geo_point" | "st_point" => {
            let lng = num_arg(args, 0).unwrap_or(0.0);
            let lat = num_arg(args, 1).unwrap_or(0.0);
            Value::Geometry(nodedb_types::geometry::Geometry::point(lng, lat))
        }
        "geo_geohash" => {
            let lng = num_arg(args, 0).unwrap_or(0.0);
            let lat = num_arg(args, 1).unwrap_or(0.0);
            let precision = num_arg(args, 2).unwrap_or(6.0) as u8;
            Value::String(nodedb_spatial::geohash_encode(lng, lat, precision))
        }
        "geo_geohash_decode" => {
            let hash = str_arg(args, 0).unwrap_or_default();
            match nodedb_spatial::geohash_decode(&hash) {
                Some(bb) => {
                    let mut map = std::collections::HashMap::new();
                    map.insert("min_lng".to_string(), Value::Float(bb.min_lng));
                    map.insert("min_lat".to_string(), Value::Float(bb.min_lat));
                    map.insert("max_lng".to_string(), Value::Float(bb.max_lng));
                    map.insert("max_lat".to_string(), Value::Float(bb.max_lat));
                    Value::Object(map)
                }
                None => Value::Null,
            }
        }
        "geo_geohash_neighbors" => {
            let hash = str_arg(args, 0).unwrap_or_default();
            let neighbors = nodedb_spatial::geohash_neighbors(&hash);
            let arr: Vec<Value> = neighbors
                .into_iter()
                .map(|(dir, h)| {
                    let mut map = std::collections::HashMap::new();
                    map.insert("direction".to_string(), Value::String(format!("{dir:?}")));
                    map.insert("hash".to_string(), Value::String(h));
                    Value::Object(map)
                })
                .collect();
            Value::Array(arr)
        }

        // ── Spatial predicates (ST_*) ──
        "st_contains" => geo_predicate_2(args, nodedb_spatial::st_contains),
        "st_intersects" => geo_predicate_2(args, nodedb_spatial::st_intersects),
        "st_within" => geo_predicate_2(args, nodedb_spatial::st_within),
        "st_disjoint" => geo_predicate_2(args, nodedb_spatial::st_disjoint),
        "st_dwithin" => {
            let (Some(a), Some(b)) = (geom_arg(args, 0), geom_arg(args, 1)) else {
                return Some(Value::Null);
            };
            let dist = num_arg(args, 2).unwrap_or(0.0);
            Value::Bool(nodedb_spatial::st_dwithin(&a, &b, dist))
        }
        "st_distance" => {
            let (Some(a), Some(b)) = (geom_arg(args, 0), geom_arg(args, 1)) else {
                return Some(Value::Null);
            };
            to_value_number(nodedb_spatial::st_distance(&a, &b))
        }
        "st_buffer" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            let dist = num_arg(args, 1).unwrap_or(0.0);
            let segs = num_arg(args, 2).unwrap_or(32.0) as usize;
            Value::Geometry(nodedb_spatial::st_buffer(&geom, dist, segs))
        }
        "st_envelope" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            Value::Geometry(nodedb_spatial::st_envelope(&geom))
        }
        "st_union" => {
            let (Some(a), Some(b)) = (geom_arg(args, 0), geom_arg(args, 1)) else {
                return Some(Value::Null);
            };
            Value::Geometry(nodedb_spatial::st_union(&a, &b))
        }

        // ── Extended geo functions ──
        "geo_length" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            to_value_number(geo_linestring_length(&geom))
        }
        "geo_perimeter" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            to_value_number(geo_polygon_perimeter(&geom))
        }
        "geo_line" => {
            let coords: Vec<[f64; 2]> = args
                .iter()
                .filter_map(|v| {
                    let geom = v.as_geometry()?;
                    if let nodedb_types::geometry::Geometry::Point { coordinates } = geom {
                        Some(*coordinates)
                    } else {
                        None
                    }
                })
                .collect();
            if coords.len() < 2 {
                Value::Null
            } else {
                Value::Geometry(nodedb_types::geometry::Geometry::line_string(coords))
            }
        }
        "geo_polygon" => {
            // Args are arrays of coordinate pairs. Convert from Value::Array.
            let rings: Vec<Vec<[f64; 2]>> = args
                .iter()
                .filter_map(|v| {
                    let arr = v.as_array()?;
                    let coords: Vec<[f64; 2]> = arr
                        .iter()
                        .filter_map(|pt| {
                            let inner = pt.as_array()?;
                            if inner.len() >= 2 {
                                Some([inner[0].as_f64()?, inner[1].as_f64()?])
                            } else {
                                None
                            }
                        })
                        .collect();
                    if coords.is_empty() {
                        None
                    } else {
                        Some(coords)
                    }
                })
                .collect();
            if rings.is_empty() {
                Value::Null
            } else {
                Value::Geometry(nodedb_types::geometry::Geometry::polygon(rings))
            }
        }
        "geo_circle" => {
            let lng = num_arg(args, 0).unwrap_or(0.0);
            let lat = num_arg(args, 1).unwrap_or(0.0);
            let radius = num_arg(args, 2).unwrap_or(0.0);
            let segs = num_arg(args, 3).unwrap_or(32.0) as usize;
            let circle = nodedb_spatial::st_buffer(
                &nodedb_types::geometry::Geometry::point(lng, lat),
                radius,
                segs,
            );
            Value::Geometry(circle)
        }
        "geo_bbox" => {
            let min_lng = num_arg(args, 0).unwrap_or(0.0);
            let min_lat = num_arg(args, 1).unwrap_or(0.0);
            let max_lng = num_arg(args, 2).unwrap_or(0.0);
            let max_lat = num_arg(args, 3).unwrap_or(0.0);
            Value::Geometry(nodedb_types::geometry::Geometry::polygon(vec![vec![
                [min_lng, min_lat],
                [max_lng, min_lat],
                [max_lng, max_lat],
                [min_lng, max_lat],
                [min_lng, min_lat],
            ]]))
        }
        "geo_as_geojson" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            match sonic_rs::to_string(&geom) {
                Ok(s) => Value::String(s),
                Err(_) => Value::Null,
            }
        }
        "geo_from_geojson" => {
            let s = str_arg(args, 0).unwrap_or_default();
            match sonic_rs::from_str::<nodedb_types::geometry::Geometry>(&s) {
                Ok(g) => Value::Geometry(g),
                Err(_) => Value::Null,
            }
        }
        "geo_as_wkt" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            Value::String(nodedb_spatial::geometry_to_wkt(&geom))
        }
        "geo_from_wkt" => {
            let s = str_arg(args, 0).unwrap_or_default();
            match nodedb_spatial::geometry_from_wkt(&s) {
                Some(g) => Value::Geometry(g),
                None => Value::Null,
            }
        }
        "geo_x" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            if let nodedb_types::geometry::Geometry::Point { coordinates } = geom {
                to_value_number(coordinates[0])
            } else {
                Value::Null
            }
        }
        "geo_y" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            if let nodedb_types::geometry::Geometry::Point { coordinates } = geom {
                to_value_number(coordinates[1])
            } else {
                Value::Null
            }
        }
        "geo_num_points" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            Value::Integer(count_points(&geom) as i64)
        }
        "geo_type" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            Value::String(geom.geometry_type().to_string())
        }
        "geo_is_valid" => {
            let Some(geom) = geom_arg(args, 0) else {
                return Some(Value::Null);
            };
            Value::Bool(nodedb_spatial::is_valid(&geom))
        }

        // ── H3 hexagonal index ──
        "geo_h3" => {
            let lng = num_arg(args, 0).unwrap_or(0.0);
            let lat = num_arg(args, 1).unwrap_or(0.0);
            let resolution = num_arg(args, 2).unwrap_or(7.0) as u8;
            match nodedb_spatial::h3::h3_encode_string(lng, lat, resolution) {
                Some(hex) => Value::String(hex),
                None => Value::Null,
            }
        }
        "geo_h3_to_boundary" => {
            let h3_str = str_arg(args, 0).unwrap_or_default();
            let h3_idx = u64::from_str_radix(&h3_str, 16).unwrap_or(0);
            if !nodedb_spatial::h3::h3_is_valid(h3_idx) {
                return Some(Value::Null);
            }
            match nodedb_spatial::h3::h3_to_boundary(h3_idx) {
                Some(geom) => Value::Geometry(geom),
                None => Value::Null,
            }
        }
        "geo_h3_resolution" => {
            let h3_str = str_arg(args, 0).unwrap_or_default();
            let h3_idx = u64::from_str_radix(&h3_str, 16).unwrap_or(0);
            if !nodedb_spatial::h3::h3_is_valid(h3_idx) {
                return Some(Value::Null);
            }
            match nodedb_spatial::h3::h3_resolution(h3_idx) {
                Some(r) => Value::Integer(r as i64),
                None => Value::Null,
            }
        }
        // ── SQL-aliased geohash/H3 encode/decode ──
        "st_geohash" => {
            let lng = num_arg(args, 0).unwrap_or(0.0);
            let lat = num_arg(args, 1).unwrap_or(0.0);
            let precision = num_arg(args, 2).unwrap_or(6.0) as u8;
            Value::String(nodedb_spatial::geohash_encode(lng, lat, precision))
        }
        "st_geohashdecode" => {
            let hash = str_arg(args, 0).unwrap_or_default();
            match nodedb_spatial::geohash_decode(&hash) {
                Some(bb) => {
                    let mut map = std::collections::HashMap::new();
                    map.insert("min_lng".to_string(), Value::Float(bb.min_lng));
                    map.insert("min_lat".to_string(), Value::Float(bb.min_lat));
                    map.insert("max_lng".to_string(), Value::Float(bb.max_lng));
                    map.insert("max_lat".to_string(), Value::Float(bb.max_lat));
                    Value::Object(map)
                }
                None => Value::Null,
            }
        }
        "h3_latlngtocell" => {
            let lat = num_arg(args, 0).unwrap_or(0.0);
            let lng = num_arg(args, 1).unwrap_or(0.0);
            let resolution = num_arg(args, 2).unwrap_or(7.0) as u8;
            match nodedb_spatial::h3::h3_encode_string(lng, lat, resolution) {
                Some(hex) => Value::String(hex),
                None => Value::Null,
            }
        }
        "h3_celltolatlng" => {
            let h3_str = str_arg(args, 0).unwrap_or_default();
            let h3_idx = u64::from_str_radix(&h3_str, 16).unwrap_or(0);
            if !nodedb_spatial::h3::h3_is_valid(h3_idx) {
                return Some(Value::Null);
            }
            match nodedb_spatial::h3::h3_to_center(h3_idx) {
                Some((lng, lat)) => {
                    let mut map = std::collections::HashMap::new();
                    map.insert("lat".to_string(), Value::Float(lat));
                    map.insert("lng".to_string(), Value::Float(lng));
                    Value::Object(map)
                }
                None => Value::Null,
            }
        }
        "st_intersection" => {
            let (Some(a), Some(b)) = (geom_arg(args, 0), geom_arg(args, 1)) else {
                return Some(Value::Null);
            };
            Value::Geometry(nodedb_spatial::st_intersection(&a, &b))
        }
        _ => return None,
    };
    Some(result)
}

// ── Helpers ──

fn str_arg(args: &[Value], idx: usize) -> Option<String> {
    args.get(idx)?.as_str().map(|s| s.to_string())
}

fn num_arg(args: &[Value], idx: usize) -> Option<f64> {
    args.get(idx).and_then(|v| value_to_f64(v, true))
}

/// Extract a geometry argument. Supports `Value::Geometry` directly,
/// or falls back to JSON deserialization for `Value::Object` (GeoJSON).
fn geom_arg(args: &[Value], idx: usize) -> Option<nodedb_types::geometry::Geometry> {
    match args.get(idx)? {
        Value::Geometry(g) => Some(g.clone()),
        // GeoJSON string: produced when a Geometry constant was round-tripped
        // through the const-fold SqlValue path (e.g. ST_Distance(ST_Point(...), ST_Point(...))).
        Value::String(s) => sonic_rs::from_str::<nodedb_types::geometry::Geometry>(s).ok(),
        other => {
            // Fallback: convert Value → JSON → Geometry for GeoJSON objects.
            let json = serde_json::Value::from(other.clone());
            serde_json::from_value(json).ok()
        }
    }
}

fn geo_predicate_2(
    args: &[Value],
    f: fn(&nodedb_types::geometry::Geometry, &nodedb_types::geometry::Geometry) -> bool,
) -> Value {
    let (Some(a), Some(b)) = (geom_arg(args, 0), geom_arg(args, 1)) else {
        return Value::Null;
    };
    Value::Bool(f(&a, &b))
}

fn geo_linestring_length(geom: &nodedb_types::geometry::Geometry) -> f64 {
    let coords = match geom {
        nodedb_types::geometry::Geometry::LineString { coordinates } => coordinates,
        _ => return 0.0,
    };
    let mut total = 0.0;
    for i in 0..coords.len().saturating_sub(1) {
        total += nodedb_types::geometry::haversine_distance(
            coords[i][0],
            coords[i][1],
            coords[i + 1][0],
            coords[i + 1][1],
        );
    }
    total
}

fn geo_polygon_perimeter(geom: &nodedb_types::geometry::Geometry) -> f64 {
    let rings = match geom {
        nodedb_types::geometry::Geometry::Polygon { coordinates } => coordinates,
        _ => return 0.0,
    };
    let Some(exterior) = rings.first() else {
        return 0.0;
    };
    let mut total = 0.0;
    for i in 0..exterior.len().saturating_sub(1) {
        total += nodedb_types::geometry::haversine_distance(
            exterior[i][0],
            exterior[i][1],
            exterior[i + 1][0],
            exterior[i + 1][1],
        );
    }
    total
}

fn count_points(geom: &nodedb_types::geometry::Geometry) -> usize {
    use nodedb_types::geometry::Geometry;
    match geom {
        Geometry::Point { .. } => 1,
        Geometry::LineString { coordinates } => coordinates.len(),
        Geometry::Polygon { coordinates } => coordinates.iter().map(|r| r.len()).sum(),
        Geometry::MultiPoint { coordinates } => coordinates.len(),
        Geometry::MultiLineString { coordinates } => coordinates.iter().map(|ls| ls.len()).sum(),
        Geometry::MultiPolygon { coordinates } => coordinates
            .iter()
            .flat_map(|poly| poly.iter())
            .map(|ring| ring.len())
            .sum(),
        Geometry::GeometryCollection { geometries } => geometries.iter().map(count_points).sum(),
        _ => 0,
    }
}