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
#![allow(dead_code)]
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::ops::Deref;
use syn::{
parse2, Attribute, DeriveInput, Field, GenericArgument, GenericParam, Generics, Ident, Lit,
LitInt, Meta, Type, TypePath, TypeReference,
};
const GEO_TYPES: &'static [&'static str] = &[
"GPKGPolygon",
"GPKGLineString",
"GPKGPoint",
"GPKGMultiPolygon",
"GPKGMultiLineString",
"GPKGMultiPoint",
"GPKGPolygonM",
"GPKGLineStringM",
"GPKGPointM",
"GPKGMultiPolygonM",
"GPKGMultiLineStringM",
"GPKGMultiPointM",
"GPKGPolygonZ",
"GPKGLineStringZ",
"GPKGPointZ",
"GPKGMultiPolygonZ",
"GPKGMultiLineStringZ",
"GPKGMultiPointZ",
"GPKGPolygonZM",
"GPKGLineStringZM",
"GPKGPointZM",
"GPKGMultiPolygonZM",
"GPKGMultiLineStringZM",
"GPKGMultiPointZM",
];
#[proc_macro_derive(GPKGModel, attributes(table_name, geom_field))]
pub fn derive_gpkg(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let inner_input = proc_macro2::TokenStream::from(input);
proc_macro::TokenStream::from(derive_gpkg_inner(inner_input))
}
fn derive_gpkg_inner(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let ast = parse2::<DeriveInput>(input).unwrap();
let tbl_name_meta = get_meta_attr(&ast.attrs, "table_name");
let tbl_name = match tbl_name_meta {
Some(meta) => match meta {
Meta::NameValue(nv) => match nv.lit {
Lit::Str(ls) => Some(ls.value()),
_ => None,
},
_ => None,
},
_ => None,
};
let name = &ast.ident;
let fields = match &ast.data {
syn::Data::Struct(data) => match &data.fields {
syn::Fields::Named(fields) => fields.named.iter(),
_ => panic!("GPKGModel derive expected named fields"),
},
_ => panic!("GPKGModel derive expected a struct"),
}
.collect();
impl_model(&name.clone(), &fields, tbl_name, &ast.generics)
}
fn get_meta_attr<'a>(attrs: &Vec<Attribute>, name: &'a str) -> Option<Meta> {
let mut temp = attrs
.iter()
.filter_map(|attr| attr.parse_meta().ok())
.filter(|i| match i.path().get_ident() {
Some(i) => i.to_string() == name.to_owned(),
None => false,
})
.collect::<Vec<Meta>>();
temp.pop()
}
#[derive(Debug, Clone, Copy)]
enum MZOptions {
Prohibited = 0,
Mandatory = 1,
Optional = 2,
}
#[derive(Debug, Clone)]
struct GeomInfo {
geom_type: String,
srs_id: i64,
m: MZOptions,
z: MZOptions,
}
#[derive(Debug)]
struct FieldInfo {
name: String,
geom_info: Option<GeomInfo>,
optional: bool,
type_for_sql: String,
}
fn get_reference_type_name(t: &TypeReference) -> String {
match t.elem.deref() {
syn::Type::Path(p) => {
assert!(p.path.segments.len() == 1);
match get_path_type_name(p).0.as_str() {
"str" => return String::from("str"),
_ => panic!("The only reference types supported are &str and &[u8]"),
}
}
syn::Type::Slice(s) => match s.elem.deref() {
Type::Path(p) => match get_path_type_name(p).0.as_str() {
"u8" => return String::from("buf"),
_ => panic!("The only reference types supported are &str and &[u8]"),
},
_ => panic!("The only reference types supported are &str and &[u8]"),
},
_ => panic!("The only reference types supported are &str and &[u8]"),
};
}
fn get_path_type_name(p: &TypePath) -> (String, bool) {
let mut optional = false;
assert!(p.path.segments.len() > 0);
let final_segment = p.path.segments.last().unwrap();
let id_string = final_segment.ident.to_string();
match id_string.as_str() {
"Option" => {
optional = true;
if let syn::PathArguments::AngleBracketed(a) = &final_segment.arguments {
assert!(a.args.len() == 1, "Only one argument allowed in an Option");
if let GenericArgument::Type(t) = &a.args[0] {
match t {
Type::Path(p) => {
return (get_path_type_name(p).0, optional);
}
Type::Reference(r) => {
return (get_reference_type_name(r), optional);
}
_ => panic!("Unsupported type within Option"),
}
}
} else {
panic!("Unsupported use of the option type");
}
}
"Vec" => {
if let syn::PathArguments::AngleBracketed(a) = &final_segment.arguments {
assert!(a.args.len() == 1, "Only one argument allowed in a Vec");
if let GenericArgument::Type(t) = &a.args[0] {
match t {
Type::Path(p) => {
let type_return = get_path_type_name(p).0;
match type_return.as_str() {
"u8" => return (String::from("buf"), optional),
_ => panic!("Vec<u8> is the only allowed use of the Vec type"),
};
}
_ => panic!("Vec<u8> is the only allowed use of the Vec type"),
}
}
} else {
panic!("Vec<u8> is the only allowed use of the Vec type");
}
}
_ => {}
}
(final_segment.ident.to_string(), false)
}
fn impl_model(
name: &Ident,
fields: &Vec<&Field>,
tbl_name: Option<String>,
generics: &Generics,
) -> TokenStream {
let table_name_final = match tbl_name {
Some(n) => Ident::new(&n, name.span()),
None => name.to_owned(),
};
let geom_field_name: String;
let mut final_generics = generics.clone();
if let Some(g) = final_generics.params.first_mut() {
match g {
GenericParam::Lifetime(l) => match l.lifetime.ident.to_string().as_str() {
"static" | "_" => {}
_ => l.lifetime.ident = Ident::new("_", Span::call_site()),
},
_ => {}
}
}
let field_infos: Vec<FieldInfo> = fields
.iter()
.map(|f| {
let mut optional = false;
let field_name = f.ident.as_ref().expect("Expected named field").to_string();
let type_name: String;
let is_geom_field = is_geom_field(&f);
match &f.ty {
syn::Type::Reference(r) => {
type_name = get_reference_type_name(r);
}
syn::Type::Path(tp) => {
(type_name, optional) = get_path_type_name(tp);
}
_ => panic!("Don't know how to map to GPKG type {:?}", f.ty),
}
let sql_type = match type_name.as_str() {
"bool" => quote!(INTEGER),
"String" | "str" => quote!(TEXT),
"i64" | "i32" | "i16" | "i8" => quote!(INTEGER),
"f64" | "f32" => quote!(REAL),
"buf" => quote!(BLOB),
"u128" | "u64" | "u32" | "u16" | "u8" => {
panic!("SQLite doesn't support unsigned integers, use a signed integer value")
}
_ if GEO_TYPES.contains(&type_name.as_str()) => quote!(BLOB),
_ => panic!("Don't know how to map to SQL type {}", type_name),
};
let geom_info = match is_geom_field {
true => Some(GeomInfo {
geom_type: type_name.clone(),
srs_id: 4326,
m: MZOptions::Prohibited,
z: MZOptions::Prohibited,
}),
false => None,
};
FieldInfo {
name: field_name,
optional,
geom_info,
type_for_sql: sql_type.to_string(),
}
})
.collect();
let geom_fields: Vec<&FieldInfo> = field_infos
.iter()
.filter(|f| f.geom_info.is_some())
.collect();
assert!(
geom_fields.len() <= 1,
"Found {} geometry fields, 1 is the maximum allowed amount",
geom_fields.len()
);
let mut geom_column_sql: Option<String> = None;
let mut contents_sql = format!(
r#"INSERT INTO gpkg_contents (table_name, data_type) VALUES ("{}", "{}");"#,
table_name_final, "attributes"
);
if geom_fields.len() > 0 {
let geom_field = geom_fields[0];
let geom_info = geom_field.geom_info.clone().unwrap();
let mut geom_type_sql = geom_info.geom_type.clone();
geom_type_sql.replace_range(0..4, "");
geom_field_name = geom_field.name.clone();
geom_column_sql = Some(format!(
r#"INSERT INTO gpkg_geometry_columns VALUES("{}", "{}", "{}", {}, {}, {});"#,
table_name_final,
geom_field_name,
geom_type_sql.to_uppercase(),
geom_info.srs_id,
geom_info.m as i32,
geom_info.z as i32
));
contents_sql = format!(
r#"INSERT INTO gpkg_contents (table_name, data_type, srs_id) VALUES ("{}", "{}", {});"#,
table_name_final, "features", geom_info.srs_id
);
};
let contents_ts: TokenStream = contents_sql
.parse()
.expect("Unable to convert contents table insert statement into token stream");
let geom_column_ts: TokenStream = match geom_column_sql {
Some(s) => s
.parse()
.expect("Unable to convert contents table insert statement into token stream"),
None => TokenStream::new(),
};
let column_defs = field_infos
.iter()
.map(|f| {
let null_str = if f.optional { "" } else { " NOT NULL" };
format!("{} {}{}", f.name, f.type_for_sql, null_str)
.parse()
.unwrap()
})
.collect::<Vec<TokenStream>>();
let column_names: Vec<Ident> = field_infos
.iter()
.map(|i| Ident::new(i.name.as_str(), Span::call_site()))
.collect();
let params = vec![quote!(?); column_names.len()];
let column_params: Vec<TokenStream> = field_infos
.iter()
.map(|i| {
let name_ident = Ident::new(i.name.as_str(), Span::call_site());
quote!(self.#name_ident)
})
.collect();
let column_nums = (0..column_defs.len())
.map(|i| LitInt::new(i.to_string().as_str(), Span::call_site()))
.collect::<Vec<LitInt>>();
let new = quote!(
impl GPKGModel <'_> for #name #final_generics {
fn create_table(gpkg: &GeoPackage) -> rusqlite::Result<()> {
return gpkg.conn.execute_batch(
std::stringify!(
BEGIN;
CREATE TABLE #table_name_final (
object_id INTEGER PRIMARY KEY,
#(#column_defs ),*
);
#geom_column_ts
#contents_ts
COMMIT;
)
)
}
fn insert_record(&self, gpkg: &GeoPackage) -> rusqlite::Result<()> {
let sql =
std::stringify!(
INSERT INTO #table_name_final (
#(#column_names),*
) VALUES (
#(#params),*
)
);
gpkg.conn.execute(
sql,
rusqlite::params![
#(#column_params),*
]
)?;
Ok(())
}
fn get_first(gpkg: &GeoPackage) -> Result<Option<Self>, rusqlite::Error> {
let mut stmt = gpkg.conn.prepare(
std::stringify!(
SELECT #(#column_names),* FROM #table_name_final;
)
)?;
let mut rows = stmt.query([])?;
if let Some(row) = rows.next()? {
Ok(Some(Self {
#(#column_names: row.get((#column_nums))?,)*
}))
}
else {
Ok(None)
}
}
fn get_all(gpkg: &GeoPackage) -> Result<Vec<Self>, rusqlite::Error> {
let mut stmt = gpkg.conn.prepare(
std::stringify!(
SELECT #(#column_names),* FROM #table_name_final;
)
)?;
let mut out_vec = Vec::new();
let rows = stmt.query_map([], |row| {
Ok(Self {
#(#column_names: row.get((#column_nums))?,)*
})
})?;
for r in rows {
out_vec.push(r?)
}
Ok(out_vec)
}
fn get_where(gpkg: &GeoPackage, predicate: &str) -> Result<Vec<Self>, rusqlite::Error> {
let mut stmt = gpkg.conn.prepare(
(std::stringify!(
SELECT #(#column_names),* FROM #table_name_final WHERE
).to_owned() + " " + predicate + ";").as_str()
)?;
let mut out_vec = Vec::new();
let rows = stmt.query_map([], |row| {
Ok(Self {
#(#column_names: row.get((#column_nums))?,)*
})
})?;
for r in rows {
out_vec.push(r?)
}
Ok(out_vec)
}
}
);
new
}
fn is_geom_field(field: &Field) -> bool {
for attr in &field.attrs {
if let Some(ident) = attr.path.get_ident() {
if ident.to_string() == "geom_field" {
return true;
}
}
}
false
}
#[cfg(test)]
mod test {
use super::*;
use quote::quote;
#[test]
fn basic_test() {
let tstream = quote!(
#[table_name = "streetlights"]
struct StreetLight {
id: i64,
height: f64,
string_ref: Option<String>,
buf_ref: &'a [u8],
#[geom_field]
geom: GPKGLineStringZ,
}
);
println!("{}", derive_gpkg_inner(tstream.into()));
}
}