/
ogrext.pyx
2436 lines (1937 loc) · 81.9 KB
/
ogrext.pyx
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Extension classes and functions using the OGR C API."""
include "gdal.pxi"
import datetime
import json
import locale
import logging
import os
import warnings
import math
from collections import namedtuple
from typing import List
from uuid import uuid4
from fiona.crs cimport CRS, osr_set_traditional_axis_mapping_strategy
from fiona._geometry cimport (
GeomBuilder, OGRGeomBuilder, geometry_type_code,
normalize_geometry_type_code, base_geometry_type_code)
from fiona._err cimport exc_wrap_int, exc_wrap_pointer, exc_wrap_vsilfile, get_last_error_msg
import fiona
from fiona._env import get_gdal_version_num, calc_gdal_version_num, get_gdal_version_tuple
from fiona._err import (
cpl_errs, FionaNullPointerError, CPLE_BaseError, CPLE_AppDefinedError,
CPLE_OpenFailedError)
from fiona._geometry import GEOMETRY_TYPES
from fiona import compat
from fiona.compat import strencode
from fiona.env import Env
from fiona.errors import (
DriverError, DriverIOError, SchemaError, CRSError, FionaValueError,
TransactionError, GeometryTypeValidationError, DatasetDeleteError,
AttributeFilterError, FeatureWarning, FionaDeprecationWarning, UnsupportedGeometryTypeError)
from fiona.model import decode_object, Feature, Geometry, Properties
from fiona._path import _vsi_path
from fiona.rfc3339 import parse_date, parse_datetime, parse_time
from fiona.schema import FIELD_TYPES_MAP2, normalize_field_type, NAMED_FIELD_TYPES
from libc.stdlib cimport malloc, free
from libc.string cimport strcmp
from cpython cimport PyBytes_FromStringAndSize, PyBytes_AsString
from fiona.drvsupport import _driver_supports_timezones
log = logging.getLogger(__name__)
DEFAULT_TRANSACTION_SIZE = 20000
# OGR Driver capability
cdef const char * ODrCCreateDataSource = "CreateDataSource"
cdef const char * ODrCDeleteDataSource = "DeleteDataSource"
# OGR Layer capability
cdef const char * OLC_RANDOMREAD = "RandomRead"
cdef const char * OLC_SEQUENTIALWRITE = "SequentialWrite"
cdef const char * OLC_RANDOMWRITE = "RandomWrite"
cdef const char * OLC_FASTSPATIALFILTER = "FastSpatialFilter"
cdef const char * OLC_FASTFEATURECOUNT = "FastFeatureCount"
cdef const char * OLC_FASTGETEXTENT = "FastGetExtent"
cdef const char * OLC_FASTSETNEXTBYINDEX = "FastSetNextByIndex"
cdef const char * OLC_CREATEFIELD = "CreateField"
cdef const char * OLC_CREATEGEOMFIELD = "CreateGeomField"
cdef const char * OLC_DELETEFIELD = "DeleteField"
cdef const char * OLC_REORDERFIELDS = "ReorderFields"
cdef const char * OLC_ALTERFIELDDEFN = "AlterFieldDefn"
cdef const char * OLC_DELETEFEATURE = "DeleteFeature"
cdef const char * OLC_STRINGSASUTF8 = "StringsAsUTF8"
cdef const char * OLC_TRANSACTIONS = "Transactions"
cdef const char * OLC_IGNOREFIELDS = "IgnoreFields"
# OGR integer error types.
OGRERR_NONE = 0
OGRERR_NOT_ENOUGH_DATA = 1 # not enough data to deserialize */
OGRERR_NOT_ENOUGH_MEMORY = 2
OGRERR_UNSUPPORTED_GEOMETRY_TYPE = 3
OGRERR_UNSUPPORTED_OPERATION = 4
OGRERR_CORRUPT_DATA = 5
OGRERR_FAILURE = 6
OGRERR_UNSUPPORTED_SRS = 7
OGRERR_INVALID_HANDLE = 8
cdef void gdal_flush_cache(void *cogr_ds):
with cpl_errs:
GDALFlushCache(cogr_ds)
cdef void* gdal_open_vector(const char* path_c, int mode, drivers, options) except NULL:
cdef void* cogr_ds = NULL
cdef char **drvs = NULL
cdef void* drv = NULL
cdef char **open_opts = NULL
flags = GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR
if mode == 1:
flags |= GDAL_OF_UPDATE
else:
flags |= GDAL_OF_READONLY
if drivers:
for name in drivers:
name_b = name.encode()
name_c = name_b
drv = GDALGetDriverByName(name_c)
if drv != NULL:
drvs = CSLAddString(drvs, name_c)
for k, v in options.items():
if v is not None:
kb = k.upper().encode('utf-8')
if isinstance(v, bool):
vb = ('ON' if v else 'OFF').encode('utf-8')
else:
vb = str(v).encode('utf-8')
open_opts = CSLAddNameValue(open_opts, <const char *>kb, <const char *>vb)
open_opts = CSLAddNameValue(open_opts, "VALIDATE_OPEN_OPTIONS", "NO")
try:
cogr_ds = exc_wrap_pointer(
GDALOpenEx(path_c, flags, <const char *const *>drvs, <const char *const *>open_opts, NULL)
)
return cogr_ds
except FionaNullPointerError:
raise DriverError(
f"Failed to open dataset (mode={mode}): {path_c.decode('utf-8')}")
except CPLE_BaseError as exc:
raise DriverError(str(exc))
finally:
CSLDestroy(drvs)
CSLDestroy(open_opts)
cdef void* gdal_create(void* cogr_driver, const char *path_c, options) except NULL:
cdef char **creation_opts = NULL
cdef void *cogr_ds = NULL
db = <const char *>GDALGetDriverShortName(cogr_driver)
# To avoid a circular import.
from fiona import meta
option_keys = set(key.upper() for key in options.keys())
creation_option_keys = option_keys & set(meta.dataset_creation_options(db.decode("utf-8")))
for k, v in options.items():
if k.upper() in creation_option_keys:
kb = k.upper().encode('utf-8')
if isinstance(v, bool):
vb = ('ON' if v else 'OFF').encode('utf-8')
else:
vb = str(v).encode('utf-8')
creation_opts = CSLAddNameValue(creation_opts, <const char *>kb, <const char *>vb)
try:
return exc_wrap_pointer(GDALCreate(cogr_driver, path_c, 0, 0, 0, GDT_Unknown, creation_opts))
except FionaNullPointerError:
raise DriverError(f"Failed to create dataset: {path_c.decode('utf-8')}")
except CPLE_BaseError as exc:
raise DriverError(str(exc))
finally:
CSLDestroy(creation_opts)
def _explode(coords):
"""Explode a GeoJSON geometry's coordinates object and yield
coordinate tuples. As long as the input is conforming, the type of
the geometry doesn't matter."""
for e in coords:
if isinstance(e, (float, int)):
yield coords
break
else:
for f in _explode(e):
yield f
def _bounds(geometry):
"""Bounding box of a GeoJSON geometry"""
try:
xyz = tuple(zip(*list(_explode(geometry['coordinates']))))
return min(xyz[0]), min(xyz[1]), max(xyz[0]), max(xyz[1])
except (KeyError, TypeError):
return None
cdef int GDAL_VERSION_NUM = get_gdal_version_num()
class TZ(datetime.tzinfo):
def __init__(self, minutes):
self.minutes = minutes
def utcoffset(self, dt):
return datetime.timedelta(minutes=self.minutes)
cdef class AbstractField:
cdef object driver
cdef object supports_tz
def __init__(self, driver=None):
self.driver = driver
cdef object name(self, OGRFieldDefnH fdefn):
"""Get the short Fiona field name corresponding to the OGR field definition."""
raise NotImplementedError
cdef object get(self, OGRFeatureH feature, int i, object kwds):
"""Get the value of a feature's field."""
raise NotImplementedError
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
"""Set the value of a feature's field."""
raise NotImplementedError
cdef class IntegerField(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
cdef int width = OGR_Fld_GetWidth(fdefn)
fmt = ""
if width:
fmt = f":{width:d}"
return f"int32{fmt}"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
return OGR_F_GetFieldAsInteger(feature, i)
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
OGR_F_SetFieldInteger(feature, i, int(value))
cdef class Int16Field(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
cdef int width = OGR_Fld_GetWidth(fdefn)
fmt = ""
if width:
fmt = f":{width:d}"
return f"int16{fmt}"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
return OGR_F_GetFieldAsInteger(feature, i)
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
OGR_F_SetFieldInteger(feature, i, int(value))
cdef class BooleanField(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
return "bool"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
return bool(OGR_F_GetFieldAsInteger(feature, i))
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
OGR_F_SetFieldInteger(feature, i, int(value))
cdef class Integer64Field(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
cdef int width = OGR_Fld_GetWidth(fdefn)
fmt = ""
if width:
fmt = f":{width:d}"
return f"int{fmt}"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
return OGR_F_GetFieldAsInteger64(feature, i)
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
OGR_F_SetFieldInteger64(feature, i, int(value))
cdef class RealField(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
cdef int width = OGR_Fld_GetWidth(fdefn)
cdef int precision = OGR_Fld_GetPrecision(fdefn)
fmt = ""
if width:
fmt = f":{width:d}"
if precision:
fmt += f".{precision:d}"
return f"float{fmt}"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
return OGR_F_GetFieldAsDouble(feature, i)
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
OGR_F_SetFieldDouble(feature, i, float(value))
cdef class StringField(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
cdef int width = OGR_Fld_GetWidth(fdefn)
fmt = ""
if width:
fmt = f":{width:d}"
return f"str{fmt}"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
encoding = kwds["encoding"]
val = OGR_F_GetFieldAsString(feature, i)
try:
val = val.decode(encoding)
except UnicodeDecodeError:
log.warning(
"Failed to decode %s using %s codec", val, encoding)
else:
return val
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
encoding = kwds["encoding"]
cdef object value_b = str(value).encode(encoding)
OGR_F_SetFieldString(feature, i, <const char *>value_b)
cdef class BinaryField(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
return "bytes"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
cdef unsigned char *data = NULL
cdef int l
data = OGR_F_GetFieldAsBinary(feature, i, &l)
return data[:l]
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
OGR_F_SetFieldBinary(feature, i, len(value), <const unsigned char *>value)
cdef class StringListField(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
return "List[str]"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
cdef char **string_list = NULL
encoding = kwds["encoding"]
string_list = OGR_F_GetFieldAsStringList(feature, i)
string_list_index = 0
vals = []
if string_list != NULL:
while string_list[string_list_index] != NULL:
val = string_list[string_list_index]
try:
val = val.decode(encoding)
except UnicodeDecodeError:
log.warning(
"Failed to decode %s using %s codec", val, encoding
)
vals.append(val)
string_list_index += 1
return vals
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
cdef char **string_list = NULL
encoding = kwds["encoding"]
for item in value:
item_b = item.encode(encoding)
string_list = CSLAddString(string_list, <const char *>item_b)
OGR_F_SetFieldStringList(feature, i, <const char **>string_list)
cdef class JSONField(AbstractField):
cdef object name(self, OGRFieldDefnH fdefn):
return "json"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
val = OGR_F_GetFieldAsString(feature, i)
return json.loads(val)
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
value_b = json.dumps(value).encode("utf-8")
OGR_F_SetFieldString(feature, i, <const char *>value_b)
cdef class DateField(AbstractField):
"""Dates without time."""
cdef object name(self, OGRFieldDefnH fdefn):
return "date"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
cdef int retval
cdef int y = 0
cdef int m = 0
cdef int d = 0
cdef int hh = 0
cdef int mm = 0
cdef float fss = 0.0
cdef int tz = 0
retval = OGR_F_GetFieldAsDateTimeEx(feature, i, &y, &m, &d, &hh, &mm, &fss, &tz)
return datetime.date(y, m, d).isoformat()
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
if isinstance(value, str):
y, m, d, hh, mm, ss, ms, tz = parse_date(value)
elif isinstance(value, datetime.date):
y, m, d = value.year, value.month, value.day
hh = mm = ss = ms = 0
else:
raise ValueError()
tzinfo = 0
OGR_F_SetFieldDateTimeEx(feature, i, y, m, d, hh, mm, ss, tzinfo)
cdef class TimeField(AbstractField):
"""Times without dates."""
def __init__(self, driver=None):
self.driver = driver
self.supports_tz = _driver_supports_timezones(self.driver, "time")
cdef object name(self, OGRFieldDefnH fdefn):
return "time"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
cdef int retval
cdef int y = 0
cdef int m = 0
cdef int d = 0
cdef int hh = 0
cdef int mm = 0
cdef float fss = 0.0
cdef int tz = 0
retval = OGR_F_GetFieldAsDateTimeEx(feature, i, &y, &m, &d, &hh, &mm, &fss, &tz)
ms, ss = math.modf(fss)
ss = int(ss)
ms = int(round(ms * 10**6))
# OGR_F_GetFieldAsDateTimeEx: (0=unknown, 1=localtime, 100=GMT, see data model for details)
# CPLParseRFC822DateTime: (0=unknown, 100=GMT, 101=GMT+15minute, 99=GMT-15minute), or NULL
tzinfo = None
if tz > 1:
tz_minutes = (tz - 100) * 15
tzinfo = TZ(tz_minutes)
return datetime.time(hh, mm, ss, ms, tzinfo).isoformat()
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
if isinstance(value, str):
y, m, d, hh, mm, ss, ms, tz = parse_time(value)
elif isinstance(value, datetime.time):
y = m = d = 0
hh, mm, ss, ms = value.hour, value.minute, value.second, value.microsecond
if value.utcoffset() is None:
tz = None
else:
tz = value.utcoffset().total_seconds() / 60
else:
raise ValueError()
if tz is not None and not self.supports_tz:
d_tz = datetime.datetime(1900, 1, 1, hh, mm, ss, int(ms), TZ(tz))
d_utc = d_tz - d_tz.utcoffset()
y = m = d = 0
hh, mm, ss, ms = d_utc.hour, d_utc.minute, d_utc.second, d_utc.microsecond
tz = 0
# tzinfo: (0=unknown, 100=GMT, 101=GMT+15minute, 99=GMT-15minute), or NULL
if tz is not None:
tzinfo = int(tz / 15.0 + 100)
else:
tzinfo = 0
ss += ms / 10**6
OGR_F_SetFieldDateTimeEx(feature, i, y, m, d, hh, mm, ss, tzinfo)
cdef class DateTimeField(AbstractField):
"""Dates and times."""
def __init__(self, driver=None):
self.driver = driver
self.supports_tz = _driver_supports_timezones(self.driver, "datetime")
cdef object name(self, OGRFieldDefnH fdefn):
return "datetime"
cdef object get(self, OGRFeatureH feature, int i, object kwds):
cdef int retval
cdef int y = 0
cdef int m = 0
cdef int d = 0
cdef int hh = 0
cdef int mm = 0
cdef float fss = 0.0
cdef int tz = 0
retval = OGR_F_GetFieldAsDateTimeEx(feature, i, &y, &m, &d, &hh, &mm, &fss, &tz)
ms, ss = math.modf(fss)
ss = int(ss)
ms = int(round(ms * 10**6))
# OGR_F_GetFieldAsDateTimeEx: (0=unknown, 1=localtime, 100=GMT, see data model for details)
# CPLParseRFC822DateTime: (0=unknown, 100=GMT, 101=GMT+15minute, 99=GMT-15minute), or NULL
tzinfo = None
if tz > 1:
tz_minutes = (tz - 100) * 15
tzinfo = TZ(tz_minutes)
return datetime.datetime(y, m, d, hh, mm, ss, ms, tzinfo).isoformat()
cdef set(self, OGRFeatureH feature, int i, object value, object kwds):
if isinstance(value, str):
y, m, d, hh, mm, ss, ms, tz = parse_datetime(value)
elif isinstance(value, datetime.datetime):
y, m, d = value.year, value.month, value.day
hh, mm, ss, ms = value.hour, value.minute, value.second, value.microsecond
if value.utcoffset() is None:
tz = None
else:
tz = value.utcoffset().total_seconds() / 60
else:
raise ValueError()
if tz is not None and not self.supports_tz:
d_tz = datetime.datetime(y, m, d, hh, mm, ss, int(ms), TZ(tz))
d_utc = d_tz - d_tz.utcoffset()
y, m, d = d_utc.year, d_utc.month, d_utc.day
hh, mm, ss, ms = d_utc.hour, d_utc.minute, d_utc.second, d_utc.microsecond
tz = 0
# tzinfo: (0=unknown, 100=GMT, 101=GMT+15minute, 99=GMT-15minute), or NULL
if tz is not None:
tzinfo = int(tz / 15.0 + 100)
else:
tzinfo = 0
ss += ms / 10**6
OGR_F_SetFieldDateTimeEx(feature, i, y, m, d, hh, mm, ss, tzinfo)
cdef bint is_field_null(OGRFeatureH feature, int i):
return OGR_F_IsFieldNull(feature, i) or not OGR_F_IsFieldSet(feature, i)
cdef class FeatureBuilder:
"""Build Fiona features from OGR feature pointers.
No OGR objects are allocated by this function and the feature
argument is not destroyed.
"""
cdef object driver
cdef object property_getter_cache
OGRPropertyGetter = {
(OFTInteger, OFSTNone): IntegerField,
(OFTInteger, OFSTBoolean): BooleanField,
(OFTInteger, OFSTInt16): Int16Field,
(OFTInteger64, OFSTNone): Integer64Field,
(OFTReal, OFSTNone): RealField,
(OFTString, OFSTNone): StringField,
(OFTDate, OFSTNone): DateField,
(OFTTime, OFSTNone): TimeField,
(OFTDateTime, OFSTNone): DateTimeField,
(OFTBinary, OFSTNone): BinaryField,
(OFTStringList, OFSTNone): StringListField,
(OFTString, OFSTJSON): JSONField,
}
def __init__(self, driver=None):
self.driver = driver
self.property_getter_cache = {}
cdef build(
self,
OGRFeatureH feature,
encoding='utf-8',
bbox=False,
driver=None,
ignore_fields=None,
ignore_geometry=False
):
"""Build a Fiona feature object from an OGR feature
Parameters
----------
feature : void *
The OGR feature # TODO: use a real typedef
encoding : str
The encoding of OGR feature attributes
bbox : bool
Not used
driver : str
OGR format driver name like 'GeoJSON'
ignore_fields : sequence
A sequence of field names that will be ignored and omitted
in the Fiona feature properties
ignore_geometry : bool
Flag for whether the OGR geometry field is to be ignored
Returns
-------
dict
"""
cdef OGRFieldDefnH fdefn
cdef int i
cdef int fieldtype
cdef int fieldsubtype
cdef const char *key_c
cdef AbstractField getter
# Skeleton of the feature to be returned.
fid = OGR_F_GetFID(feature)
props = {}
ignore_fields = set(ignore_fields or [])
for i in range(OGR_F_GetFieldCount(feature)):
fdefn = OGR_F_GetFieldDefnRef(feature, i)
if fdefn == NULL:
raise ValueError(f"NULL field definition at index {i}")
key_c = OGR_Fld_GetNameRef(fdefn)
if key_c == NULL:
raise ValueError(f"NULL field name reference at index {i}")
key_b = key_c
key = key_b.decode(encoding)
# Some field names are empty strings, apparently.
# We warn in this case.
if not key:
warnings.warn(f"Empty field name at index {i}")
if key in ignore_fields:
continue
fieldtype = OGR_Fld_GetType(fdefn)
fieldsubtype = OGR_Fld_GetSubType(fdefn)
fieldkey = (fieldtype, fieldsubtype)
if is_field_null(feature, i):
props[key] = None
else:
if fieldkey in self.property_getter_cache:
getter = self.property_getter_cache[fieldkey]
else:
try:
getter = self.OGRPropertyGetter[fieldkey](driver=driver or self.driver)
self.property_getter_cache[fieldkey] = getter
except KeyError:
log.warning(
"Skipping field %s: invalid type %s",
key,
fieldkey
)
continue
props[key] = getter.get(feature, i, {"encoding": encoding})
cdef void *cogr_geometry = NULL
geom = None
if not ignore_geometry:
cogr_geometry = OGR_F_GetGeometryRef(feature)
geom = GeomBuilder().build_from_feature(feature)
return Feature(id=str(fid), properties=Properties(**props), geometry=geom)
cdef class OGRFeatureBuilder:
"""Builds an OGR Feature from a Fiona feature mapping.
Allocates one OGR Feature which should be destroyed by the caller.
Borrows a layer definition from the collection.
"""
cdef object driver
cdef object property_setter_cache
OGRPropertySetter = {
(OFTInteger, OFSTNone, "int"): IntegerField,
(OFTInteger, OFSTNone, "int32"): IntegerField,
(OFTInteger, OFSTNone, "float"): RealField,
(OFTInteger, OFSTNone, "str"): StringField,
(OFTInteger, OFSTBoolean, "bool"): BooleanField,
(OFTInteger, OFSTBoolean, "int"): BooleanField,
(OFTInteger, OFSTInt16, "int"): Int16Field,
(OFTInteger, OFSTInt16, "str"): StringField,
(OFTInteger64, OFSTNone, "int"): Integer64Field,
(OFTInteger64, OFSTNone, "int64"): Integer64Field,
(OFTInteger64, OFSTNone, "float"): RealField,
(OFTInteger64, OFSTNone, "str"): StringField,
(OFTReal, OFSTNone, "float"): RealField,
(OFTReal, OFSTNone, "str"): StringField,
(OFTReal, OFSTFloat32, "float"): RealField,
(OFTReal, OFSTFloat32, "float32"): RealField,
(OFTReal, OFSTFloat32, "str"): StringField,
(OFTString, OFSTNone, "str"): StringField,
(OFTString, OFSTNone, "dict"): StringField,
(OFTDate, OFSTNone, "date"): DateField,
(OFTDate, OFSTNone, "str"): DateField,
(OFTTime, OFSTNone, "time"): TimeField,
(OFTTime, OFSTNone, "str"): TimeField,
(OFTDateTime, OFSTNone, "datetime"): DateTimeField,
(OFTDateTime, OFSTNone, "str"): DateTimeField,
(OFTBinary, OFSTNone, "bytes"): BinaryField,
(OFTBinary, OFSTNone, "bytearray"): BinaryField,
(OFTBinary, OFSTNone, "memoryview"): BinaryField,
(OFTStringList, OFSTNone, "list"): StringListField,
(OFTString, OFSTJSON, "dict"): JSONField,
(OFTString, OFSTJSON, "list"): JSONField,
}
def __init__(self, driver=None):
self.driver = driver
self.property_setter_cache = {}
cdef OGRFeatureH build(self, feature, collection) except NULL:
cdef void *cogr_geometry = NULL
cdef const char *string_c = NULL
cdef WritingSession session = collection.session
cdef void *cogr_layer = session.cogr_layer
cdef void *cogr_featuredefn = OGR_L_GetLayerDefn(cogr_layer)
cdef void *cogr_feature = OGR_F_Create(cogr_featuredefn)
cdef AbstractField setter
if cogr_layer == NULL:
raise ValueError("Null layer")
if cogr_featuredefn == NULL:
raise ValueError("Null feature definition")
if cogr_feature == NULL:
raise ValueError("Null feature")
if feature.geometry is not None:
cogr_geometry = OGRGeomBuilder().build(feature.geometry)
exc_wrap_int(OGR_F_SetGeometryDirectly(cogr_feature, cogr_geometry))
encoding = session._get_internal_encoding()
for key, value in feature.properties.items():
i = session._schema_mapping_index[key]
if i < 0:
continue
if value is None:
OGR_F_SetFieldNull(cogr_feature, i)
else:
schema_type = session._schema_normalized_field_types[key]
val_type = type(value)
if val_type in self.property_setter_cache:
setter = self.property_setter_cache[val_type]
else:
for cls in val_type.mro():
fieldkey = (*FIELD_TYPES_MAP2[NAMED_FIELD_TYPES[schema_type]], cls.__name__)
try:
setter = self.OGRPropertySetter[fieldkey](driver=self.driver)
except KeyError:
continue
else:
self.property_setter_cache[val_type] = setter
break
else:
log.warning("Skipping field because of invalid value: key=%r, value=%r", key, value)
continue
# Special case: serialize dicts to assist OGR.
if isinstance(value, dict):
value = json.dumps(value)
log.debug("Setting feature property: key=%r, value=%r, i=%r, setter=%r", key, value, i, setter)
setter.set(cogr_feature, i, value, {"encoding": encoding})
return cogr_feature
cdef _deleteOgrFeature(void *cogr_feature):
"""Delete an OGR feature"""
if cogr_feature is not NULL:
OGR_F_Destroy(cogr_feature)
cogr_feature = NULL
def featureRT(feat, collection):
# For testing purposes only, leaks the JSON data
feature = decode_object(feat)
cdef void *cogr_feature = OGRFeatureBuilder().build(feature, collection)
cdef void *cogr_geometry = OGR_F_GetGeometryRef(cogr_feature)
if cogr_geometry == NULL:
raise ValueError("Null geometry")
result = FeatureBuilder().build(
cogr_feature,
encoding='utf-8',
bbox=False,
driver=collection.driver
)
_deleteOgrFeature(cogr_feature)
return result
cdef class Session:
cdef void *cogr_ds
cdef void *cogr_layer
cdef object _fileencoding
cdef object _encoding
cdef object collection
cdef bint cursor_interrupted
OGRFieldGetter = {
(OFTInteger, OFSTNone): IntegerField,
(OFTInteger, OFSTBoolean): BooleanField,
(OFTInteger, OFSTInt16): Int16Field,
(OFTInteger64, OFSTNone): Integer64Field,
(OFTReal, OFSTNone): RealField,
(OFTString, OFSTNone): StringField,
(OFTDate, OFSTNone): DateField,
(OFTTime, OFSTNone): TimeField,
(OFTDateTime, OFSTNone): DateTimeField,
(OFTBinary, OFSTNone): BinaryField,
(OFTStringList, OFSTNone): StringListField,
(OFTString, OFSTJSON): JSONField,
}
def __init__(self):
self.cogr_ds = NULL
self.cogr_layer = NULL
self._fileencoding = None
self._encoding = None
self.cursor_interrupted = False
def __dealloc__(self):
self.stop()
def start(self, collection, **kwargs):
cdef const char *path_c = NULL
cdef const char *name_c = NULL
cdef void *drv = NULL
cdef void *ds = NULL
cdef char **ignore_fields = NULL
path_b = collection.path.encode('utf-8')
path_c = path_b
self._fileencoding = kwargs.get('encoding') or collection.encoding
# We have two ways of specifying drivers to try. Resolve the
# values into a single set of driver short names.
if collection._driver:
drivers = set([collection._driver])
elif collection.enabled_drivers:
drivers = set(collection.enabled_drivers)
else:
drivers = None
encoding = kwargs.pop('encoding', None)
if encoding:
kwargs['encoding'] = encoding.upper()
self.cogr_ds = gdal_open_vector(path_c, 0, drivers, kwargs)
layername = collection.name
if isinstance(layername, str):
layername_b = layername.encode('utf-8')
self.cogr_layer = GDALDatasetGetLayerByName(self.cogr_ds, <const char *>layername_b)
elif isinstance(layername, int):
self.cogr_layer = GDALDatasetGetLayer(self.cogr_ds, <int>layername)
if self.cogr_layer == NULL:
raise ValueError(f"Null layer: {collection} {layername}")
else:
name_c = OGR_L_GetName(self.cogr_layer)
name_b = name_c
collection.name = name_b.decode('utf-8')
encoding = self._get_internal_encoding()
if collection.ignore_fields or collection.include_fields is not None:
if not OGR_L_TestCapability(self.cogr_layer, OLC_IGNOREFIELDS):
raise DriverError("Driver does not support ignore_fields")
self.collection = collection
if self.collection.include_fields is not None:
self.collection.ignore_fields = list(
set(self.get_schema()["properties"]) - set(collection.include_fields)
)
if self.collection.ignore_fields:
try:
for name in self.collection.ignore_fields:
try:
name_b = name.encode(encoding)
except AttributeError:
raise TypeError(
f'Ignored field "{name}" has type '
f'"{name.__class__.__name__}", expected string'
)
else:
ignore_fields = CSLAddString(ignore_fields, <const char *>name_b)
OGR_L_SetIgnoredFields(self.cogr_layer, <const char**>ignore_fields)
finally:
CSLDestroy(ignore_fields)
cpdef stop(self):
self.cogr_layer = NULL
if self.cogr_ds != NULL:
try:
with cpl_errs:
GDALClose(self.cogr_ds)
except CPLE_BaseError as exc:
raise DriverError(str(exc))
finally:
self.cogr_ds = NULL
def get_fileencoding(self):
"""DEPRECATED"""
warnings.warn("get_fileencoding is deprecated and will be removed in a future version.", FionaDeprecationWarning)
return self._fileencoding
def _get_fallback_encoding(self):
"""Determine a format-specific fallback encoding to use when using OGR_F functions
Parameters
----------
None
Returns
-------
str
"""
if "Shapefile" in self.get_driver():
return 'iso-8859-1'
else:
return locale.getpreferredencoding()
def _get_internal_encoding(self):
"""Determine the encoding to use when use OGR_F functions
Parameters
----------
None
Returns
-------
str
Notes
-----
If the layer implements RFC 23 support for UTF-8, the return
value will be 'utf-8' and callers can be certain that this is
correct. If the layer does not have the OLC_STRINGSASUTF8
capability marker, it is not possible to know exactly what the
internal encoding is and this method returns best guesses. That
means ISO-8859-1 for shapefiles and the locale's preferred
encoding for other formats such as CSV files.
"""
if OGR_L_TestCapability(self.cogr_layer, OLC_STRINGSASUTF8):
return 'utf-8'
else:
return self._fileencoding or self._get_fallback_encoding()
def get_length(self):
if self.cogr_layer == NULL:
raise ValueError("Null layer")
return self._get_feature_count(0)
def get_driver(self):
cdef void *cogr_driver = GDALGetDatasetDriver(self.cogr_ds)
if cogr_driver == NULL:
raise ValueError("Null driver")
cdef const char *name = OGR_Dr_GetName(cogr_driver)
driver_name = name
return driver_name.decode()
def get_schema(self):
"""Get a dictionary representation of a collection's schema.
The schema dict contains "geometry" and "properties" items.