hecate 0.27.1

OpenStreetMap Inspired Data Storage Backend Focused on Performance and GeoJSON Interchange
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
extern crate r2d2;
extern crate r2d2_postgres;
extern crate geojson;
extern crate postgres;
extern crate serde_json;
extern crate valico;

use stream::PGStream;

#[derive(PartialEq, Debug)]
pub enum FeatureError {
    NotFound,
    NoProps,
    NoMembers,
    NoGeometry,
    DuplicateKey,
    VersionRequired,
    SchemaMisMatch,
    CreateError(String),
    DeleteVersionMismatch,
    DeleteError(String),
    ModifyError(String),
    RestoreError(String),
    ModifyVersionMismatch,
    RestoreVersionMismatch,
    IdRequired,
    ActionRequired,
    InvalidBBOX,
    InvalidFeature
}

#[derive(PartialEq, Debug)]
pub enum Action {
    Create,
    Modify,
    Delete,
    Restore
}

#[derive(PartialEq, Debug)]
pub struct Response {
    pub old: Option<i64>,
    pub new: Option<i64>,
    pub version: Option<i64>
}

impl FeatureError {
    pub fn to_string(&self) -> String {
        match *self {
            FeatureError::NotFound => String::from("Feature Not Found"),
            FeatureError::NoProps => String::from("No Properties"),
            FeatureError::NoMembers => String::from("No Members"),
            FeatureError::NoGeometry => String::from("No Geometry"),
            FeatureError::DuplicateKey => String::from("Duplicate Key Value"),
            FeatureError::VersionRequired => String::from("Version Required"),
            FeatureError::SchemaMisMatch => String::from("Feature properties do not pass schema definition"),
            FeatureError::CreateError(ref msg) => format!("Create Error: {}", msg),
            FeatureError::DeleteVersionMismatch => String::from("Delete Version Mismatch"),
            FeatureError::DeleteError(ref msg) => format!("Delete Error: {}", msg),
            FeatureError::ModifyVersionMismatch => String::from("Modify Version Mismatch"),
            FeatureError::RestoreVersionMismatch => String::from("Restore Version Mismatch"),
            FeatureError::ModifyError(ref msg) => format!("Modify Error: {}", msg),
            FeatureError::RestoreError(ref msg) => format!("Restore Error: {}", msg),
            FeatureError::IdRequired => String::from( "ID Required"),
            FeatureError::ActionRequired => String::from( "Action Required"),
            FeatureError::InvalidBBOX => String::from( "Invalid BBOX"),
            FeatureError::InvalidFeature => String::from( "Invalid Feature")
        }
    }
}

pub fn get_version(feat: &geojson::Feature) -> Result<i64, FeatureError> {
    match feat.foreign_members {
        None => { return Err(FeatureError::VersionRequired); },
        Some(ref members) => match members.get("version") {
            Some(version) => {
                match version.as_i64() {
                    Some(version) => Ok(version),
                    None => { return Err(FeatureError::VersionRequired); },
                }
            },
            None => { return Err(FeatureError::VersionRequired); },
        }
    }
}

pub fn get_id(feat: &geojson::Feature) -> Result<i64, FeatureError> {
    match feat.id {
        None => { return Err(FeatureError::IdRequired); },
        Some(ref id) => match id.as_i64() {
            Some(id) => Ok(id),
            None => { return Err(FeatureError::IdRequired); },
        }
    }
}

pub fn get_action(feat: &geojson::Feature) -> Result<Action, FeatureError> {
    match feat.foreign_members {
        None => { return Err(FeatureError::ActionRequired); },
        Some(ref members) => match members.get("action") {
            Some(action) => {
                match action.as_str() {
                    Some("create") => Ok(Action::Create),
                    Some("modify") => Ok(Action::Modify),
                    Some("delete") => Ok(Action::Delete),
                    Some("restore") => Ok(Action::Restore),
                    Some(_) => { return Err(FeatureError::ActionRequired); },
                    None => { return Err(FeatureError::ActionRequired); }
                }
            },
            None => { return Err(FeatureError::ActionRequired); },
        }
    }
}

pub fn get_key(feat: &geojson::Feature) -> Option<String> {
    match feat.foreign_members {
        None => None,
        Some(ref members) => {
            match members.get("key") {
                None => None,
                Some(key) => {
                    Some(key.to_string())
                }
            }
        }
    }
}

pub fn action(trans: &postgres::transaction::Transaction, schema_json: &Option<serde_json::value::Value>, feat: &geojson::Feature, delta: &Option<i64>) -> Result<Response, FeatureError> {
    let action = get_action(&feat)?;

    let mut scope = valico::json_schema::Scope::new();
    let schema = match schema_json {
        &Some(ref schema) => {
            Some(scope.compile_and_return(schema.clone(), false).unwrap())
        },
        &None => None
    };

    let res = match action {
        Action::Create => create(&trans, &schema, &feat, &delta)?,
        Action::Modify => modify(&trans, &schema, &feat, &delta)?,
        Action::Restore => restore(&trans, &schema, &feat, &delta)?,
        Action::Delete => delete(&trans, &feat)?
    };

    Ok(res)
}

pub fn create(trans: &postgres::transaction::Transaction, schema: &Option<valico::json_schema::schema::ScopedSchema>, feat: &geojson::Feature, delta: &Option<i64>) -> Result<Response, FeatureError> {
    let geom = match feat.geometry {
        None => { return Err(FeatureError::NoGeometry); },
        Some(ref geom) => geom
    };

    let props = match feat.properties {
        None => { return Err(FeatureError::NoProps); },
        Some(ref props) => props
    };

    let valid = match schema {
        &Some(ref schema) => {
            schema.validate(&json!(props)).is_valid()
        },
        &None => true
    };

    if !valid { return Err(FeatureError::SchemaMisMatch) };

    let geom_str = serde_json::to_string(&geom).unwrap();
    let props_str = serde_json::to_string(&props).unwrap();

    let key = get_key(&feat);

    match trans.query("
        INSERT INTO geo (version, geom, props, deltas, key)
            VALUES (
                1,
                ST_SetSRID(ST_GeomFromGeoJSON($1), 4326),
                $2::TEXT::JSON,
                array[COALESCE($3, currval('deltas_id_seq')::BIGINT)],
                $4
            ) RETURNING id;
    ", &[&geom_str, &props_str, &delta, &key]) {
        Ok(res) => Ok(Response {
            old: match feat.id {
                Some(ref id) => id.as_i64(),
                _ => None
            },
            new: Some(res.get(0).get(0)),
            version: Some(1)
        }),
        Err(err) => {
            match err.as_db() {
                Some(e) => {
                    if e.message == "duplicate key value violates unique constraint \"geo_key_key\"" {
                        Err(FeatureError::DuplicateKey)
                    } else {
                        Err(FeatureError::CreateError(e.message.clone()))
                    }
                },
                _ => Err(FeatureError::CreateError(String::from("generic")))
            }
        }
    }
}

pub fn modify(trans: &postgres::transaction::Transaction, schema: &Option<valico::json_schema::schema::ScopedSchema>, feat: &geojson::Feature, delta: &Option<i64>) -> Result<Response, FeatureError> {
    let geom = match feat.geometry {
        None => { return Err(FeatureError::NoGeometry); },
        Some(ref geom) => geom
    };

    let props = match feat.properties {
        None => { return Err(FeatureError::NoProps); },
        Some(ref props) => props
    };

    let valid = match schema {
        &Some(ref schema) => {
            schema.validate(&json!(props)).is_valid()
        },
        &None => true
    };

    if !valid { return Err(FeatureError::SchemaMisMatch) };

    let id = get_id(&feat)?;
    let version = get_version(&feat)?;
    let key = get_key(&feat);

    let geom_str = serde_json::to_string(&geom).unwrap();
    let props_str = serde_json::to_string(&props).unwrap();

    match trans.query("SELECT modify_geo($1, $2, COALESCE($5, currval('deltas_id_seq')::BIGINT), $3, $4, $6);", &[&geom_str, &props_str, &id, &version, &delta, &key]) {
        Ok(_) => Ok(Response {
            old: Some(id),
            new: Some(id),
            version: Some(version + 1)
        }),
        Err(err) => {
            match err.as_db() {
                Some(e) => {
                    if e.message == "MODIFY: ID or VERSION Mismatch" {
                        Err(FeatureError::ModifyVersionMismatch)
                    } else if e.message == "duplicate key value violates unique constraint \"geo_key_key\"" {
                        Err(FeatureError::DuplicateKey)
                    } else {
                        Err(FeatureError::CreateError(e.message.clone()))
                    }
                },
                _ => Err(FeatureError::ModifyError(String::from("generic")))
            }
        }
    }
}

pub fn delete(trans: &postgres::transaction::Transaction, feat: &geojson::Feature) -> Result<Response, FeatureError> {
    let id = get_id(&feat)?;
    let version = get_version(&feat)?;

    match trans.query("SELECT delete_geo($1, $2);", &[&id, &version]) {
        Ok(_) => Ok(Response {
            old: Some(id),
            new: None,
            version: None
        }),
        Err(err) => {
            match err.as_db() {
                Some(e) => {
                    if e.message == "DELETE: ID or VERSION Mismatch" {
                        Err(FeatureError::DeleteVersionMismatch)
                    } else {
                        Err(FeatureError::DeleteError(e.message.clone()))
                    }
                },
                _ => Err(FeatureError::DeleteError(String::from("generic")))
            }
        }
    }
}

pub fn get(conn: &r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>, id: &i64) -> Result<geojson::Feature, FeatureError> {
    let res = conn.query("
        SELECT
            row_to_json(f)::TEXT AS feature
        FROM (
            SELECT
                id AS id,
                key AS key,
                'Feature' AS type,
                version AS version,
                ST_AsGeoJSON(geom)::JSON AS geometry,
                props AS properties
            FROM geo
            WHERE id = $1
        ) f;
    ", &[&id]).unwrap();

    if res.len() != 1 { return Err(FeatureError::NotFound); }

    let feat: postgres::rows::Row = res.get(0);
    let feat: String = feat.get(0);
    let feat: geojson::Feature = match feat.parse() {
        Ok(feat) => match feat {
            geojson::GeoJson::Feature(feat) => feat,
            _ => { return Err(FeatureError::InvalidFeature); }
        },
        Err(_) => { return Err(FeatureError::InvalidFeature); }
    };

    Ok(feat)
}

pub fn restore(trans: &postgres::transaction::Transaction, schema: &Option<valico::json_schema::schema::ScopedSchema>, feat: &geojson::Feature, delta: &Option<i64>) -> Result<Response, FeatureError> {
    let geom = match feat.geometry {
        None => { return Err(FeatureError::NoGeometry); },
        Some(ref geom) => geom
    };

    let props = match feat.properties {
        None => { return Err(FeatureError::NoProps); },
        Some(ref props) => props
    };

    let valid = match schema {
        &Some(ref schema) => {
            schema.validate(&json!(props)).is_valid()
        },
        &None => true
    };

    if !valid { return Err(FeatureError::SchemaMisMatch) };

    let id = get_id(&feat)?;
    let version = get_version(&feat)?;
    let key = get_key(&feat);

    let geom_str = serde_json::to_string(&geom).unwrap();
    let props_str = serde_json::to_string(&props).unwrap();

    //Get the previous version of a given feature
    match trans.query("
        SELECT
            ARRAY_AGG(id ORDER BY id) AS delta_ids,
            MAX(feat->>'version')::BIGINT + 1 AS max_version
        FROM (
            SELECT
                deltas.id,
                JSON_Array_Elements((deltas.features -> 'features')::JSON) AS feat 
            FROM
                deltas
            WHERE
                affected @> ARRAY[$1]::BIGINT[]
            ORDER BY id DESC
        ) f
        WHERE
            (feat->>'id')::BIGINT = $1
        GROUP BY feat->>'id'
    ", &[&id]) {
        Ok(history) => {

            if history.len() != 1 {
                return Err(FeatureError::RestoreError(format!("Feature id: {} does not exist", &id)));
            }

            //Version will be None if the feature was created but has never been modified since the
            //original create does not need a version
            let prev_version: Option<i64> = history.get(0).get(1);
            match prev_version {
                None => {
                    return Err(FeatureError::RestoreError(format!("Feature id: {} cannot restore an existing feature", &id)));
                },
                Some(prev_version) => {
                    if prev_version != version {
                        return Err(FeatureError::RestoreVersionMismatch);
                    }
                }
            };

            let affected: Vec<i64> = history.get(0).get(0);

            //Create Delta History Array
            match trans.query("
                INSERT INTO geo (id, version, geom, props, deltas, key)
                    VALUES (
                        $1::BIGINT,
                        $2::BIGINT + 1,
                        ST_SetSRID(ST_GeomFromGeoJSON($3), 4326),
                        $4::TEXT::JSON,
                        array_append($5::BIGINT[], COALESCE($6, currval('deltas_id_seq')::BIGINT)),
                        $7
                    );
            ", &[&id, &prev_version, &geom_str, &props_str, &affected, &delta, &key]) {
                Ok(_) => Ok(Response {
                    old: Some(id),
                    new: Some(id),
                    version: Some(version + 1)
                }),
                Err(err) => {
                    match err.as_db() {
                        Some(e) => {
                            println!("{}", e.message);
                            if e.message == "duplicate key value violates unique constraint \"geo_id_key\"" {
                                Err(FeatureError::RestoreError(format!("Feature id: {} cannot restore an existing feature", &id)))
                            } else if e.message == "duplicate key value violates unique constraint \"geo_key_key\"" {
                                Err(FeatureError::DuplicateKey)
                            } else {
                                Err(FeatureError::RestoreError(String::from("generic")))
                            }
                        }
                        _ => Err(FeatureError::RestoreError(String::from("generic")))
                    }
                }
            }
        },
        Err(_) => {
            Err(FeatureError::RestoreError(format!("Error fetching feature history for: {}", &id)))
        }
    }
}

pub fn get_bbox_stream(conn: r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>, bbox: Vec<f64>) -> Result<PGStream, FeatureError> {
    if bbox.len() != 4 {
        return Err(FeatureError::InvalidBBOX);
    }

    match PGStream::new(conn, String::from("next_features"), String::from(r#"
        DECLARE next_features CURSOR FOR
            SELECT
                row_to_json(f)::TEXT AS feature
            FROM (
                SELECT
                    id AS id,
                    key AS key,
                    'Feature' AS type,
                    version AS version,
                    ST_AsGeoJSON(geom)::JSON AS geometry,
                    props AS properties
                FROM geo
                WHERE
                    ST_Intersects(geom, ST_MakeEnvelope($1, $2, $3, $4, 4326))
                    OR ST_Within(geom, ST_MakeEnvelope($1, $2, $3, $4, 4326))
            ) f;
    "#), &[&bbox[0], &bbox[1], &bbox[2], &bbox[3]]) {
        Ok(stream) => Ok(stream),
        Err(_) => Err(FeatureError::NotFound)
    }
}

pub fn get_bbox(conn: &r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>, bbox: Vec<f64>) -> Result<geojson::FeatureCollection, FeatureError> {
    if bbox.len() != 4 {
        return Err(FeatureError::InvalidBBOX);
    }

    let res = conn.query("
        SELECT
            row_to_json(f)::TEXT AS feature
        FROM (
            SELECT
                id AS id,
                key AS key,
                'Feature' AS type,
                version AS version,
                ST_AsGeoJSON(geom)::JSON AS geometry,
                props AS properties
            FROM geo
            WHERE
                ST_Intersects(geom, ST_MakeEnvelope($1, $2, $3, $4, 4326))
                OR ST_Within(geom, ST_MakeEnvelope($1, $2, $3, $4, 4326))
        ) f;
    ", &[&bbox[0], &bbox[1], &bbox[2], &bbox[3]]).unwrap();

    let mut fc = geojson::FeatureCollection {
        bbox: None,
        features: vec![],
        foreign_members: None
    };

    for row in res.iter() {
        let feat: String = row.get(0);
        let feat: geojson::Feature = match feat.parse().unwrap() {
            geojson::GeoJson::Feature(feat) => feat,
            _ => { return Err(FeatureError::InvalidFeature); }
        };

        fc.features.push(feat);
    }

    Ok(fc)
}