-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path_io.pyx
2786 lines (2183 loc) · 92 KB
/
_io.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
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
"""IO support for OGR vector data sources
"""
import contextlib
import datetime
import locale
import logging
import math
import os
import sys
import warnings
from pathlib import Path
from libc.stdint cimport uint8_t, uintptr_t
from libc.stdlib cimport malloc, free
from libc.string cimport strlen
from libc.math cimport isnan
from cpython.pycapsule cimport PyCapsule_GetPointer
cimport cython
from cpython.pycapsule cimport PyCapsule_New, PyCapsule_GetPointer
import numpy as np
from pyogrio._ogr cimport *
from pyogrio._err cimport (
check_last_error, check_int, check_pointer, ErrorHandler
)
from pyogrio._vsi cimport *
from pyogrio._err import (
CPLE_AppDefinedError,
CPLE_BaseError,
CPLE_NotSupportedError,
CPLE_OpenFailedError,
NullPointerError,
capture_errors,
)
from pyogrio._geometry cimport get_geometry_type, get_geometry_type_code
from pyogrio.errors import CRSError, DataSourceError, DataLayerError, GeometryError, FieldError, FeatureError
log = logging.getLogger(__name__)
# Mapping of OGR integer field types to Python field type names
# (index in array is the integer field type)
FIELD_TYPES = [
'int32', # OFTInteger, Simple 32bit integer
None, # OFTIntegerList, List of 32bit integers, not supported
'float64', # OFTReal, Double Precision floating point
None, # OFTRealList, List of doubles, not supported
'object', # OFTString, String of UTF-8 chars
None, # OFTStringList, Array of strings, not supported
None, # OFTWideString, deprecated, not supported
None, # OFTWideStringList, deprecated, not supported
'object', # OFTBinary, Raw Binary data
'datetime64[D]', # OFTDate, Date
None, # OFTTime, Time, NOTE: not directly supported in numpy
'datetime64[ms]',# OFTDateTime, Date and Time
'int64', # OFTInteger64, Single 64bit integer
None # OFTInteger64List, List of 64bit integers, not supported
]
FIELD_SUBTYPES = {
OFSTNone: None, # No subtype
OFSTBoolean: "bool", # Boolean integer
OFSTInt16: "int16", # Signed 16-bit integer
OFSTFloat32: "float32", # Single precision (32 bit) floating point
}
# Mapping of numpy ndarray dtypes to (field type, subtype)
DTYPE_OGR_FIELD_TYPES = {
'int8': (OFTInteger, OFSTInt16),
'int16': (OFTInteger, OFSTInt16),
'int32': (OFTInteger, OFSTNone),
'int': (OFTInteger64, OFSTNone),
'int64': (OFTInteger64, OFSTNone),
# unsigned ints have to be converted to ints; these are converted
# to the next largest integer size
'uint8': (OFTInteger, OFSTInt16),
'uint16': (OFTInteger, OFSTNone),
'uint32': (OFTInteger64, OFSTNone),
# TODO: these might get truncated, check maximum value and raise error
'uint': (OFTInteger64, OFSTNone),
'uint64': (OFTInteger64, OFSTNone),
# bool is handled as integer with boolean subtype
'bool': (OFTInteger, OFSTBoolean),
'float32': (OFTReal,OFSTFloat32),
'float': (OFTReal, OFSTNone),
'float64': (OFTReal, OFSTNone),
'datetime64[D]': (OFTDate, OFSTNone),
'datetime64': (OFTDateTime, OFSTNone),
}
cdef int start_transaction(OGRDataSourceH ogr_dataset, int force) except 1:
cdef int err = GDALDatasetStartTransaction(ogr_dataset, force)
if err == OGRERR_FAILURE:
raise DataSourceError("Failed to start transaction")
return 0
cdef int commit_transaction(OGRDataSourceH ogr_dataset) except 1:
cdef int err = GDALDatasetCommitTransaction(ogr_dataset)
if err == OGRERR_FAILURE:
raise DataSourceError("Failed to commit transaction")
return 0
# Not currently used; uncomment when used
# cdef int rollback_transaction(OGRDataSourceH ogr_dataset) except 1:
# cdef int err = GDALDatasetRollbackTransaction(ogr_dataset)
# if err == OGRERR_FAILURE:
# raise DataSourceError("Failed to rollback transaction")
# return 0
cdef char** dict_to_options(object values):
"""Convert a python dictionary into name / value pairs (stored in a char**)
Parameters
----------
values: dict
all keys and values must be strings
Returns
-------
char**
"""
cdef char **options = NULL
if values is None:
return NULL
for k, v in values.items():
k = k.encode('UTF-8')
v = v.encode('UTF-8')
options = CSLAddNameValue(options, <const char *>k, <const char *>v)
return options
cdef const char* override_threadlocal_config_option(str key, str value):
"""Set the CPLSetThreadLocalConfigOption for key=value
Parameters
----------
key : str
value : str
Returns
-------
const char*
value previously set for key, so that it can be later restored. Caller
is responsible for freeing this via CPLFree() if not NULL.
"""
key_b = key.encode("UTF-8")
cdef const char* key_c = key_b
value_b = value.encode("UTF-8")
cdef const char* value_c = value_b
cdef const char *prev_value = CPLGetThreadLocalConfigOption(key_c, NULL)
if prev_value != NULL:
# strings returned from config options may be replaced via
# CPLSetConfigOption() below; GDAL instructs us to save a copy
# in a new string
prev_value = CPLStrdup(prev_value)
CPLSetThreadLocalConfigOption(key_c, value_c)
return prev_value
cdef void* ogr_open(const char* path_c, int mode, char** options) except NULL:
"""Open an existing OGR data source
Parameters
----------
path_c : char *
input path, including an in-memory path (/vsimem/...)
mode : int
set to 1 to allow updating data source
options : char **, optional
dataset open options
"""
cdef void *ogr_dataset = NULL
cdef ErrorHandler errors
# Force linear approximations in all cases
OGRSetNonLinearGeometriesEnabledFlag(0)
flags = GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR
if mode == 1:
flags |= GDAL_OF_UPDATE
else:
flags |= GDAL_OF_READONLY
try:
# WARNING: GDAL logs warnings about invalid open options to stderr
# instead of raising an error
with capture_errors() as errors:
ogr_dataset = GDALOpenEx(path_c, flags, NULL, <const char *const *>options, NULL)
return errors.check_pointer(ogr_dataset, True)
except NullPointerError:
raise DataSourceError(
f"Failed to open dataset ({mode=}): {path_c.decode('utf-8')}"
) from None
except CPLE_BaseError as exc:
if " a supported file format." in str(exc):
# In gdal 3.9, this error message was slightly changed, so we can only check
# on this part of the error message.
raise DataSourceError(
f"{str(exc)}; It might help to specify the correct driver explicitly by "
"prefixing the file path with '<DRIVER>:', e.g. 'CSV:path'."
) from None
raise DataSourceError(str(exc)) from None
cdef ogr_close(GDALDatasetH ogr_dataset):
"""Close the dataset and raise exception if that fails.
NOTE: some drivers only raise errors on write when calling GDALClose()
"""
if ogr_dataset != NULL:
IF CTE_GDAL_VERSION >= (3, 7, 0):
if GDALClose(ogr_dataset) != CE_None:
return check_last_error()
return
ELSE:
GDALClose(ogr_dataset)
# GDAL will set an error if there was an error writing the data source
# on close
return check_last_error()
cdef OGRLayerH get_ogr_layer(GDALDatasetH ogr_dataset, layer) except NULL:
"""Open OGR layer by index or name.
Parameters
----------
ogr_dataset : pointer to open OGR dataset
layer : str or int
name or index of layer
Returns
-------
pointer to OGR layer
"""
cdef OGRLayerH ogr_layer = NULL
try:
if isinstance(layer, str):
name_b = layer.encode('utf-8')
name_c = name_b
ogr_layer = check_pointer(GDALDatasetGetLayerByName(ogr_dataset, name_c))
elif isinstance(layer, int):
ogr_layer = check_pointer(GDALDatasetGetLayer(ogr_dataset, layer))
# GDAL does not always raise exception messages in this case
except NullPointerError:
raise DataLayerError(f"Layer '{layer}' could not be opened") from None
except CPLE_BaseError as exc:
raise DataLayerError(str(exc))
# if the driver is OSM, we need to execute SQL to set the layer to read in
# order to read it properly
if get_driver(ogr_dataset) == "OSM":
# Note: this returns NULL and does not need to be freed via
# GDALDatasetReleaseResultSet()
layer_name = get_string(OGR_L_GetName(ogr_layer))
sql_b = f"SET interest_layers = {layer_name}".encode('utf-8')
sql_c = sql_b
GDALDatasetExecuteSQL(ogr_dataset, sql_c, NULL, NULL)
return ogr_layer
cdef OGRLayerH execute_sql(GDALDatasetH ogr_dataset, str sql, str sql_dialect=None) except NULL:
"""Execute an SQL statement on a dataset.
Parameters
----------
ogr_dataset : pointer to open OGR dataset
sql : str
The sql statement to execute
sql_dialect : str, optional (default: None)
The sql dialect the sql statement is written in
Returns
-------
pointer to OGR layer
"""
try:
sql_b = sql.encode('utf-8')
sql_c = sql_b
if sql_dialect is None:
return check_pointer(GDALDatasetExecuteSQL(ogr_dataset, sql_c, NULL, NULL))
sql_dialect_b = sql_dialect.encode('utf-8')
sql_dialect_c = sql_dialect_b
return check_pointer(GDALDatasetExecuteSQL(ogr_dataset, sql_c, NULL, sql_dialect_c))
# GDAL does not always raise exception messages in this case
except NullPointerError:
raise DataLayerError(f"Error executing sql '{sql}'") from None
except CPLE_BaseError as exc:
raise DataLayerError(str(exc))
cdef str get_crs(OGRLayerH ogr_layer):
"""Read CRS from layer as EPSG:<code> if available or WKT.
Parameters
----------
ogr_layer : pointer to open OGR layer
Returns
-------
str or None
EPSG:<code> or WKT
"""
cdef void *ogr_crs = NULL
cdef const char *authority_key = NULL
cdef const char *authority_val = NULL
cdef char *ogr_wkt = NULL
try:
ogr_crs = check_pointer(OGR_L_GetSpatialRef(ogr_layer))
except NullPointerError:
# No coordinate system defined.
# This is expected and valid for nonspatial tables.
return None
except CPLE_BaseError as exc:
raise CRSError(str(exc))
# If CRS can be decoded to an EPSG code, use that.
# The following pointers will be NULL if it cannot be decoded.
retval = OSRAutoIdentifyEPSG(ogr_crs)
authority_key = <const char *>OSRGetAuthorityName(ogr_crs, NULL)
authority_val = <const char *>OSRGetAuthorityCode(ogr_crs, NULL)
if authority_key != NULL and authority_val != NULL:
key = get_string(authority_key)
if key == 'EPSG':
value = get_string(authority_val)
return f"EPSG:{value}"
try:
OSRExportToWkt(ogr_crs, &ogr_wkt)
if ogr_wkt == NULL:
raise CRSError("CRS could not be extracted as WKT") from None
wkt = get_string(ogr_wkt)
finally:
CPLFree(ogr_wkt)
return wkt
cdef get_driver(OGRDataSourceH ogr_dataset):
"""Get the driver for a dataset.
Parameters
----------
ogr_dataset : pointer to open OGR dataset
Returns
-------
str or None
"""
cdef void *ogr_driver
try:
ogr_driver = check_pointer(GDALGetDatasetDriver(ogr_dataset))
except NullPointerError:
raise DataLayerError(f"Could not detect driver of dataset") from None
except CPLE_BaseError as exc:
raise DataLayerError(str(exc))
driver = OGR_Dr_GetName(ogr_driver).decode("UTF-8")
return driver
cdef get_feature_count(OGRLayerH ogr_layer, int force):
"""Get the feature count of a layer.
If GDAL returns an unknown count (-1), this iterates over every feature
to calculate the count.
Parameters
----------
ogr_layer : pointer to open OGR layer
force : bool
True if the feature count should be computed even if it is expensive
Returns
-------
int
count of features
"""
cdef OGRFeatureH ogr_feature = NULL
cdef int feature_count = OGR_L_GetFeatureCount(ogr_layer, force)
# if GDAL refuses to give us the feature count, we have to loop over all
# features ourselves and get the count. This can happen for some drivers
# (e.g., OSM) or if a where clause is invalid but not rejected as error
if force and feature_count == -1:
# make sure layer is read from beginning
OGR_L_ResetReading(ogr_layer)
feature_count = 0
while True:
try:
ogr_feature = check_pointer(OGR_L_GetNextFeature(ogr_layer))
feature_count +=1
except NullPointerError:
# No more rows available, so stop reading
break
# driver may raise other errors, e.g., for OSM if node ids are not
# increasing, the default config option OSM_USE_CUSTOM_INDEXING=YES
# causes errors iterating over features
except CPLE_BaseError as exc:
# if an invalid where clause is used for a GPKG file, it is not
# caught as an error until attempting to iterate over features;
# catch it here
if "failed to prepare SQL" in str(exc):
raise ValueError(f"Invalid SQL query: {str(exc)}") from None
raise DataLayerError(f"Could not iterate over features: {str(exc)}") from None
finally:
if ogr_feature != NULL:
OGR_F_Destroy(ogr_feature)
ogr_feature = NULL
return feature_count
cdef get_total_bounds(OGRLayerH ogr_layer, int force):
"""Get the total bounds of a layer.
Parameters
----------
ogr_layer : pointer to open OGR layer
force : bool
True if the total bounds should be computed even if it is expensive
Returns
-------
tuple of (xmin, ymin, xmax, ymax) or None
The total bounds of the layer, or None if they could not be determined.
"""
cdef OGREnvelope ogr_envelope
if OGR_L_GetExtent(ogr_layer, &ogr_envelope, force) == OGRERR_NONE:
bounds = (
ogr_envelope.MinX, ogr_envelope.MinY, ogr_envelope.MaxX, ogr_envelope.MaxY
)
else:
bounds = None
return bounds
cdef set_metadata(GDALMajorObjectH obj, object metadata):
"""Set metadata on a dataset or layer
Parameters
----------
obj : pointer to dataset or layer
metadata : dict, optional (default None)
keys and values must be strings
"""
cdef char **metadata_items = NULL
cdef int err = 0
metadata_items = dict_to_options(metadata)
if metadata_items != NULL:
# only default namepace is currently supported
err = GDALSetMetadata(obj, metadata_items, NULL)
CSLDestroy(metadata_items)
metadata_items = NULL
if err:
raise RuntimeError("Could not set metadata") from None
cdef get_metadata(GDALMajorObjectH obj):
"""Get metadata for a dataset or layer
Parameters
----------
obj : pointer to dataset or layer
Returns
-------
dict or None
metadata as key, value pairs
"""
# only default namespace is currently supported
cdef char **metadata = GDALGetMetadata(obj, NULL)
if metadata != NULL:
return dict(
metadata[i].decode('UTF-8').split('=', 1)
for i in range(CSLCount(metadata))
)
return None
cdef detect_encoding(OGRDataSourceH ogr_dataset, OGRLayerH ogr_layer):
"""Attempt to detect the encoding to use to read/write string values.
If the layer/dataset supports reading/writing data in UTF-8, returns UTF-8.
If UTF-8 is not supported and ESRI Shapefile, returns ISO-8859-1
Otherwise the system locale preferred encoding is returned.
Parameters
----------
ogr_dataset : pointer to open OGR dataset
ogr_layer : pointer to open OGR layer
Returns
-------
str or None
"""
if OGR_L_TestCapability(ogr_layer, OLCStringsAsUTF8):
# OGR_L_TestCapability returns True for OLCStringsAsUTF8 if GDAL hides encoding
# complexities for this layer/driver type. In this case all string attribute
# values have to be supplied in UTF-8 and values will be returned in UTF-8.
# The encoding used to read/write under the hood depends on the driver used.
# For layers/drivers where False is returned, the string values are written and
# read without recoding. Hence, it is up to you to supply the data in the
# appropriate encoding. More info:
# https://gdal.org/development/rfc/rfc23_ogr_unicode.html#oftstring-oftstringlist-fields
# NOTE: for shapefiles, this always returns False for the layer returned
# when executing SQL, even when it supports UTF-8 (patched below);
# this may be fixed by https://github.com/OSGeo/gdal/pull/9649 (GDAL >=3.9.0?)
return "UTF-8"
driver = get_driver(ogr_dataset)
if driver == "ESRI Shapefile":
# OGR_L_TestCapability returns True for OLCStringsAsUTF8 (above) for
# shapefiles when a .cpg file is present with a valid encoding, or GDAL
# auto-detects the encoding from the code page of the .dbf file, or
# SHAPE_ENCODING config option is set, or ENCODING layer creation option
# is specified (shapefiles only). Otherwise, we can only assume that
# shapefiles are in their default encoding of ISO-8859-1 (which may be
# incorrect and must be overridden by user-provided encoding)
# Always use the first layer to test capabilities until detection for
# SQL results from shapefiles are fixed (above)
# This block should only be used for unfixed versions of GDAL (<3.9.0?)
if OGR_L_TestCapability(GDALDatasetGetLayer(ogr_dataset, 0), OLCStringsAsUTF8):
return "UTF-8"
return "ISO-8859-1"
if driver == "OSM":
# always set OSM data to UTF-8
# per https://help.openstreetmap.org/questions/2172/what-encoding-does-openstreetmap-use
return "UTF-8"
if driver in ("XLSX", "ODS"):
# TestCapability for OLCStringsAsUTF8 for XLSX and ODS was False for new files
# being created for GDAL < 3.8.5. Once these versions of GDAL are no longer
# supported, this can be removed.
return "UTF-8"
if driver == "GeoJSONSeq":
# In old gdal versions, OLCStringsAsUTF8 wasn't advertised yet.
return "UTF-8"
return locale.getpreferredencoding()
cdef get_fields(OGRLayerH ogr_layer, str encoding, use_arrow=False):
"""Get field names and types for layer.
Parameters
----------
ogr_layer : pointer to open OGR layer
encoding : str
encoding to use when reading field name
use_arrow : bool, default False
If using arrow, all types are supported, and we don't have to
raise warnings
Returns
-------
ndarray(n, 4)
array of index, ogr type, name, numpy type
"""
cdef int i
cdef int field_count
cdef OGRFeatureDefnH ogr_featuredef = NULL
cdef OGRFieldDefnH ogr_fielddef = NULL
cdef int field_subtype
cdef const char *key_c
try:
ogr_featuredef = check_pointer(OGR_L_GetLayerDefn(ogr_layer))
except NullPointerError:
raise DataLayerError("Could not get layer definition") from None
except CPLE_BaseError as exc:
raise DataLayerError(str(exc))
field_count = OGR_FD_GetFieldCount(ogr_featuredef)
fields = np.empty(shape=(field_count, 4), dtype=object)
fields_view = fields[:,:]
skipped_fields = False
for i in range(field_count):
try:
ogr_fielddef = check_pointer(OGR_FD_GetFieldDefn(ogr_featuredef, i))
except NullPointerError:
raise FieldError(f"Could not get field definition for field at index {i}") from None
except CPLE_BaseError as exc:
raise FieldError(str(exc))
field_name = get_string(OGR_Fld_GetNameRef(ogr_fielddef), encoding=encoding)
field_type = OGR_Fld_GetType(ogr_fielddef)
np_type = FIELD_TYPES[field_type]
if not np_type and not use_arrow:
skipped_fields = True
log.warning(
f"Skipping field {field_name}: unsupported OGR type: {field_type}")
continue
field_subtype = OGR_Fld_GetSubType(ogr_fielddef)
subtype = FIELD_SUBTYPES.get(field_subtype)
if subtype is not None:
# bool, int16, float32 dtypes
np_type = subtype
fields_view[i,0] = i
fields_view[i,1] = field_type
fields_view[i,2] = field_name
fields_view[i,3] = np_type
if skipped_fields:
# filter out skipped fields
mask = np.array([idx is not None for idx in fields[:, 0]])
fields = fields[mask]
return fields
cdef apply_where_filter(OGRLayerH ogr_layer, str where):
"""Applies where filter to layer.
WARNING: GDAL does not raise an error for GPKG when SQL query is invalid
but instead only logs to stderr.
Parameters
----------
ogr_layer : pointer to open OGR layer
where : str
See http://ogdi.sourceforge.net/prop/6.2.CapabilitiesMetadata.html
restricted_where for more information about valid expressions.
Raises
------
ValueError: if SQL query is not valid
"""
where_b = where.encode('utf-8')
where_c = where_b
err = OGR_L_SetAttributeFilter(ogr_layer, where_c)
# WARNING: GDAL does not raise this error for GPKG but instead only
# logs to stderr
if err != OGRERR_NONE:
try:
check_last_error()
except CPLE_BaseError as exc:
raise ValueError(str(exc))
raise ValueError(f"Invalid SQL query for layer '{OGR_L_GetName(ogr_layer)}': '{where}'")
cdef apply_bbox_filter(OGRLayerH ogr_layer, bbox):
"""Applies bounding box spatial filter to layer.
Parameters
----------
ogr_layer : pointer to open OGR layer
bbox : list or tuple of xmin, ymin, xmax, ymax
Raises
------
ValueError: if bbox is not a list or tuple or does not have proper number of
items
"""
if not (isinstance(bbox, (tuple, list)) and len(bbox) == 4):
raise ValueError(f"Invalid bbox: {bbox}")
xmin, ymin, xmax, ymax = bbox
OGR_L_SetSpatialFilterRect(ogr_layer, xmin, ymin, xmax, ymax)
cdef apply_geometry_filter(OGRLayerH ogr_layer, wkb):
"""Applies geometry spatial filter to layer.
Parameters
----------
ogr_layer : pointer to open OGR layer
wkb : WKB encoding of geometry
"""
cdef OGRGeometryH ogr_geometry = NULL
cdef unsigned char *wkb_buffer = wkb
err = OGR_G_CreateFromWkb(wkb_buffer, NULL, &ogr_geometry, len(wkb))
if err:
if ogr_geometry != NULL:
OGR_G_DestroyGeometry(ogr_geometry)
raise GeometryError("Could not create mask geometry") from None
OGR_L_SetSpatialFilter(ogr_layer, ogr_geometry)
OGR_G_DestroyGeometry(ogr_geometry)
cdef validate_feature_range(OGRLayerH ogr_layer, int skip_features=0, int max_features=0):
"""Limit skip_features and max_features to bounds available for dataset.
This is typically performed after applying where and spatial filters, which
reduce the available range of features.
Parameters
----------
ogr_layer : pointer to open OGR layer
skip_features : number of features to skip from beginning of available range
max_features : maximum number of features to read from available range
"""
feature_count = get_feature_count(ogr_layer, 1)
num_features = max_features
if feature_count == 0:
return 0, 0
if skip_features >= feature_count:
skip_features = feature_count
elif max_features == 0:
num_features = feature_count - skip_features
elif max_features > feature_count:
num_features = feature_count
return skip_features, num_features
@cython.boundscheck(False) # Deactivate bounds checking
@cython.wraparound(False) # Deactivate negative indexing.
cdef process_geometry(OGRFeatureH ogr_feature, int i, geom_view, uint8_t force_2d):
cdef OGRGeometryH ogr_geometry = NULL
cdef OGRwkbGeometryType ogr_geometry_type
cdef unsigned char *wkb = NULL
cdef int ret_length
ogr_geometry = OGR_F_GetGeometryRef(ogr_feature)
if ogr_geometry == NULL:
geom_view[i] = None
else:
try:
ogr_geometry_type = OGR_G_GetGeometryType(ogr_geometry)
# if geometry has M values, these need to be removed first
if (OGR_G_IsMeasured(ogr_geometry)):
OGR_G_SetMeasured(ogr_geometry, 0)
if force_2d and OGR_G_Is3D(ogr_geometry):
OGR_G_Set3D(ogr_geometry, 0)
# if non-linear (e.g., curve), force to linear type
if OGR_GT_IsNonLinear(ogr_geometry_type):
ogr_geometry = OGR_G_GetLinearGeometry(ogr_geometry, 0, NULL)
ret_length = OGR_G_WkbSize(ogr_geometry)
wkb = <unsigned char*>malloc(sizeof(unsigned char)*ret_length)
OGR_G_ExportToWkb(ogr_geometry, 1, wkb)
geom_view[i] = wkb[:ret_length]
finally:
free(wkb)
@cython.boundscheck(False) # Deactivate bounds checking
@cython.wraparound(False) # Deactivate negative indexing.
cdef process_fields(
OGRFeatureH ogr_feature,
int i,
int n_fields,
object field_data,
object field_data_view,
object field_indexes,
object field_ogr_types,
encoding,
bint datetime_as_string
):
cdef int j
cdef int success
cdef int field_index
cdef int ret_length
cdef GByte *bin_value
cdef int year = 0
cdef int month = 0
cdef int day = 0
cdef int hour = 0
cdef int minute = 0
cdef float fsecond = 0.0
cdef int timezone = 0
for j in range(n_fields):
field_index = field_indexes[j]
field_type = field_ogr_types[j]
data = field_data_view[j]
isnull = OGR_F_IsFieldSetAndNotNull(ogr_feature, field_index) == 0
if isnull:
if field_type in (OFTInteger, OFTInteger64, OFTReal):
# if a boolean or integer type, have to cast to float to hold
# NaN values
if data.dtype.kind in ('b', 'i', 'u'):
field_data[j] = field_data[j].astype(np.float64)
field_data_view[j] = field_data[j][:]
field_data_view[j][i] = np.nan
else:
data[i] = np.nan
elif field_type in ( OFTDate, OFTDateTime) and not datetime_as_string:
data[i] = np.datetime64('NaT')
else:
data[i] = None
continue
if field_type == OFTInteger:
data[i] = OGR_F_GetFieldAsInteger(ogr_feature, field_index)
elif field_type == OFTInteger64:
data[i] = OGR_F_GetFieldAsInteger64(ogr_feature, field_index)
elif field_type == OFTReal:
data[i] = OGR_F_GetFieldAsDouble(ogr_feature, field_index)
elif field_type == OFTString:
value = get_string(OGR_F_GetFieldAsString(ogr_feature, field_index), encoding=encoding)
data[i] = value
elif field_type == OFTBinary:
bin_value = OGR_F_GetFieldAsBinary(ogr_feature, field_index, &ret_length)
data[i] = bin_value[:ret_length]
elif field_type == OFTDateTime or field_type == OFTDate:
if datetime_as_string:
# defer datetime parsing to user/ pandas layer
# Update to OGR_F_GetFieldAsISO8601DateTime when GDAL 3.7+ only
data[i] = get_string(OGR_F_GetFieldAsString(ogr_feature, field_index), encoding=encoding)
else:
success = OGR_F_GetFieldAsDateTimeEx(
ogr_feature, field_index, &year, &month, &day, &hour, &minute, &fsecond, &timezone)
ms, ss = math.modf(fsecond)
second = int(ss)
# fsecond has millisecond accuracy
microsecond = round(ms * 1000) * 1000
if not success:
data[i] = np.datetime64('NaT')
elif field_type == OFTDate:
data[i] = datetime.date(year, month, day).isoformat()
elif field_type == OFTDateTime:
data[i] = datetime.datetime(year, month, day, hour, minute, second, microsecond).isoformat()
@cython.boundscheck(False) # Deactivate bounds checking
@cython.wraparound(False) # Deactivate negative indexing.
cdef get_features(
OGRLayerH ogr_layer,
object[:,:] fields,
encoding,
uint8_t read_geometry,
uint8_t force_2d,
int skip_features,
int num_features,
uint8_t return_fids,
bint datetime_as_string
):
cdef OGRFeatureH ogr_feature = NULL
cdef int n_fields
cdef int i
cdef int field_index
# make sure layer is read from beginning
OGR_L_ResetReading(ogr_layer)
if skip_features > 0:
OGR_L_SetNextByIndex(ogr_layer, skip_features)
if return_fids:
fid_data = np.empty(shape=(num_features), dtype=np.int64)
fid_view = fid_data[:]
else:
fid_data = None
if read_geometry:
geometries = np.empty(shape=(num_features, ), dtype='object')
geom_view = geometries[:]
else:
geometries = None
n_fields = fields.shape[0]
field_indexes = fields[:,0]
field_ogr_types = fields[:,1]
field_data = [
np.empty(shape=(num_features, ),
dtype = ("object" if datetime_as_string and
fields[field_index,3].startswith("datetime") else fields[field_index,3])
) for field_index in range(n_fields)
]
field_data_view = [field_data[field_index][:] for field_index in range(n_fields)]
if num_features == 0:
return fid_data, geometries, field_data
i = 0
while True:
try:
if num_features > 0 and i == num_features:
break
try:
ogr_feature = check_pointer(OGR_L_GetNextFeature(ogr_layer))
except NullPointerError:
# No more rows available, so stop reading
break
except CPLE_BaseError as exc:
raise FeatureError(str(exc))
if i >= num_features:
raise FeatureError(
"GDAL returned more records than expected based on the count of "
"records that may meet your combination of filters against this "
"dataset. Please open an issue on Github "
"(https://github.com/geopandas/pyogrio/issues) to report encountering "
"this error."
) from None