vibesql-executor 0.2.0

Query execution engine for vibesql SQL database
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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! Spatial Measurement Functions
//!
//! Implements distance, area, length, centroid, and other measurement functions.
//! Uses geo-types and geo crate algorithms.

#![cfg(feature = "spatial")]

use geo::{
    algorithm::{Area, BoundingRect, Centroid, ConvexHull},
    Distance, Euclidean,
};
use vibesql_types::SqlValue;

use super::{sql_value_to_geometry, Geometry};
use crate::errors::ExecutorError;

/// Helper function to convert WKT string to geo::Geometry
fn wkt_to_geo(wkt_str: &str) -> Result<geo::Geometry<f64>, ExecutorError> {
    // Parse WKT string into internal Geometry enum
    let sql_value = SqlValue::Varchar(arcstr::ArcStr::from(wkt_str));
    let geom_with_srid = sql_value_to_geometry(&sql_value)?;

    // Convert internal Geometry to geo::Geometry
    to_geo_geometry(&geom_with_srid.geometry)
}

/// Convert internal Geometry to geo::Geometry for spatial operations
fn to_geo_geometry(geom: &Geometry) -> Result<geo::Geometry<f64>, ExecutorError> {
    match geom {
        Geometry::Point { x, y } => Ok(geo::Geometry::Point(geo::Point::new(*x, *y))),
        Geometry::LineString { points } => {
            let coords: Vec<geo::Coord<f64>> =
                points.iter().map(|(x, y)| geo::Coord { x: *x, y: *y }).collect();
            Ok(geo::Geometry::LineString(geo::LineString(coords)))
        }
        Geometry::Polygon { rings } => {
            if rings.is_empty() {
                return Err(ExecutorError::SpatialGeometryError {
                    function_name: "to_geo_geometry".to_string(),
                    message: "Empty polygon".to_string(),
                });
            }

            let exterior: Vec<geo::Coord<f64>> =
                rings[0].iter().map(|(x, y)| geo::Coord { x: *x, y: *y }).collect();
            let exterior_ring = geo::LineString(exterior);

            let interiors: Vec<geo::LineString<f64>> = rings[1..]
                .iter()
                .map(|ring| {
                    let coords: Vec<geo::Coord<f64>> =
                        ring.iter().map(|(x, y)| geo::Coord { x: *x, y: *y }).collect();
                    geo::LineString(coords)
                })
                .collect();

            Ok(geo::Geometry::Polygon(geo::Polygon::new(exterior_ring, interiors)))
        }
        Geometry::MultiPoint { points } => {
            let points: Vec<geo::Point<f64>> =
                points.iter().map(|(x, y)| geo::Point::new(*x, *y)).collect();
            Ok(geo::Geometry::MultiPoint(geo::MultiPoint(points)))
        }
        Geometry::MultiLineString { lines } => {
            let lines: Vec<geo::LineString<f64>> = lines
                .iter()
                .map(|line| {
                    let coords: Vec<geo::Coord<f64>> =
                        line.iter().map(|(x, y)| geo::Coord { x: *x, y: *y }).collect();
                    geo::LineString(coords)
                })
                .collect();
            Ok(geo::Geometry::MultiLineString(geo::MultiLineString(lines)))
        }
        Geometry::MultiPolygon { polygons } => {
            let polys: Vec<geo::Polygon<f64>> = polygons
                .iter()
                .map(|poly_rings| {
                    if poly_rings.is_empty() {
                        Err(ExecutorError::SpatialGeometryError {
                            function_name: "to_geo_geometry".to_string(),
                            message: "Empty polygon in multipolygon".to_string(),
                        })
                    } else {
                        let exterior: Vec<geo::Coord<f64>> = poly_rings[0]
                            .iter()
                            .map(|(x, y)| geo::Coord { x: *x, y: *y })
                            .collect();
                        let exterior_ring = geo::LineString(exterior);

                        let interiors: Vec<geo::LineString<f64>> = poly_rings[1..]
                            .iter()
                            .map(|ring| {
                                let coords: Vec<geo::Coord<f64>> =
                                    ring.iter().map(|(x, y)| geo::Coord { x: *x, y: *y }).collect();
                                geo::LineString(coords)
                            })
                            .collect();

                        Ok(geo::Polygon::new(exterior_ring, interiors))
                    }
                })
                .collect::<Result<Vec<_>, _>>()?;
            Ok(geo::Geometry::MultiPolygon(geo::MultiPolygon(polys)))
        }
        Geometry::Collection { geometries } => {
            let geoms: Vec<geo::Geometry<f64>> =
                geometries.iter().map(to_geo_geometry).collect::<Result<Vec<_>, _>>()?;
            Ok(geo::Geometry::GeometryCollection(geo::GeometryCollection(geoms)))
        }
    }
}

/// Convert geo::Geometry back to internal Geometry representation
#[allow(dead_code)]
fn from_geo_geometry(geom: &geo::Geometry<f64>) -> Result<Geometry, ExecutorError> {
    match geom {
        geo::Geometry::Point(p) => Ok(Geometry::Point { x: p.x(), y: p.y() }),
        geo::Geometry::LineString(ls) => {
            let points = ls.coords().map(|c| (c.x, c.y)).collect();
            Ok(Geometry::LineString { points })
        }
        geo::Geometry::Polygon(poly) => {
            let mut rings = vec![];
            let exterior: Vec<(f64, f64)> = poly.exterior().coords().map(|c| (c.x, c.y)).collect();
            rings.push(exterior);
            for interior in poly.interiors() {
                let ring: Vec<(f64, f64)> = interior.coords().map(|c| (c.x, c.y)).collect();
                rings.push(ring);
            }
            Ok(Geometry::Polygon { rings })
        }
        geo::Geometry::MultiPoint(mp) => {
            let points = mp.0.iter().map(|p| (p.x(), p.y())).collect();
            Ok(Geometry::MultiPoint { points })
        }
        geo::Geometry::MultiLineString(mls) => {
            let lines = mls.0.iter().map(|ls| ls.coords().map(|c| (c.x, c.y)).collect()).collect();
            Ok(Geometry::MultiLineString { lines })
        }
        geo::Geometry::MultiPolygon(mp) => {
            let polygons = mp
                .0
                .iter()
                .map(|poly| {
                    let mut rings = vec![];
                    let exterior: Vec<(f64, f64)> =
                        poly.exterior().coords().map(|c| (c.x, c.y)).collect();
                    rings.push(exterior);
                    for interior in poly.interiors() {
                        let ring: Vec<(f64, f64)> = interior.coords().map(|c| (c.x, c.y)).collect();
                        rings.push(ring);
                    }
                    rings
                })
                .collect();
            Ok(Geometry::MultiPolygon { polygons })
        }
        geo::Geometry::GeometryCollection(gc) => {
            let geometries = gc.0.iter().map(from_geo_geometry).collect::<Result<Vec<_>, _>>()?;
            Ok(Geometry::Collection { geometries })
        }
        _ => Err(ExecutorError::UnsupportedFeature(
            "Geometry type not yet supported for measurements".to_string(),
        )),
    }
}

/// ST_Distance(geom1, geom2) - Calculate Euclidean distance between geometries
pub fn st_distance(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 2 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Distance".to_string(),
            expected: "exactly 2 arguments".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match (&args[0], &args[1]) {
        (SqlValue::Null, _) | (_, SqlValue::Null) => Ok(SqlValue::Null),
        (
            SqlValue::Varchar(wkt1) | SqlValue::Character(wkt1),
            SqlValue::Varchar(wkt2) | SqlValue::Character(wkt2),
        ) => {
            let geom1 = wkt_to_geo(wkt1)?;
            let geom2 = wkt_to_geo(wkt2)?;

            let distance = match (&geom1, &geom2) {
                (geo::Geometry::Point(p1), geo::Geometry::Point(p2)) => {
                    Euclidean.distance(*p1, *p2)
                }
                _ => {
                    // For other geometry types, calculate minimum distance
                    // between any two points in the geometries
                    // This is a simplified version - full implementation would handle all types
                    match (&geom1, &geom2) {
                        (geo::Geometry::Point(p), geo::Geometry::LineString(ls))
                        | (geo::Geometry::LineString(ls), geo::Geometry::Point(p)) => ls
                            .coords()
                            .map(|coord| {
                                let p2 = geo::Point::new(coord.x, coord.y);
                                Euclidean.distance(*p, p2)
                            })
                            .fold(f64::INFINITY, f64::min),
                        (geo::Geometry::Point(p), geo::Geometry::Polygon(poly))
                        | (geo::Geometry::Polygon(poly), geo::Geometry::Point(p)) => poly
                            .exterior()
                            .coords()
                            .map(|coord| {
                                let p2 = geo::Point::new(coord.x, coord.y);
                                Euclidean.distance(*p, p2)
                            })
                            .fold(f64::INFINITY, f64::min),
                        _ => {
                            return Err(ExecutorError::SpatialOperationFailed {
                                function_name: "ST_Distance".to_string(),
                                message: "not fully supported between these geometry types"
                                    .to_string(),
                            });
                        }
                    }
                }
            };

            Ok(SqlValue::Double(distance))
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Distance".to_string(),
            expected: "VARCHAR geometry arguments".to_string(),
            actual: format!("{:?}, {:?}", args[0].type_name(), args[1].type_name()),
        }),
    }
}

/// ST_Length(geom) - Calculate length of LineString
pub fn st_length(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 1 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Length".to_string(),
            expected: "exactly 1 argument".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match &args[0] {
        SqlValue::Null => Ok(SqlValue::Null),
        SqlValue::Varchar(wkt) | SqlValue::Character(wkt) => {
            let geom = wkt_to_geo(wkt)?;

            // Calculate length by summing distances between consecutive points
            fn calculate_length<'a>(coords: impl Iterator<Item = &'a geo::Coord<f64>>) -> f64 {
                let coords_vec: Vec<_> = coords.collect();
                let mut length = 0.0;
                for i in 0..coords_vec.len().saturating_sub(1) {
                    let p1 = geo::Point::new(coords_vec[i].x, coords_vec[i].y);
                    let p2 = geo::Point::new(coords_vec[i + 1].x, coords_vec[i + 1].y);
                    length += Euclidean.distance(p1, p2);
                }
                length
            }

            match geom {
                geo::Geometry::LineString(ls) => {
                    let length = calculate_length(ls.coords());
                    Ok(SqlValue::Double(length))
                }
                geo::Geometry::MultiLineString(mls) => {
                    let mut total_length = 0.0;
                    for ls in &mls.0 {
                        total_length += calculate_length(ls.coords());
                    }
                    Ok(SqlValue::Double(total_length))
                }
                _ => Err(ExecutorError::SpatialGeometryError {
                    function_name: "ST_Length".to_string(),
                    message: "only works on LineString and MultiLineString".to_string(),
                }),
            }
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Length".to_string(),
            expected: "VARCHAR geometry argument".to_string(),
            actual: format!("{:?}", args[0].type_name()),
        }),
    }
}

/// ST_Perimeter(geom) - Calculate perimeter of Polygon
pub fn st_perimeter(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 1 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Perimeter".to_string(),
            expected: "exactly 1 argument".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match &args[0] {
        SqlValue::Null => Ok(SqlValue::Null),
        SqlValue::Varchar(wkt) | SqlValue::Character(wkt) => {
            let geom = wkt_to_geo(wkt)?;

            // Helper to calculate line length
            fn line_length<'a>(coords: impl Iterator<Item = &'a geo::Coord<f64>>) -> f64 {
                let coords_vec: Vec<_> = coords.collect();
                let mut length = 0.0;
                for i in 0..coords_vec.len().saturating_sub(1) {
                    let p1 = geo::Point::new(coords_vec[i].x, coords_vec[i].y);
                    let p2 = geo::Point::new(coords_vec[i + 1].x, coords_vec[i + 1].y);
                    length += Euclidean.distance(p1, p2);
                }
                length
            }

            match geom {
                geo::Geometry::Polygon(poly) => {
                    // Perimeter = exterior ring length + all interior rings length
                    let mut perimeter = line_length(poly.exterior().coords());
                    for interior in poly.interiors() {
                        perimeter += line_length(interior.coords());
                    }
                    Ok(SqlValue::Double(perimeter))
                }
                geo::Geometry::MultiPolygon(mp) => {
                    let mut total_perimeter = 0.0;
                    for poly in &mp.0 {
                        total_perimeter += line_length(poly.exterior().coords());
                        for interior in poly.interiors() {
                            total_perimeter += line_length(interior.coords());
                        }
                    }
                    Ok(SqlValue::Double(total_perimeter))
                }
                _ => Err(ExecutorError::SpatialGeometryError {
                    function_name: "ST_Perimeter".to_string(),
                    message: "only works on Polygon and MultiPolygon".to_string(),
                }),
            }
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Perimeter".to_string(),
            expected: "VARCHAR geometry argument".to_string(),
            actual: format!("{:?}", args[0].type_name()),
        }),
    }
}

/// ST_Area(geom) - Calculate area of Polygon
pub fn st_area(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 1 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Area".to_string(),
            expected: "exactly 1 argument".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match &args[0] {
        SqlValue::Null => Ok(SqlValue::Null),
        SqlValue::Varchar(wkt) | SqlValue::Character(wkt) => {
            let geom = wkt_to_geo(wkt)?;

            match geom {
                geo::Geometry::Polygon(poly) => {
                    let area = poly.unsigned_area();
                    Ok(SqlValue::Double(area))
                }
                geo::Geometry::MultiPolygon(mp) => {
                    let area = mp.unsigned_area();
                    Ok(SqlValue::Double(area))
                }
                _ => Err(ExecutorError::SpatialGeometryError {
                    function_name: "ST_Area".to_string(),
                    message: "only works on Polygon and MultiPolygon".to_string(),
                }),
            }
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Area".to_string(),
            expected: "VARCHAR geometry argument".to_string(),
            actual: format!("{:?}", args[0].type_name()),
        }),
    }
}

/// ST_Centroid(geom) - Find center point (geometric center of mass)
pub fn st_centroid(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 1 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Centroid".to_string(),
            expected: "exactly 1 argument".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match &args[0] {
        SqlValue::Null => Ok(SqlValue::Null),
        SqlValue::Varchar(wkt) | SqlValue::Character(wkt) => {
            let geom = wkt_to_geo(wkt)?;

            match geom.centroid() {
                Some(centroid) => {
                    let result_geom = Geometry::Point { x: centroid.x(), y: centroid.y() };
                    let result_value = super::geometry_to_sql_value(result_geom, 0);
                    Ok(result_value)
                }
                None => {
                    // Degenerate geometry (no centroid)
                    Ok(SqlValue::Null)
                }
            }
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Centroid".to_string(),
            expected: "VARCHAR geometry argument".to_string(),
            actual: format!("{:?}", args[0].type_name()),
        }),
    }
}

/// ST_Envelope(geom) - Get bounding box as a Polygon
pub fn st_envelope(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 1 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Envelope".to_string(),
            expected: "exactly 1 argument".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match &args[0] {
        SqlValue::Null => Ok(SqlValue::Null),
        SqlValue::Varchar(wkt) | SqlValue::Character(wkt) => {
            let geom = wkt_to_geo(wkt)?;

            match geom.bounding_rect() {
                Some(rect) => {
                    // Create a polygon from the bounding rectangle
                    let min_x = rect.min().x;
                    let min_y = rect.min().y;
                    let max_x = rect.max().x;
                    let max_y = rect.max().y;

                    let result_geom = Geometry::Polygon {
                        rings: vec![vec![
                            (min_x, min_y),
                            (max_x, min_y),
                            (max_x, max_y),
                            (min_x, max_y),
                            (min_x, min_y),
                        ]],
                    };
                    let result_value = super::geometry_to_sql_value(result_geom, 0);
                    Ok(result_value)
                }
                None => Ok(SqlValue::Null),
            }
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Envelope".to_string(),
            expected: "VARCHAR geometry argument".to_string(),
            actual: format!("{:?}", args[0].type_name()),
        }),
    }
}

/// ST_ConvexHull(geom) - Find smallest convex polygon containing geometry
pub fn st_convex_hull(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 1 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_ConvexHull".to_string(),
            expected: "exactly 1 argument".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match &args[0] {
        SqlValue::Null => Ok(SqlValue::Null),
        SqlValue::Varchar(wkt) | SqlValue::Character(wkt) => {
            let geom = wkt_to_geo(wkt)?;

            // The convex_hull() method returns a Polygon directly
            let hull_poly = match geom {
                geo::Geometry::Point(p) => {
                    // Point has a trivial convex hull (itself)
                    return Ok(super::geometry_to_sql_value(
                        Geometry::Point { x: p.x(), y: p.y() },
                        0,
                    ));
                }
                _ => geom.convex_hull(),
            };

            // Convert the Polygon back to internal Geometry
            let result_geom = {
                let mut rings = vec![];
                let exterior: Vec<(f64, f64)> =
                    hull_poly.exterior().coords().map(|c| (c.x, c.y)).collect();
                rings.push(exterior);
                for interior in hull_poly.interiors() {
                    let ring: Vec<(f64, f64)> = interior.coords().map(|c| (c.x, c.y)).collect();
                    rings.push(ring);
                }
                Geometry::Polygon { rings }
            };

            let result_value = super::geometry_to_sql_value(result_geom, 0);
            Ok(result_value)
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_ConvexHull".to_string(),
            expected: "VARCHAR geometry argument".to_string(),
            actual: format!("{:?}", args[0].type_name()),
        }),
    }
}

/// ST_PointOnSurface(geom) - Get a point guaranteed to be on the geometry
pub fn st_point_on_surface(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 1 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_PointOnSurface".to_string(),
            expected: "exactly 1 argument".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match &args[0] {
        SqlValue::Null => Ok(SqlValue::Null),
        SqlValue::Varchar(wkt) | SqlValue::Character(wkt) => {
            let geom = wkt_to_geo(wkt)?;

            match geom {
                geo::Geometry::Point(p) => {
                    let result_geom = Geometry::Point { x: p.x(), y: p.y() };
                    let result_value = super::geometry_to_sql_value(result_geom, 0);
                    Ok(result_value)
                }
                geo::Geometry::LineString(ls) => {
                    // Return the first coordinate on the line
                    if let Some(coord) = ls.coords().next() {
                        let result_geom = Geometry::Point { x: coord.x, y: coord.y };
                        let result_value = super::geometry_to_sql_value(result_geom, 0);
                        Ok(result_value)
                    } else {
                        Ok(SqlValue::Null)
                    }
                }
                geo::Geometry::Polygon(_) => {
                    // Use centroid for polygons (guaranteed to be on surface for convex polygons)
                    // For non-convex, this is still a reasonable approximation
                    match geom.centroid() {
                        Some(centroid) => {
                            let result_geom = Geometry::Point { x: centroid.x(), y: centroid.y() };
                            let result_value = super::geometry_to_sql_value(result_geom, 0);
                            Ok(result_value)
                        }
                        None => Ok(SqlValue::Null),
                    }
                }
                _ => Err(ExecutorError::SpatialGeometryError {
                    function_name: "ST_PointOnSurface".to_string(),
                    message: "not fully supported for this geometry type".to_string(),
                }),
            }
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_PointOnSurface".to_string(),
            expected: "VARCHAR geometry argument".to_string(),
            actual: format!("{:?}", args[0].type_name()),
        }),
    }
}

/// ST_Boundary(geom) - Get boundary of geometry (exterior ring for polygons, endpoints for lines)
pub fn st_boundary(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 1 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Boundary".to_string(),
            expected: "exactly 1 argument".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match &args[0] {
        SqlValue::Null => Ok(SqlValue::Null),
        SqlValue::Varchar(_) | SqlValue::Character(_) => {
            let geom_with_srid = sql_value_to_geometry(&args[0])?;
            let geom = &geom_with_srid.geometry;

            let boundary_geom = match geom {
                Geometry::Point { .. } => {
                    // Boundary of a point is empty
                    return Ok(SqlValue::Varchar(arcstr::ArcStr::from(
                        "__GEOMETRY__GEOMETRYCOLLECTION()",
                    )));
                }
                Geometry::LineString { points } => {
                    // Boundary of a line is a multi-point of the endpoints
                    if points.is_empty() {
                        return Ok(SqlValue::Varchar(arcstr::ArcStr::from(
                            "__GEOMETRY__GEOMETRYCOLLECTION()",
                        )));
                    }
                    if points.len() == 1 {
                        let (x, y) = points[0];
                        return Ok(super::geometry_to_sql_value(
                            Geometry::Point { x, y },
                            geom_with_srid.srid,
                        ));
                    }
                    let first = points[0];
                    let last = points[points.len() - 1];
                    if first == last {
                        // Closed linestring (ring): boundary is empty
                        return Ok(SqlValue::Varchar(arcstr::ArcStr::from(
                            "__GEOMETRY__GEOMETRYCOLLECTION()",
                        )));
                    }
                    Geometry::MultiPoint { points: vec![first, last] }
                }
                Geometry::Polygon { rings } => {
                    // Boundary of a polygon is all its rings as a MultiLineString
                    if rings.is_empty() {
                        return Ok(SqlValue::Varchar(arcstr::ArcStr::from(
                            "__GEOMETRY__GEOMETRYCOLLECTION()",
                        )));
                    }
                    Geometry::MultiLineString { lines: rings.clone() }
                }
                Geometry::MultiPoint { .. }
                | Geometry::MultiLineString { .. }
                | Geometry::MultiPolygon { .. } => {
                    // Boundary of multi-geometries: aggregate boundaries
                    // For simplicity, we'll return empty geometry collection for now
                    return Ok(SqlValue::Varchar(arcstr::ArcStr::from(
                        "__GEOMETRY__GEOMETRYCOLLECTION()",
                    )));
                }
                Geometry::Collection { .. } => {
                    // Boundary of a collection: aggregate boundaries
                    return Ok(SqlValue::Varchar(arcstr::ArcStr::from(
                        "__GEOMETRY__GEOMETRYCOLLECTION()",
                    )));
                }
            };

            Ok(super::geometry_to_sql_value(boundary_geom, geom_with_srid.srid))
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_Boundary".to_string(),
            expected: "VARCHAR geometry argument".to_string(),
            actual: format!("{:?}", args[0].type_name()),
        }),
    }
}

/// ST_HausdorffDistance(geom1, geom2) - Maximum distance between any point in geom1 to nearest
/// point in geom2
pub fn st_hausdorff_distance(args: &[SqlValue]) -> Result<SqlValue, ExecutorError> {
    if args.len() != 2 {
        return Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_HausdorffDistance".to_string(),
            expected: "exactly 2 arguments".to_string(),
            actual: format!("{} arguments", args.len()),
        });
    }

    match (&args[0], &args[1]) {
        (SqlValue::Null, _) | (_, SqlValue::Null) => Ok(SqlValue::Null),
        (SqlValue::Varchar(wkt1), SqlValue::Varchar(wkt2))
        | (SqlValue::Character(wkt1), SqlValue::Character(wkt2))
        | (SqlValue::Varchar(wkt1), SqlValue::Character(wkt2))
        | (SqlValue::Character(wkt1), SqlValue::Varchar(wkt2)) => {
            let geom1 = wkt_to_geo(wkt1)?;
            let geom2 = wkt_to_geo(wkt2)?;

            // Calculate Hausdorff distance: max(min_dist(p1 to geom2), min_dist(p2 to geom1))
            // For simplicity, we use a basic implementation that samples points
            let distance = calculate_hausdorff_distance(&geom1, &geom2)?;
            Ok(SqlValue::Double(distance))
        }
        _ => Err(ExecutorError::SpatialArgumentError {
            function_name: "ST_HausdorffDistance".to_string(),
            expected: "VARCHAR geometry arguments".to_string(),
            actual: format!("{:?}, {:?}", args[0].type_name(), args[1].type_name()),
        }),
    }
}

/// Helper function to calculate Hausdorff distance between two geometries
fn calculate_hausdorff_distance(
    geom1: &geo::Geometry<f64>,
    geom2: &geo::Geometry<f64>,
) -> Result<f64, ExecutorError> {
    let coords1 = extract_coordinates(geom1);
    let coords2 = extract_coordinates(geom2);

    if coords1.is_empty() || coords2.is_empty() {
        return Ok(0.0);
    }

    // Maximum distance from any point in geom1 to nearest point in geom2
    let max_dist_1_to_2 = coords1
        .iter()
        .map(|p1| {
            coords2.iter().map(|p2| Euclidean.distance(*p1, *p2)).fold(f64::INFINITY, f64::min)
        })
        .fold(f64::NEG_INFINITY, f64::max);

    // Maximum distance from any point in geom2 to nearest point in geom1
    let max_dist_2_to_1 = coords2
        .iter()
        .map(|p2| {
            coords1.iter().map(|p1| Euclidean.distance(*p2, *p1)).fold(f64::INFINITY, f64::min)
        })
        .fold(f64::NEG_INFINITY, f64::max);

    Ok(f64::max(max_dist_1_to_2, max_dist_2_to_1))
}

/// Helper function to extract all coordinates from a geometry
fn extract_coordinates(geom: &geo::Geometry<f64>) -> Vec<geo::Point<f64>> {
    let mut coords = Vec::new();

    match geom {
        geo::Geometry::Point(p) => coords.push(*p),
        geo::Geometry::LineString(ls) => {
            coords.extend(ls.points());
        }
        geo::Geometry::Polygon(poly) => {
            coords.extend(poly.exterior().points());
            for interior in poly.interiors() {
                coords.extend(interior.points());
            }
        }
        geo::Geometry::MultiPoint(mp) => {
            coords.extend(&mp.0);
        }
        geo::Geometry::MultiLineString(mls) => {
            for ls in &mls.0 {
                coords.extend(ls.points());
            }
        }
        geo::Geometry::MultiPolygon(mp) => {
            for poly in &mp.0 {
                coords.extend(poly.exterior().points());
                for interior in poly.interiors() {
                    coords.extend(interior.points());
                }
            }
        }
        geo::Geometry::GeometryCollection(gc) => {
            for g in &gc.0 {
                coords.extend(extract_coordinates(g));
            }
        }
        _ => {}
    }

    coords
}