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
use std::fmt;

use crate::sql_types::Geography;
use crate::sql_types::Geometry;

/// Error which may be returned if point constructed without required fields or has some unexpected fields for type.
/// ```
/// use postgis_diesel::types::{PointT, PointZ, Point, PointConstructorError};
/// let point = PointZ::new_point(72.0, 63.0, None, None, None);
/// assert!(point.is_err());
/// assert_eq!(Result::Err(PointConstructorError{reason:"Z is not defined, but mandatory for PointZ".to_string()}), point);
/// let point = Point::new_point(72.0, 63.0, None, Some(10.0), None);
/// assert!(point.is_err());
/// assert_eq!(Result::Err(PointConstructorError{reason:"unexpectedly defined Z Some(10.0) or M None for Point".to_string()}), point);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct PointConstructorError {
    pub reason: String,
}

impl fmt::Display for PointConstructorError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "can't construct point: {}", self.reason)
    }
}

impl std::error::Error for PointConstructorError {}

/// Use that structure in `Insertable` or `Queryable` struct if you work with Point geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::Point;
/// #[derive(Queryable)]
/// struct QueryablePointExample {
///     id: i32,
///     point: Point,
/// }
/// ```
#[derive(Copy, Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct Point {
    pub x: f64,
    pub y: f64,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with PointZ geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::PointZ;
/// #[derive(Queryable)]
/// struct QueryablePointZExample {
///     id: i32,
///     point: PointZ,
/// }
/// ```
#[derive(Copy, Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct PointZ {
    pub x: f64,
    pub y: f64,
    pub z: f64,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with PointM geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::PointM;
/// #[derive(Queryable)]
/// struct QueryablePointMExample {
///     id: i32,
///     point: PointM,
/// }
/// ```
#[derive(Copy, Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct PointM {
    pub x: f64,
    pub y: f64,
    pub m: f64,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with PointZM geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::PointZM;
/// #[derive(Queryable)]
/// struct QueryablePointZMExample {
///     id: i32,
///     point: PointZM,
/// }
/// ```
#[derive(Copy, Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct PointZM {
    pub x: f64,
    pub y: f64,
    pub z: f64,
    pub m: f64,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Allows uniform access across the four point types
pub trait PointT {
    fn new_point(
        x: f64,
        y: f64,
        srid: Option<u32>,
        z: Option<f64>,
        m: Option<f64>,
    ) -> Result<Self, PointConstructorError>
    where
        Self: Sized;
    fn get_x(&self) -> f64;
    fn get_y(&self) -> f64;
    fn get_srid(&self) -> Option<u32>;
    fn get_z(&self) -> Option<f64>;
    fn get_m(&self) -> Option<f64>;
    fn dimension(&self) -> u32;
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with MultiPoint geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::{MultiPoint,Point};
/// #[derive(Queryable)]
/// struct QueryableMultiPointExample {
///     id: i32,
///     multipoint: MultiPoint<Point>,
/// }
/// ```
#[derive(Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct MultiPoint<T> {
    pub points: Vec<T>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with LineString geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::{LineString,Point};
/// #[derive(Queryable)]
/// struct QueryableLineStringExample {
///     id: i32,
///     linestring: LineString<Point>,
/// }
/// ```
#[derive(Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct LineString<T> {
    pub points: Vec<T>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with MultiLineString geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::{MultiLineString, LineString,Point};
/// #[derive(Queryable)]
/// struct QueryableMultiLineStringExample {
///     id: i32,
///     multilinestring: MultiLineString<LineString<Point>>,
/// }
/// ```
#[derive(Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct MultiLineString<T> {
    pub lines: Vec<LineString<T>>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with Polygon geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::{Polygon,Point};
/// #[derive(Queryable)]
/// struct QueryablePolygonExample {
///     id: i32,
///     polygon: Polygon<Point>,
/// }
/// ```
#[derive(Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct Polygon<T> {
    pub rings: Vec<Vec<T>>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with MultiPolygon geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::{MultiPolygon, Polygon,Point};
/// #[derive(Queryable)]
/// struct QueryableMultiPolygonExample {
///     id: i32,
///     multipolygon: MultiPolygon<Polygon<Point>>,
/// }
/// ```
#[derive(Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct MultiPolygon<T> {
    pub polygons: Vec<Polygon<T>>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

/// Represents any type that can appear in a geometry or geography column.
///
/// T is the Point type (Point or PointZ or PointM)
#[derive(Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde_geojson", derive(Deserialize))]
#[cfg_attr(feature = "serde_geojson", serde(tag = "type", bound(deserialize = "T: crate::geojson::GeoJsonGeometry<f64> + PointT + Clone + serde::Deserialize<'de>")))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum GeometryContainer<T> {
    Point(T),
    LineString(LineString<T>),
    Polygon(Polygon<T>),
    MultiPoint(MultiPoint<T>),
    MultiLineString(MultiLineString<T>),
    MultiPolygon(MultiPolygon<T>),
    GeometryCollection(GeometryCollection<T>),
}

/// Use that structure in `Insertable` or `Queryable` struct if you work with GeometryCollection geometry.
/// ```
/// #[macro_use] extern crate diesel;
/// use postgis_diesel::types::{GeometryCollection, GeometryContainer, Point};
/// #[derive(Queryable)]
/// struct QueryableGeometryCollectionExample {
///     id: i32,
///     geometrycollection: GeometryCollection<GeometryContainer<Point>>,
/// }
/// ```
#[derive(Clone, Debug, PartialEq, FromSqlRow, AsExpression)]
#[diesel(sql_type = Geometry)]
#[diesel(sql_type = Geography)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct GeometryCollection<T> {
    pub geometries: Vec<GeometryContainer<T>>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub srid: Option<u32>,
}

#[cfg(feature = "serde_geojson")]
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag = "type", bound(deserialize = "T: crate::geojson::GeoJsonGeometry<f64> + PointT + Clone + serde::Deserialize<'de>, P: serde::Deserialize<'de>"))]
pub struct Feature<T, P: serde::Serialize> {
    pub id: Option<String>,
    pub geometry: Option<GeometryContainer<T>>,
    pub properties: Option<P>,
}

#[cfg(feature = "serde_geojson")]
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag = "type", bound(deserialize = "T: crate::geojson::GeoJsonGeometry<f64> + PointT + Clone + serde::Deserialize<'de>, P: serde::Deserialize<'de>"))]
pub struct FeatureCollection<T, P: serde::Serialize> {
    pub features: Vec<Feature<T, P>>,
}

#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {
    // Note this useful idiom: importing names from outer (for mod tests) scope.
    use super::*;

    #[test]
    fn test_point_serde() {
        let point = Point::new(72.0, 64.0, None);
        let expected_point = "{\"x\":72.0,\"y\":64.0}";
        let point_from_json = serde_json::from_str(expected_point).unwrap();
        assert_eq!(point, point_from_json);
        let point_json = serde_json::to_string(&point).unwrap();
        assert_eq!(expected_point, point_json);

        #[cfg(feature = "schemars")]
        {
            let schema = schema_for!(Point);
            let schema_json = serde_json::to_string(&schema).unwrap();
            let expected_schema = r#"{"$schema":"http://json-schema.org/draft-07/schema#","title":"Point","description":"Use that structure in `Insertable` or `Queryable` struct if you work with Point geometry. ``` #[macro_use] extern crate diesel; use postgis_diesel::types::Point; #[derive(Queryable)] struct QueryablePointExample { id: i32, point: Point, } ```","type":"object","required":["x","y"],"properties":{"srid":{"type":["integer","null"],"format":"uint32","minimum":0.0},"x":{"type":"number","format":"double"},"y":{"type":"number","format":"double"}}}"#;
            assert_eq!(expected_schema, schema_json);

            let schema_for_value = schema_for_value!(point);
            let schema_for_value_json = serde_json::to_string(&schema_for_value).unwrap();
            println!("{}", schema_for_value_json);
            let expected_schema_for_value = r#"{"$schema":"http://json-schema.org/draft-07/schema#","title":"Point","examples":[{"x":72.0,"y":64.0}],"type":"object","properties":{"x":{"type":"number"},"y":{"type":"number"}}}"#;
            assert_eq!(expected_schema_for_value, schema_for_value_json);
        }

    }
}