ruprizzle 1.6.0

A schema-first ORM for Rust: typed queries, relations, and automatic migrations
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
//! PostGIS and Geospatial Scalar Types for Ruprizzle.
//!
//! Provides geometric data structures ([`Point`], [`Polygon`], [`LineString`],
//! [`MultiPolygon`]) with WKT parsing/formatting, SRID support (defaulting to
//! WGS 84 / `4326`), JSON/GeoJSON serialization, and integration with `Encodable`
//! and query filters.

use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

use crate::value::{Encodable, Value};

/// A 2D geometric coordinate point `(x, y)` / `(lat, lng)`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Point {
    /// X coordinate / Latitude.
    pub x: f64,
    /// Y coordinate / Longitude.
    pub y: f64,
    /// Spatial Reference System Identifier (SRID). Default is `4326` (WGS 84).
    #[serde(default = "default_srid")]
    pub srid: u32,
}

fn default_srid() -> u32 {
    4326
}

impl Point {
    /// Creates a new `Point` with default SRID `4326` (WGS 84).
    #[must_use]
    pub const fn new(x: f64, y: f64) -> Self {
        Self { x, y, srid: 4326 }
    }

    /// Creates a new `Point` with an explicit SRID.
    #[must_use]
    pub const fn with_srid(x: f64, y: f64, srid: u32) -> Self {
        Self { x, y, srid }
    }

    /// Latitude accessor (alias for `x`).
    #[must_use]
    pub const fn lat(&self) -> f64 {
        self.x
    }

    /// Longitude accessor (alias for `y`).
    #[must_use]
    pub const fn lng(&self) -> f64 {
        self.y
    }

    /// Computes the Euclidean distance to another point.
    #[must_use]
    pub fn distance_to(&self, other: &Point) -> f64 {
        let dx = self.x - other.x;
        let dy = self.y - other.y;
        (dx * dx + dy * dy).sqrt()
    }

    /// Returns the Well-Known Text (WKT) representation.
    #[must_use]
    pub fn to_wkt(&self) -> String {
        format!("POINT({} {})", self.x, self.y)
    }

    /// Returns the EWKT representation including the SRID.
    #[must_use]
    pub fn to_ewkt(&self) -> String {
        format!("SRID={};POINT({} {})", self.srid, self.x, self.y)
    }
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "POINT({} {})", self.x, self.y)
    }
}

impl FromStr for Point {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        let mut srid = 4326;
        let body = if s.starts_with("SRID=") {
            let semi = s
                .find(';')
                .ok_or_else(|| format!("malformed EWKT missing ';': {s}"))?;
            let srid_str = s.get(5..semi).unwrap_or("");
            srid = srid_str
                .parse::<u32>()
                .map_err(|e| format!("invalid SRID {srid_str}: {e}"))?;
            s.get(semi + 1..).unwrap_or("")
        } else {
            s
        };

        let body = body.trim();
        if let Some(coords_str) = body
            .strip_prefix("POINT")
            .or_else(|| body.strip_prefix("point"))
        {
            let trimmed = coords_str.trim();
            if trimmed.starts_with('(') && trimmed.ends_with(')') {
                let inner = trimmed
                    .get(1..trimmed.len().saturating_sub(1))
                    .unwrap_or("")
                    .trim();
                let parts: Vec<&str> = inner.split_whitespace().collect();
                if let (Some(x_part), Some(y_part)) = (parts.first(), parts.get(1)) {
                    let x = x_part
                        .parse::<f64>()
                        .map_err(|e| format!("invalid x coordinate: {e}"))?;
                    let y = y_part
                        .parse::<f64>()
                        .map_err(|e| format!("invalid y coordinate: {e}"))?;
                    return Ok(Point::with_srid(x, y, srid));
                }
            }
        }

        // Try comma-separated "x, y"
        if let Some((x_str, y_str)) = s.split_once(',') {
            let x = x_str
                .trim()
                .parse::<f64>()
                .map_err(|e| format!("invalid x coordinate: {e}"))?;
            let y = y_str
                .trim()
                .parse::<f64>()
                .map_err(|e| format!("invalid y coordinate: {e}"))?;
            return Ok(Point::with_srid(x, y, srid));
        }

        Err(format!("cannot parse Point from '{s}'"))
    }
}

impl Encodable for Point {
    fn to_value(&self) -> Value {
        Value::Str(self.to_wkt().into())
    }
}

/// A 2D geometric line string consisting of consecutive line segments.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LineString {
    /// Points forming the linestring in order.
    pub points: Vec<Point>,
    /// SRID identifier.
    #[serde(default = "default_srid")]
    pub srid: u32,
}

impl LineString {
    /// Creates a new `LineString` with default SRID `4326`.
    #[must_use]
    pub fn new(points: Vec<Point>) -> Self {
        Self { points, srid: 4326 }
    }

    /// Returns the WKT representation.
    #[must_use]
    pub fn to_wkt(&self) -> String {
        let pts = self
            .points
            .iter()
            .map(|p| format!("{} {}", p.x, p.y))
            .collect::<Vec<_>>()
            .join(", ");
        format!("LINESTRING({pts})")
    }
}

impl fmt::Display for LineString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_wkt())
    }
}

impl FromStr for LineString {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        let body = if let Some(stripped) = s.strip_prefix("LINESTRING") {
            stripped.trim()
        } else if let Some(stripped) = s.strip_prefix("linestring") {
            stripped.trim()
        } else {
            s
        };

        if body.starts_with('(') && body.ends_with(')') {
            let inner = body
                .get(1..body.len().saturating_sub(1))
                .unwrap_or("")
                .trim();
            let mut points = Vec::new();
            for part in inner.split(',') {
                let coords: Vec<&str> = part.split_whitespace().collect();
                if let (Some(x_coord), Some(y_coord)) = (coords.first(), coords.get(1)) {
                    let x = x_coord
                        .parse::<f64>()
                        .map_err(|e| format!("invalid x: {e}"))?;
                    let y = y_coord
                        .parse::<f64>()
                        .map_err(|e| format!("invalid y: {e}"))?;
                    points.push(Point::new(x, y));
                }
            }
            return Ok(LineString::new(points));
        }

        Err(format!("cannot parse LineString from '{s}'"))
    }
}

impl Encodable for LineString {
    fn to_value(&self) -> Value {
        Value::Str(self.to_wkt().into())
    }
}

/// A 2D geometric polygon consisting of an exterior ring and optional interior rings (holes).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Polygon {
    /// Rings of the polygon: `rings[0]` is the exterior ring; `rings[1..]` are holes.
    pub rings: Vec<Vec<Point>>,
    /// SRID identifier.
    #[serde(default = "default_srid")]
    pub srid: u32,
}

impl Polygon {
    /// Creates a polygon from an exterior ring of points.
    #[must_use]
    pub fn new(exterior: Vec<Point>) -> Self {
        Self {
            rings: vec![exterior],
            srid: 4326,
        }
    }

    /// Creates a polygon with an exterior ring and one or more interior holes.
    #[must_use]
    pub fn with_holes(exterior: Vec<Point>, holes: Vec<Vec<Point>>) -> Self {
        let mut rings = Vec::with_capacity(1 + holes.len());
        rings.push(exterior);
        rings.extend(holes);
        Self { rings, srid: 4326 }
    }

    /// Returns the WKT representation.
    #[must_use]
    pub fn to_wkt(&self) -> String {
        let rings_wkt = self
            .rings
            .iter()
            .map(|ring| {
                let pts = ring
                    .iter()
                    .map(|p| format!("{} {}", p.x, p.y))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("({pts})")
            })
            .collect::<Vec<_>>()
            .join(", ");
        format!("POLYGON({rings_wkt})")
    }
}

impl fmt::Display for Polygon {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_wkt())
    }
}

impl FromStr for Polygon {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        let body = if let Some(stripped) = s.strip_prefix("POLYGON") {
            stripped.trim()
        } else if let Some(stripped) = s.strip_prefix("polygon") {
            stripped.trim()
        } else {
            s
        };

        if body.starts_with('(') && body.ends_with(')') {
            let inner = body
                .get(1..body.len().saturating_sub(1))
                .unwrap_or("")
                .trim();
            let mut rings = Vec::new();
            for ring_str in inner.split("),") {
                let ring_str = ring_str
                    .trim()
                    .trim_start_matches('(')
                    .trim_end_matches(')');
                let mut ring = Vec::new();
                for pt_str in ring_str.split(',') {
                    let coords: Vec<&str> = pt_str.split_whitespace().collect();
                    if let (Some(x_coord), Some(y_coord)) = (coords.first(), coords.get(1)) {
                        let x = x_coord
                            .parse::<f64>()
                            .map_err(|e| format!("invalid x: {e}"))?;
                        let y = y_coord
                            .parse::<f64>()
                            .map_err(|e| format!("invalid y: {e}"))?;
                        ring.push(Point::new(x, y));
                    }
                }
                if !ring.is_empty() {
                    rings.push(ring);
                }
            }
            return Ok(Polygon { rings, srid: 4326 });
        }

        Err(format!("cannot parse Polygon from '{s}'"))
    }
}

impl Encodable for Polygon {
    fn to_value(&self) -> Value {
        Value::Str(self.to_wkt().into())
    }
}

/// A 2D geometric collection of polygons.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MultiPolygon {
    /// Individual polygons in the collection.
    pub polygons: Vec<Polygon>,
    /// SRID identifier.
    #[serde(default = "default_srid")]
    pub srid: u32,
}

impl MultiPolygon {
    /// Creates a new `MultiPolygon`.
    #[must_use]
    pub fn new(polygons: Vec<Polygon>) -> Self {
        Self {
            polygons,
            srid: 4326,
        }
    }

    /// Returns the WKT representation.
    #[must_use]
    pub fn to_wkt(&self) -> String {
        let polys_wkt = self
            .polygons
            .iter()
            .map(|poly| {
                let rings_wkt = poly
                    .rings
                    .iter()
                    .map(|ring| {
                        let pts = ring
                            .iter()
                            .map(|p| format!("{} {}", p.x, p.y))
                            .collect::<Vec<_>>()
                            .join(", ");
                        format!("({pts})")
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("({rings_wkt})")
            })
            .collect::<Vec<_>>()
            .join(", ");
        format!("MULTIPOLYGON({polys_wkt})")
    }
}

impl fmt::Display for MultiPolygon {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_wkt())
    }
}

impl FromStr for MultiPolygon {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        let body = if let Some(stripped) = s.strip_prefix("MULTIPOLYGON") {
            stripped.trim()
        } else if let Some(stripped) = s.strip_prefix("multipolygon") {
            stripped.trim()
        } else {
            s
        };

        if body.starts_with('(') && body.ends_with(')') {
            let inner = body
                .get(1..body.len().saturating_sub(1))
                .unwrap_or("")
                .trim();
            let mut polygons = Vec::new();
            for poly_str in inner.split(")),") {
                let poly_str = format!("{poly_str}))");
                if let Ok(poly) = poly_str.trim().parse::<Polygon>() {
                    polygons.push(poly);
                }
            }
            return Ok(MultiPolygon::new(polygons));
        }

        Err(format!("cannot parse MultiPolygon from '{s}'"))
    }
}

impl Encodable for MultiPolygon {
    fn to_value(&self) -> Value {
        Value::Str(self.to_wkt().into())
    }
}