pyogrio 0.12.0__cp314-cp314t-macosx_12_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. pyogrio/.dylibs/libgdal.37.3.11.4.dylib +0 -0
  2. pyogrio/__init__.py +57 -0
  3. pyogrio/_compat.py +54 -0
  4. pyogrio/_env.py +59 -0
  5. pyogrio/_err.cpython-314t-darwin.so +0 -0
  6. pyogrio/_geometry.cpython-314t-darwin.so +0 -0
  7. pyogrio/_io.cpython-314t-darwin.so +0 -0
  8. pyogrio/_ogr.cpython-314t-darwin.so +0 -0
  9. pyogrio/_version.py +21 -0
  10. pyogrio/_vsi.cpython-314t-darwin.so +0 -0
  11. pyogrio/core.py +387 -0
  12. pyogrio/errors.py +25 -0
  13. pyogrio/gdal_data/GDAL-targets-release.cmake +19 -0
  14. pyogrio/gdal_data/GDAL-targets.cmake +106 -0
  15. pyogrio/gdal_data/GDALConfig.cmake +24 -0
  16. pyogrio/gdal_data/GDALConfigVersion.cmake +65 -0
  17. pyogrio/gdal_data/GDALLogoBW.svg +138 -0
  18. pyogrio/gdal_data/GDALLogoColor.svg +126 -0
  19. pyogrio/gdal_data/GDALLogoGS.svg +126 -0
  20. pyogrio/gdal_data/LICENSE.TXT +467 -0
  21. pyogrio/gdal_data/MM_m_idofic.csv +321 -0
  22. pyogrio/gdal_data/copyright +467 -0
  23. pyogrio/gdal_data/cubewerx_extra.wkt +48 -0
  24. pyogrio/gdal_data/default.rsc +0 -0
  25. pyogrio/gdal_data/ecw_cs.wkt +1453 -0
  26. pyogrio/gdal_data/eedaconf.json +23 -0
  27. pyogrio/gdal_data/epsg.wkt +1 -0
  28. pyogrio/gdal_data/esri_StatePlane_extra.wkt +631 -0
  29. pyogrio/gdal_data/gdal_algorithm.schema.json +220 -0
  30. pyogrio/gdal_data/gdalg.schema.json +36 -0
  31. pyogrio/gdal_data/gdalicon.png +0 -0
  32. pyogrio/gdal_data/gdalinfo_output.schema.json +390 -0
  33. pyogrio/gdal_data/gdalmdiminfo_output.schema.json +326 -0
  34. pyogrio/gdal_data/gdaltileindex.xsd +253 -0
  35. pyogrio/gdal_data/gdalvrt.xsd +927 -0
  36. pyogrio/gdal_data/gfs.xsd +246 -0
  37. pyogrio/gdal_data/gml_registry.xml +117 -0
  38. pyogrio/gdal_data/gml_registry.xsd +66 -0
  39. pyogrio/gdal_data/grib2_center.csv +251 -0
  40. pyogrio/gdal_data/grib2_process.csv +102 -0
  41. pyogrio/gdal_data/grib2_subcenter.csv +63 -0
  42. pyogrio/gdal_data/grib2_table_4_2_0_0.csv +261 -0
  43. pyogrio/gdal_data/grib2_table_4_2_0_1.csv +261 -0
  44. pyogrio/gdal_data/grib2_table_4_2_0_13.csv +261 -0
  45. pyogrio/gdal_data/grib2_table_4_2_0_14.csv +261 -0
  46. pyogrio/gdal_data/grib2_table_4_2_0_15.csv +261 -0
  47. pyogrio/gdal_data/grib2_table_4_2_0_16.csv +261 -0
  48. pyogrio/gdal_data/grib2_table_4_2_0_17.csv +11 -0
  49. pyogrio/gdal_data/grib2_table_4_2_0_18.csv +261 -0
  50. pyogrio/gdal_data/grib2_table_4_2_0_19.csv +261 -0
  51. pyogrio/gdal_data/grib2_table_4_2_0_190.csv +261 -0
  52. pyogrio/gdal_data/grib2_table_4_2_0_191.csv +261 -0
  53. pyogrio/gdal_data/grib2_table_4_2_0_2.csv +261 -0
  54. pyogrio/gdal_data/grib2_table_4_2_0_20.csv +261 -0
  55. pyogrio/gdal_data/grib2_table_4_2_0_21.csv +261 -0
  56. pyogrio/gdal_data/grib2_table_4_2_0_3.csv +261 -0
  57. pyogrio/gdal_data/grib2_table_4_2_0_4.csv +261 -0
  58. pyogrio/gdal_data/grib2_table_4_2_0_5.csv +261 -0
  59. pyogrio/gdal_data/grib2_table_4_2_0_6.csv +261 -0
  60. pyogrio/gdal_data/grib2_table_4_2_0_7.csv +261 -0
  61. pyogrio/gdal_data/grib2_table_4_2_10_0.csv +261 -0
  62. pyogrio/gdal_data/grib2_table_4_2_10_1.csv +261 -0
  63. pyogrio/gdal_data/grib2_table_4_2_10_191.csv +261 -0
  64. pyogrio/gdal_data/grib2_table_4_2_10_2.csv +261 -0
  65. pyogrio/gdal_data/grib2_table_4_2_10_3.csv +261 -0
  66. pyogrio/gdal_data/grib2_table_4_2_10_4.csv +261 -0
  67. pyogrio/gdal_data/grib2_table_4_2_1_0.csv +261 -0
  68. pyogrio/gdal_data/grib2_table_4_2_1_1.csv +261 -0
  69. pyogrio/gdal_data/grib2_table_4_2_1_2.csv +261 -0
  70. pyogrio/gdal_data/grib2_table_4_2_20_0.csv +261 -0
  71. pyogrio/gdal_data/grib2_table_4_2_20_1.csv +261 -0
  72. pyogrio/gdal_data/grib2_table_4_2_20_2.csv +261 -0
  73. pyogrio/gdal_data/grib2_table_4_2_2_0.csv +261 -0
  74. pyogrio/gdal_data/grib2_table_4_2_2_3.csv +261 -0
  75. pyogrio/gdal_data/grib2_table_4_2_2_4.csv +261 -0
  76. pyogrio/gdal_data/grib2_table_4_2_2_5.csv +261 -0
  77. pyogrio/gdal_data/grib2_table_4_2_2_6.csv +261 -0
  78. pyogrio/gdal_data/grib2_table_4_2_3_0.csv +261 -0
  79. pyogrio/gdal_data/grib2_table_4_2_3_1.csv +261 -0
  80. pyogrio/gdal_data/grib2_table_4_2_3_2.csv +28 -0
  81. pyogrio/gdal_data/grib2_table_4_2_3_3.csv +8 -0
  82. pyogrio/gdal_data/grib2_table_4_2_3_4.csv +14 -0
  83. pyogrio/gdal_data/grib2_table_4_2_3_5.csv +11 -0
  84. pyogrio/gdal_data/grib2_table_4_2_3_6.csv +11 -0
  85. pyogrio/gdal_data/grib2_table_4_2_4_0.csv +261 -0
  86. pyogrio/gdal_data/grib2_table_4_2_4_1.csv +261 -0
  87. pyogrio/gdal_data/grib2_table_4_2_4_10.csv +261 -0
  88. pyogrio/gdal_data/grib2_table_4_2_4_2.csv +261 -0
  89. pyogrio/gdal_data/grib2_table_4_2_4_3.csv +261 -0
  90. pyogrio/gdal_data/grib2_table_4_2_4_4.csv +261 -0
  91. pyogrio/gdal_data/grib2_table_4_2_4_5.csv +261 -0
  92. pyogrio/gdal_data/grib2_table_4_2_4_6.csv +261 -0
  93. pyogrio/gdal_data/grib2_table_4_2_4_7.csv +261 -0
  94. pyogrio/gdal_data/grib2_table_4_2_4_8.csv +261 -0
  95. pyogrio/gdal_data/grib2_table_4_2_4_9.csv +261 -0
  96. pyogrio/gdal_data/grib2_table_4_2_local_Canada.csv +5 -0
  97. pyogrio/gdal_data/grib2_table_4_2_local_HPC.csv +2 -0
  98. pyogrio/gdal_data/grib2_table_4_2_local_MRMS.csv +175 -0
  99. pyogrio/gdal_data/grib2_table_4_2_local_NCEP.csv +401 -0
  100. pyogrio/gdal_data/grib2_table_4_2_local_NDFD.csv +38 -0
  101. pyogrio/gdal_data/grib2_table_4_2_local_index.csv +7 -0
  102. pyogrio/gdal_data/grib2_table_4_5.csv +261 -0
  103. pyogrio/gdal_data/grib2_table_versions.csv +3 -0
  104. pyogrio/gdal_data/gt_datum.csv +229 -0
  105. pyogrio/gdal_data/gt_ellips.csv +24 -0
  106. pyogrio/gdal_data/header.dxf +1124 -0
  107. pyogrio/gdal_data/inspire_cp_BasicPropertyUnit.gfs +57 -0
  108. pyogrio/gdal_data/inspire_cp_CadastralBoundary.gfs +60 -0
  109. pyogrio/gdal_data/inspire_cp_CadastralParcel.gfs +81 -0
  110. pyogrio/gdal_data/inspire_cp_CadastralZoning.gfs +161 -0
  111. pyogrio/gdal_data/jpfgdgml_AdmArea.gfs +59 -0
  112. pyogrio/gdal_data/jpfgdgml_AdmBdry.gfs +49 -0
  113. pyogrio/gdal_data/jpfgdgml_AdmPt.gfs +59 -0
  114. pyogrio/gdal_data/jpfgdgml_BldA.gfs +54 -0
  115. pyogrio/gdal_data/jpfgdgml_BldL.gfs +54 -0
  116. pyogrio/gdal_data/jpfgdgml_Cntr.gfs +54 -0
  117. pyogrio/gdal_data/jpfgdgml_CommBdry.gfs +49 -0
  118. pyogrio/gdal_data/jpfgdgml_CommPt.gfs +59 -0
  119. pyogrio/gdal_data/jpfgdgml_Cstline.gfs +54 -0
  120. pyogrio/gdal_data/jpfgdgml_ElevPt.gfs +54 -0
  121. pyogrio/gdal_data/jpfgdgml_GCP.gfs +94 -0
  122. pyogrio/gdal_data/jpfgdgml_LeveeEdge.gfs +49 -0
  123. pyogrio/gdal_data/jpfgdgml_RailCL.gfs +54 -0
  124. pyogrio/gdal_data/jpfgdgml_RdASL.gfs +44 -0
  125. pyogrio/gdal_data/jpfgdgml_RdArea.gfs +54 -0
  126. pyogrio/gdal_data/jpfgdgml_RdCompt.gfs +59 -0
  127. pyogrio/gdal_data/jpfgdgml_RdEdg.gfs +59 -0
  128. pyogrio/gdal_data/jpfgdgml_RdMgtBdry.gfs +49 -0
  129. pyogrio/gdal_data/jpfgdgml_RdSgmtA.gfs +59 -0
  130. pyogrio/gdal_data/jpfgdgml_RvrMgtBdry.gfs +49 -0
  131. pyogrio/gdal_data/jpfgdgml_SBAPt.gfs +49 -0
  132. pyogrio/gdal_data/jpfgdgml_SBArea.gfs +54 -0
  133. pyogrio/gdal_data/jpfgdgml_SBBdry.gfs +44 -0
  134. pyogrio/gdal_data/jpfgdgml_WA.gfs +54 -0
  135. pyogrio/gdal_data/jpfgdgml_WL.gfs +54 -0
  136. pyogrio/gdal_data/jpfgdgml_WStrA.gfs +54 -0
  137. pyogrio/gdal_data/jpfgdgml_WStrL.gfs +54 -0
  138. pyogrio/gdal_data/leaflet_template.html +102 -0
  139. pyogrio/gdal_data/nitf_spec.xml +3288 -0
  140. pyogrio/gdal_data/nitf_spec.xsd +171 -0
  141. pyogrio/gdal_data/ogr_fields_override.schema.json +125 -0
  142. pyogrio/gdal_data/ogrinfo_output.schema.json +528 -0
  143. pyogrio/gdal_data/ogrvrt.xsd +528 -0
  144. pyogrio/gdal_data/osmconf.ini +134 -0
  145. pyogrio/gdal_data/ozi_datum.csv +131 -0
  146. pyogrio/gdal_data/ozi_ellips.csv +35 -0
  147. pyogrio/gdal_data/pci_datum.txt +530 -0
  148. pyogrio/gdal_data/pci_ellips.txt +129 -0
  149. pyogrio/gdal_data/pdfcomposition.xsd +703 -0
  150. pyogrio/gdal_data/pds4_template.xml +65 -0
  151. pyogrio/gdal_data/plscenesconf.json +1985 -0
  152. pyogrio/gdal_data/ruian_vf_ob_v1.gfs +1455 -0
  153. pyogrio/gdal_data/ruian_vf_st_uvoh_v1.gfs +86 -0
  154. pyogrio/gdal_data/ruian_vf_st_v1.gfs +1489 -0
  155. pyogrio/gdal_data/ruian_vf_v1.gfs +2126 -0
  156. pyogrio/gdal_data/s57agencies.csv +249 -0
  157. pyogrio/gdal_data/s57attributes.csv +484 -0
  158. pyogrio/gdal_data/s57expectedinput.csv +1008 -0
  159. pyogrio/gdal_data/s57objectclasses.csv +287 -0
  160. pyogrio/gdal_data/seed_2d.dgn +0 -0
  161. pyogrio/gdal_data/seed_3d.dgn +0 -0
  162. pyogrio/gdal_data/stateplane.csv +259 -0
  163. pyogrio/gdal_data/template_tiles.mapml +28 -0
  164. pyogrio/gdal_data/tms_LINZAntarticaMapTileGrid.json +190 -0
  165. pyogrio/gdal_data/tms_MapML_APSTILE.json +268 -0
  166. pyogrio/gdal_data/tms_MapML_CBMTILE.json +346 -0
  167. pyogrio/gdal_data/tms_NZTM2000.json +243 -0
  168. pyogrio/gdal_data/trailer.dxf +434 -0
  169. pyogrio/gdal_data/usage +4 -0
  170. pyogrio/gdal_data/vcpkg-cmake-wrapper.cmake +23 -0
  171. pyogrio/gdal_data/vcpkg.spdx.json +291 -0
  172. pyogrio/gdal_data/vcpkg_abi_info.txt +45 -0
  173. pyogrio/gdal_data/vdv452.xml +349 -0
  174. pyogrio/gdal_data/vdv452.xsd +45 -0
  175. pyogrio/gdal_data/vicar.json +164 -0
  176. pyogrio/geopandas.py +978 -0
  177. pyogrio/proj_data/CH +22 -0
  178. pyogrio/proj_data/GL27 +23 -0
  179. pyogrio/proj_data/ITRF2000 +24 -0
  180. pyogrio/proj_data/ITRF2008 +94 -0
  181. pyogrio/proj_data/ITRF2014 +55 -0
  182. pyogrio/proj_data/ITRF2020 +91 -0
  183. pyogrio/proj_data/copyright +34 -0
  184. pyogrio/proj_data/deformation_model.schema.json +582 -0
  185. pyogrio/proj_data/nad.lst +142 -0
  186. pyogrio/proj_data/nad27 +810 -0
  187. pyogrio/proj_data/nad83 +745 -0
  188. pyogrio/proj_data/other.extra +53 -0
  189. pyogrio/proj_data/proj-config-version.cmake +44 -0
  190. pyogrio/proj_data/proj-config.cmake +79 -0
  191. pyogrio/proj_data/proj-targets-release.cmake +19 -0
  192. pyogrio/proj_data/proj-targets.cmake +107 -0
  193. pyogrio/proj_data/proj.db +0 -0
  194. pyogrio/proj_data/proj.ini +59 -0
  195. pyogrio/proj_data/proj4-targets-release.cmake +19 -0
  196. pyogrio/proj_data/proj4-targets.cmake +107 -0
  197. pyogrio/proj_data/projjson.schema.json +1174 -0
  198. pyogrio/proj_data/triangulation.schema.json +214 -0
  199. pyogrio/proj_data/usage +9 -0
  200. pyogrio/proj_data/vcpkg.spdx.json +203 -0
  201. pyogrio/proj_data/vcpkg_abi_info.txt +28 -0
  202. pyogrio/proj_data/world +214 -0
  203. pyogrio/raw.py +897 -0
  204. pyogrio/tests/__init__.py +0 -0
  205. pyogrio/tests/conftest.py +588 -0
  206. pyogrio/tests/fixtures/README.md +108 -0
  207. pyogrio/tests/fixtures/curve.gpkg +0 -0
  208. pyogrio/tests/fixtures/curvepolygon.gpkg +0 -0
  209. pyogrio/tests/fixtures/line_zm.gpkg +0 -0
  210. pyogrio/tests/fixtures/list_field_values_file.parquet +0 -0
  211. pyogrio/tests/fixtures/list_nested_struct_file.parquet +0 -0
  212. pyogrio/tests/fixtures/multisurface.gpkg +0 -0
  213. pyogrio/tests/fixtures/naturalearth_lowres/naturalearth_lowres.cpg +1 -0
  214. pyogrio/tests/fixtures/naturalearth_lowres/naturalearth_lowres.dbf +0 -0
  215. pyogrio/tests/fixtures/naturalearth_lowres/naturalearth_lowres.prj +1 -0
  216. pyogrio/tests/fixtures/naturalearth_lowres/naturalearth_lowres.shp +0 -0
  217. pyogrio/tests/fixtures/naturalearth_lowres/naturalearth_lowres.shx +0 -0
  218. pyogrio/tests/fixtures/sample.osm.pbf +0 -0
  219. pyogrio/tests/fixtures/test_gpkg_nulls.gpkg +0 -0
  220. pyogrio/tests/test_arrow.py +1160 -0
  221. pyogrio/tests/test_core.py +702 -0
  222. pyogrio/tests/test_geopandas_io.py +3218 -0
  223. pyogrio/tests/test_path.py +374 -0
  224. pyogrio/tests/test_raw_io.py +1473 -0
  225. pyogrio/tests/test_util.py +56 -0
  226. pyogrio/util.py +258 -0
  227. pyogrio-0.12.0.dist-info/METADATA +125 -0
  228. pyogrio-0.12.0.dist-info/RECORD +231 -0
  229. pyogrio-0.12.0.dist-info/WHEEL +6 -0
  230. pyogrio-0.12.0.dist-info/licenses/LICENSE +21 -0
  231. pyogrio-0.12.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1160 @@
1
+ import contextlib
2
+ import json
3
+ import math
4
+ import sys
5
+ from io import BytesIO
6
+ from packaging.version import Version
7
+ from zipfile import ZipFile
8
+
9
+ import numpy as np
10
+
11
+ import pyogrio
12
+ from pyogrio import (
13
+ __gdal_version__,
14
+ get_gdal_config_option,
15
+ list_layers,
16
+ read_dataframe,
17
+ read_info,
18
+ set_gdal_config_options,
19
+ vsi_listtree,
20
+ )
21
+ from pyogrio.errors import DataLayerError, DataSourceError, FieldError
22
+ from pyogrio.raw import open_arrow, read_arrow, write, write_arrow
23
+ from pyogrio.tests.conftest import (
24
+ ALL_EXTS,
25
+ DRIVER_EXT,
26
+ DRIVERS,
27
+ requires_arrow_write_api,
28
+ requires_pyarrow_api,
29
+ )
30
+
31
+ import pytest
32
+
33
+ try:
34
+ import pandas as pd
35
+ import pyarrow
36
+
37
+ from geopandas.testing import assert_geodataframe_equal
38
+ from pandas.testing import assert_frame_equal, assert_index_equal
39
+ except ImportError:
40
+ pass
41
+
42
+ # skip all tests in this file if Arrow API or GeoPandas are unavailable
43
+ pytestmark = requires_pyarrow_api
44
+ pytest.importorskip("geopandas")
45
+ pa = pytest.importorskip("pyarrow")
46
+
47
+
48
+ def test_read_arrow(naturalearth_lowres_all_ext):
49
+ result = read_dataframe(naturalearth_lowres_all_ext, use_arrow=True)
50
+ expected = read_dataframe(naturalearth_lowres_all_ext, use_arrow=False)
51
+
52
+ if naturalearth_lowres_all_ext.suffix.startswith(".geojson"):
53
+ check_less_precise = True
54
+ else:
55
+ check_less_precise = False
56
+ assert_geodataframe_equal(result, expected, check_less_precise=check_less_precise)
57
+
58
+
59
+ def test_read_arrow_unspecified_layer_warning(data_dir):
60
+ """Reading a multi-layer file without specifying a layer gives a warning."""
61
+ with pytest.warns(UserWarning, match="More than one layer found "):
62
+ read_arrow(data_dir / "sample.osm.pbf")
63
+
64
+
65
+ @pytest.mark.parametrize("skip_features, expected", [(10, 167), (200, 0)])
66
+ def test_read_arrow_skip_features(naturalearth_lowres, skip_features, expected):
67
+ table = read_arrow(naturalearth_lowres, skip_features=skip_features)[1]
68
+ assert len(table) == expected
69
+
70
+
71
+ def test_read_arrow_negative_skip_features(naturalearth_lowres):
72
+ with pytest.raises(ValueError, match="'skip_features' must be >= 0"):
73
+ read_arrow(naturalearth_lowres, skip_features=-1)
74
+
75
+
76
+ @pytest.mark.parametrize(
77
+ "max_features, expected", [(0, 0), (10, 10), (200, 177), (100000, 177)]
78
+ )
79
+ def test_read_arrow_max_features(naturalearth_lowres, max_features, expected):
80
+ table = read_arrow(naturalearth_lowres, max_features=max_features)[1]
81
+ assert len(table) == expected
82
+
83
+
84
+ def test_read_arrow_negative_max_features(naturalearth_lowres):
85
+ with pytest.raises(ValueError, match="'max_features' must be >= 0"):
86
+ read_arrow(naturalearth_lowres, max_features=-1)
87
+
88
+
89
+ @pytest.mark.parametrize(
90
+ "skip_features, max_features, expected",
91
+ [
92
+ (0, 0, 0),
93
+ (10, 0, 0),
94
+ (200, 0, 0),
95
+ (1, 200, 176),
96
+ (176, 10, 1),
97
+ (100, 100, 77),
98
+ (100, 100000, 77),
99
+ ],
100
+ )
101
+ def test_read_arrow_skip_features_max_features(
102
+ naturalearth_lowres, skip_features, max_features, expected
103
+ ):
104
+ table = read_arrow(
105
+ naturalearth_lowres, skip_features=skip_features, max_features=max_features
106
+ )[1]
107
+ assert len(table) == expected
108
+
109
+
110
+ def test_read_arrow_fid(naturalearth_lowres_all_ext):
111
+ kwargs = {"use_arrow": True, "where": "fid >= 2 AND fid <= 3"}
112
+
113
+ df = read_dataframe(naturalearth_lowres_all_ext, fid_as_index=False, **kwargs)
114
+ assert_index_equal(df.index, pd.RangeIndex(0, 2))
115
+
116
+ df = read_dataframe(naturalearth_lowres_all_ext, fid_as_index=True, **kwargs)
117
+ assert_index_equal(df.index, pd.Index([2, 3], name="fid"))
118
+
119
+
120
+ def test_read_arrow_columns(naturalearth_lowres):
121
+ result = read_dataframe(naturalearth_lowres, use_arrow=True, columns=["continent"])
122
+ assert result.columns.tolist() == ["continent", "geometry"]
123
+
124
+
125
+ def test_read_arrow_ignore_geometry(naturalearth_lowres):
126
+ result = read_dataframe(naturalearth_lowres, use_arrow=True, read_geometry=False)
127
+ assert type(result) is pd.DataFrame
128
+
129
+ expected = read_dataframe(naturalearth_lowres, use_arrow=True).drop(
130
+ columns=["geometry"]
131
+ )
132
+ assert_frame_equal(result, expected)
133
+
134
+
135
+ def test_read_arrow_to_pandas_kwargs(no_geometry_file):
136
+ # with arrow, list types are supported
137
+ arrow_to_pandas_kwargs = {"strings_to_categorical": True}
138
+ df = read_dataframe(
139
+ no_geometry_file,
140
+ read_geometry=False,
141
+ use_arrow=True,
142
+ arrow_to_pandas_kwargs=arrow_to_pandas_kwargs,
143
+ )
144
+ assert df.col.dtype.name == "category"
145
+ assert np.array_equal(df.col.values.categories, ["a", "b", "c"])
146
+
147
+
148
+ def test_read_arrow_raw(naturalearth_lowres):
149
+ meta, table = read_arrow(naturalearth_lowres)
150
+ assert isinstance(meta, dict)
151
+ assert isinstance(table, pyarrow.Table)
152
+
153
+
154
+ def test_read_arrow_vsi(naturalearth_lowres_vsi):
155
+ table = read_arrow(naturalearth_lowres_vsi[1])[1]
156
+ assert len(table) == 177
157
+
158
+ # Check temp file was cleaned up. Filter to files created by pyogrio, as GDAL keeps
159
+ # cache files in /vsimem/.
160
+ assert vsi_listtree("/vsimem/", pattern="pyogrio_*") == []
161
+
162
+
163
+ def test_read_arrow_bytes(geojson_bytes):
164
+ meta, table = read_arrow(geojson_bytes)
165
+
166
+ assert meta["fields"].shape == (5,)
167
+ assert len(table) == 3
168
+
169
+ # Check temp file was cleaned up. Filter, as gdal keeps cache files in /vsimem/.
170
+ assert vsi_listtree("/vsimem/", pattern="pyogrio_*") == []
171
+
172
+
173
+ def test_read_arrow_nonseekable_bytes(nonseekable_bytes):
174
+ meta, table = read_arrow(nonseekable_bytes)
175
+ assert meta["fields"].shape == (0,)
176
+ assert len(table) == 1
177
+
178
+ # Check temp file was cleaned up. Filter, as gdal keeps cache files in /vsimem/.
179
+ assert vsi_listtree("/vsimem/", pattern="pyogrio_*") == []
180
+
181
+
182
+ def test_read_arrow_filelike(geojson_filelike):
183
+ meta, table = read_arrow(geojson_filelike)
184
+
185
+ assert meta["fields"].shape == (5,)
186
+ assert len(table) == 3
187
+
188
+ # Check temp file was cleaned up. Filter, as gdal keeps cache files in /vsimem/.
189
+ assert vsi_listtree("/vsimem/", pattern="pyogrio_*") == []
190
+
191
+
192
+ def test_open_arrow_pyarrow(naturalearth_lowres):
193
+ with open_arrow(naturalearth_lowres, use_pyarrow=True) as (meta, reader):
194
+ assert isinstance(meta, dict)
195
+ assert isinstance(reader, pyarrow.RecordBatchReader)
196
+ assert isinstance(reader.read_all(), pyarrow.Table)
197
+
198
+
199
+ def test_open_arrow_batch_size(naturalearth_lowres):
200
+ _, table = read_arrow(naturalearth_lowres)
201
+ batch_size = math.ceil(len(table) / 2)
202
+
203
+ with open_arrow(naturalearth_lowres, batch_size=batch_size, use_pyarrow=True) as (
204
+ meta,
205
+ reader,
206
+ ):
207
+ assert isinstance(meta, dict)
208
+ assert isinstance(reader, pyarrow.RecordBatchReader)
209
+ count = 0
210
+ tables = []
211
+ for table in reader:
212
+ tables.append(table)
213
+ count += 1
214
+
215
+ assert count == 2, "Should be two batches given the batch_size parameter"
216
+ assert len(tables[0]) == batch_size, "First table should match the batch size"
217
+
218
+
219
+ @pytest.mark.skipif(
220
+ __gdal_version__ >= (3, 8, 0),
221
+ reason="skip_features supported by Arrow stream API for GDAL>=3.8.0",
222
+ )
223
+ @pytest.mark.parametrize("skip_features", [10, 200])
224
+ def test_open_arrow_skip_features_unsupported(naturalearth_lowres, skip_features):
225
+ """skip_features are not supported for the Arrow stream interface for
226
+ GDAL < 3.8.0"""
227
+ with pytest.raises(
228
+ ValueError,
229
+ match="specifying 'skip_features' is not supported for Arrow for GDAL<3.8.0",
230
+ ):
231
+ with open_arrow(naturalearth_lowres, skip_features=skip_features) as (
232
+ meta,
233
+ reader,
234
+ ):
235
+ pass
236
+
237
+
238
+ @pytest.mark.parametrize("max_features", [10, 200])
239
+ def test_open_arrow_max_features_unsupported(naturalearth_lowres, max_features):
240
+ """max_features are not supported for the Arrow stream interface"""
241
+ with pytest.raises(
242
+ ValueError,
243
+ match="specifying 'max_features' is not supported for Arrow",
244
+ ):
245
+ with open_arrow(naturalearth_lowres, max_features=max_features) as (
246
+ meta,
247
+ reader,
248
+ ):
249
+ pass
250
+
251
+
252
+ @pytest.mark.skipif(
253
+ __gdal_version__ < (3, 8, 0),
254
+ reason="returns geoarrow metadata only for GDAL>=3.8.0",
255
+ )
256
+ def test_read_arrow_geoarrow_metadata(naturalearth_lowres):
257
+ _meta, table = read_arrow(naturalearth_lowres)
258
+ field = table.schema.field("wkb_geometry")
259
+ assert field.metadata[b"ARROW:extension:name"] == b"geoarrow.wkb"
260
+ parsed_meta = json.loads(field.metadata[b"ARROW:extension:metadata"])
261
+ assert parsed_meta["crs"]["id"]["authority"] == "EPSG"
262
+ assert parsed_meta["crs"]["id"]["code"] == 4326
263
+
264
+
265
+ def test_open_arrow_capsule_protocol(naturalearth_lowres):
266
+ pytest.importorskip("pyarrow", minversion="14")
267
+
268
+ with open_arrow(naturalearth_lowres) as (meta, reader):
269
+ assert isinstance(meta, dict)
270
+ assert isinstance(reader, pyogrio._io._ArrowStream)
271
+
272
+ result = pyarrow.table(reader)
273
+
274
+ _, expected = read_arrow(naturalearth_lowres)
275
+ assert result.equals(expected)
276
+
277
+
278
+ def test_open_arrow_capsule_protocol_without_pyarrow(naturalearth_lowres):
279
+ pyarrow = pytest.importorskip("pyarrow", minversion="14")
280
+
281
+ # Make PyArrow temporarily unavailable (importing will fail)
282
+ sys.modules["pyarrow"] = None
283
+ try:
284
+ with open_arrow(naturalearth_lowres) as (meta, reader):
285
+ assert isinstance(meta, dict)
286
+ assert isinstance(reader, pyogrio._io._ArrowStream)
287
+ result = pyarrow.table(reader)
288
+ finally:
289
+ sys.modules["pyarrow"] = pyarrow
290
+
291
+ _, expected = read_arrow(naturalearth_lowres)
292
+ assert result.equals(expected)
293
+
294
+
295
+ @pytest.mark.skipif(
296
+ __gdal_version__ < (3, 8, 3), reason="Arrow bool value bug fixed in GDAL >= 3.8.3"
297
+ )
298
+ @pytest.mark.parametrize("ext", ALL_EXTS)
299
+ def test_arrow_bool_roundtrip(tmp_path, ext):
300
+ filename = tmp_path / f"test{ext}"
301
+
302
+ # Point(0, 0)
303
+ geometry = np.array(
304
+ [bytes.fromhex("010100000000000000000000000000000000000000")] * 5, dtype=object
305
+ )
306
+ bool_col = np.array([True, False, True, False, True])
307
+ field_data = [bool_col]
308
+ fields = ["bool_col"]
309
+
310
+ kwargs = {}
311
+
312
+ if ext == ".fgb":
313
+ # For .fgb, spatial_index=False to avoid the rows being reordered
314
+ kwargs["spatial_index"] = False
315
+
316
+ write(
317
+ filename,
318
+ geometry,
319
+ field_data,
320
+ fields,
321
+ geometry_type="Point",
322
+ crs="EPSG:4326",
323
+ **kwargs,
324
+ )
325
+
326
+ write(
327
+ filename, geometry, field_data, fields, geometry_type="Point", crs="EPSG:4326"
328
+ )
329
+ table = read_arrow(filename)[1]
330
+
331
+ assert np.array_equal(table["bool_col"].to_numpy(), bool_col)
332
+
333
+
334
+ @pytest.mark.skipif(
335
+ __gdal_version__ >= (3, 8, 3), reason="Arrow bool value bug fixed in GDAL >= 3.8.3"
336
+ )
337
+ @pytest.mark.parametrize("ext", ALL_EXTS)
338
+ def test_arrow_bool_exception(tmp_path, ext):
339
+ filename = tmp_path / f"test{ext}"
340
+
341
+ # Point(0, 0)
342
+ geometry = np.array(
343
+ [bytes.fromhex("010100000000000000000000000000000000000000")] * 5, dtype=object
344
+ )
345
+ bool_col = np.array([True, False, True, False, True])
346
+ field_data = [bool_col]
347
+ fields = ["bool_col"]
348
+
349
+ write(
350
+ filename, geometry, field_data, fields, geometry_type="Point", crs="EPSG:4326"
351
+ )
352
+
353
+ if ext in {".fgb", ".gpkg"}:
354
+ # only raise exception for GPKG / FGB
355
+ with pytest.raises(
356
+ RuntimeError,
357
+ match="GDAL < 3.8.3 does not correctly read boolean data values using "
358
+ "the Arrow API",
359
+ ):
360
+ with open_arrow(filename):
361
+ pass
362
+
363
+ # do not raise exception if no bool columns are read
364
+ with open_arrow(filename, columns=[]):
365
+ pass
366
+
367
+ else:
368
+ with open_arrow(filename):
369
+ pass
370
+
371
+
372
+ # Point(0, 0)
373
+ points = np.array(
374
+ [bytes.fromhex("010100000000000000000000000000000000000000")] * 3,
375
+ dtype=object,
376
+ )
377
+
378
+
379
+ @requires_arrow_write_api
380
+ def test_write_shp(tmp_path, naturalearth_lowres):
381
+ meta, table = read_arrow(naturalearth_lowres)
382
+
383
+ filename = tmp_path / "test.shp"
384
+ write_arrow(
385
+ table,
386
+ filename,
387
+ crs=meta["crs"],
388
+ encoding=meta["encoding"],
389
+ geometry_type=meta["geometry_type"],
390
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
391
+ )
392
+
393
+ assert filename.exists()
394
+ for ext in (".dbf", ".prj"):
395
+ assert filename.with_suffix(ext).exists()
396
+
397
+
398
+ @pytest.mark.filterwarnings("ignore:A geometry of type POLYGON is inserted")
399
+ @requires_arrow_write_api
400
+ def test_write_gpkg(tmp_path, naturalearth_lowres):
401
+ meta, table = read_arrow(naturalearth_lowres)
402
+
403
+ filename = tmp_path / "test.gpkg"
404
+ write_arrow(
405
+ table,
406
+ filename,
407
+ driver="GPKG",
408
+ crs=meta["crs"],
409
+ geometry_type="MultiPolygon",
410
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
411
+ )
412
+
413
+ assert filename.exists()
414
+
415
+
416
+ @pytest.mark.filterwarnings("ignore:A geometry of type POLYGON is inserted")
417
+ @requires_arrow_write_api
418
+ def test_write_gpkg_multiple_layers(tmp_path, naturalearth_lowres):
419
+ meta, table = read_arrow(naturalearth_lowres)
420
+ meta["geometry_type"] = "MultiPolygon"
421
+
422
+ filename = tmp_path / "test.gpkg"
423
+ write_arrow(
424
+ table,
425
+ filename,
426
+ driver="GPKG",
427
+ layer="first",
428
+ crs=meta["crs"],
429
+ geometry_type="MultiPolygon",
430
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
431
+ )
432
+
433
+ assert filename.exists()
434
+
435
+ assert np.array_equal(list_layers(filename), [["first", "MultiPolygon"]])
436
+
437
+ write_arrow(
438
+ table,
439
+ filename,
440
+ driver="GPKG",
441
+ layer="second",
442
+ crs=meta["crs"],
443
+ geometry_type="MultiPolygon",
444
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
445
+ )
446
+
447
+ assert np.array_equal(
448
+ list_layers(filename), [["first", "MultiPolygon"], ["second", "MultiPolygon"]]
449
+ )
450
+
451
+
452
+ @requires_arrow_write_api
453
+ def test_write_geojson(tmp_path, naturalearth_lowres):
454
+ meta, table = read_arrow(naturalearth_lowres)
455
+ filename = tmp_path / "test.json"
456
+ write_arrow(
457
+ table,
458
+ filename,
459
+ driver="GeoJSON",
460
+ crs=meta["crs"],
461
+ geometry_type=meta["geometry_type"],
462
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
463
+ )
464
+
465
+ assert filename.exists()
466
+
467
+ data = json.loads(open(filename).read())
468
+
469
+ assert data["type"] == "FeatureCollection"
470
+ assert data["name"] == "test"
471
+ assert "crs" in data
472
+ assert len(data["features"]) == len(table)
473
+ assert not len(
474
+ set(meta["fields"]).difference(data["features"][0]["properties"].keys())
475
+ )
476
+
477
+
478
+ @requires_arrow_write_api
479
+ @pytest.mark.parametrize(
480
+ "write_int64",
481
+ [
482
+ False,
483
+ pytest.param(
484
+ True,
485
+ marks=pytest.mark.skipif(
486
+ __gdal_version__ < (3, 9, 0),
487
+ reason="OpenFileGDB write support for int64 values for GDAL >= 3.9.0",
488
+ ),
489
+ ),
490
+ ],
491
+ )
492
+ def test_write_openfilegdb(tmp_path, write_int64):
493
+ expected_field_data = [
494
+ np.array([True, False, True], dtype="bool"),
495
+ np.array([1, 2, 3], dtype="int16"),
496
+ np.array([1, 2, 3], dtype="int32"),
497
+ np.array([1, 2, 3], dtype="int64"),
498
+ np.array([1, 2, 3], dtype="float32"),
499
+ np.array([1, 2, 3], dtype="float64"),
500
+ ]
501
+
502
+ table = pa.table(
503
+ {
504
+ "geometry": points,
505
+ **{field.dtype.name: field for field in expected_field_data},
506
+ }
507
+ )
508
+
509
+ filename = tmp_path / "test.gdb"
510
+
511
+ expected_meta = {"crs": "EPSG:4326"}
512
+
513
+ # int64 is not supported without additional config: https://gdal.org/en/latest/drivers/vector/openfilegdb.html#bit-integer-field-support
514
+ # it is converted to float64 by default and raises a warning
515
+ # (for GDAL >= 3.9.0 only)
516
+ write_params = (
517
+ {"TARGET_ARCGIS_VERSION": "ARCGIS_PRO_3_2_OR_LATER"} if write_int64 else {}
518
+ )
519
+
520
+ if write_int64 or __gdal_version__ < (3, 9, 0):
521
+ ctx = contextlib.nullcontext()
522
+ else:
523
+ ctx = pytest.warns(
524
+ RuntimeWarning, match="Integer64 will be written as a Float64"
525
+ )
526
+
527
+ with ctx:
528
+ write_arrow(
529
+ table,
530
+ filename,
531
+ driver="OpenFileGDB",
532
+ geometry_type="Point",
533
+ geometry_name="geometry",
534
+ **expected_meta,
535
+ **write_params,
536
+ )
537
+
538
+ meta, table = read_arrow(filename)
539
+
540
+ if not write_int64:
541
+ expected_field_data[3] = expected_field_data[3].astype("float64")
542
+
543
+ # bool types are converted to int32
544
+ expected_field_data[0] = expected_field_data[0].astype("int32")
545
+
546
+ assert meta["crs"] == expected_meta["crs"]
547
+
548
+ # NOTE: geometry name is set to "SHAPE" by GDAL
549
+ assert np.array_equal(table[meta["geometry_name"]], points)
550
+ for i in range(len(expected_field_data)):
551
+ values = table[table.schema.names[i]].to_numpy()
552
+ assert values.dtype == expected_field_data[i].dtype
553
+ assert np.array_equal(values, expected_field_data[i])
554
+
555
+
556
+ @pytest.mark.parametrize(
557
+ "driver",
558
+ {
559
+ driver
560
+ for driver in DRIVERS.values()
561
+ if driver not in ("ESRI Shapefile", "GPKG", "GeoJSON")
562
+ },
563
+ )
564
+ @requires_arrow_write_api
565
+ def test_write_supported(tmp_path, naturalearth_lowres, driver):
566
+ """Test drivers known to work that are not specifically tested above"""
567
+ meta, table = read_arrow(naturalearth_lowres, columns=["iso_a3"], max_features=1)
568
+
569
+ # note: naturalearth_lowres contains mixed polygons / multipolygons, which
570
+ # are not supported in mixed form for all drivers. To get around this here
571
+ # we take the first record only.
572
+ meta["geometry_type"] = "MultiPolygon"
573
+
574
+ filename = tmp_path / f"test{DRIVER_EXT[driver]}"
575
+ write_arrow(
576
+ table,
577
+ filename,
578
+ driver=driver,
579
+ crs=meta["crs"],
580
+ geometry_type=meta["geometry_type"],
581
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
582
+ )
583
+ assert filename.exists()
584
+
585
+
586
+ @requires_arrow_write_api
587
+ def test_write_unsupported(tmp_path, naturalearth_lowres):
588
+ meta, table = read_arrow(naturalearth_lowres)
589
+
590
+ with pytest.raises(DataSourceError, match="does not support write functionality"):
591
+ write_arrow(
592
+ table,
593
+ tmp_path / "test.json",
594
+ driver="ESRIJSON",
595
+ crs=meta["crs"],
596
+ geometry_type=meta["geometry_type"],
597
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
598
+ )
599
+
600
+
601
+ @pytest.mark.parametrize("ext", DRIVERS)
602
+ @requires_arrow_write_api
603
+ def test_write_append(request, tmp_path, naturalearth_lowres, ext):
604
+ if ext.startswith(".geojson"):
605
+ # Bug in GDAL when appending int64 to GeoJSON
606
+ # (https://github.com/OSGeo/gdal/issues/9792)
607
+ request.node.add_marker(
608
+ pytest.mark.xfail(reason="Bugs with append when writing Arrow to GeoJSON")
609
+ )
610
+
611
+ if ext == ".gpkg.zip":
612
+ pytest.skip("Append is not supported for .gpkg.zip")
613
+
614
+ meta, table = read_arrow(naturalearth_lowres)
615
+
616
+ # coerce output layer to generic Geometry to avoid mixed type errors
617
+ meta["geometry_type"] = "Unknown"
618
+
619
+ filename = tmp_path / f"test{ext}"
620
+ write_arrow(
621
+ table,
622
+ filename,
623
+ crs=meta["crs"],
624
+ geometry_type=meta["geometry_type"],
625
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
626
+ )
627
+ assert filename.exists()
628
+ assert read_info(filename)["features"] == 177
629
+
630
+ # write the same records again
631
+ write_arrow(
632
+ table,
633
+ filename,
634
+ append=True,
635
+ crs=meta["crs"],
636
+ geometry_type=meta["geometry_type"],
637
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
638
+ )
639
+ assert read_info(filename)["features"] == 354
640
+
641
+
642
+ @pytest.mark.parametrize("driver,ext", [("GML", ".gml")])
643
+ @requires_arrow_write_api
644
+ def test_write_append_unsupported(tmp_path, naturalearth_lowres, driver, ext):
645
+ meta, table = read_arrow(naturalearth_lowres)
646
+
647
+ # GML does not support append functionality
648
+ filename = tmp_path / "test.gml"
649
+ write_arrow(
650
+ table,
651
+ filename,
652
+ driver="GML",
653
+ crs=meta["crs"],
654
+ geometry_type=meta["geometry_type"],
655
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
656
+ )
657
+ assert filename.exists()
658
+ assert read_info(filename, force_feature_count=True)["features"] == 177
659
+
660
+ with pytest.raises(DataSourceError):
661
+ write_arrow(
662
+ table,
663
+ filename,
664
+ driver="GML",
665
+ append=True,
666
+ crs=meta["crs"],
667
+ geometry_type=meta["geometry_type"],
668
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
669
+ )
670
+
671
+
672
+ @requires_arrow_write_api
673
+ def test_write_gdalclose_error(naturalearth_lowres):
674
+ meta, table = read_arrow(naturalearth_lowres)
675
+
676
+ filename = "s3://non-existing-bucket/test.geojson"
677
+
678
+ # set config options to avoid errors on open due to GDAL S3 configuration
679
+ set_gdal_config_options(
680
+ {
681
+ "AWS_ACCESS_KEY_ID": "invalid",
682
+ "AWS_SECRET_ACCESS_KEY": "invalid",
683
+ "AWS_NO_SIGN_REQUEST": True,
684
+ }
685
+ )
686
+
687
+ with pytest.raises(DataSourceError, match="Failed to write features to dataset"):
688
+ write_arrow(
689
+ table,
690
+ filename,
691
+ crs=meta["crs"],
692
+ geometry_type=meta["geometry_type"],
693
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
694
+ )
695
+
696
+
697
+ @requires_arrow_write_api
698
+ @pytest.mark.parametrize("name", ["geoarrow.wkb", "ogc.wkb"])
699
+ def test_write_geometry_extension_type(tmp_path, naturalearth_lowres, name):
700
+ # Infer geometry column based on extension name
701
+ # instead of passing `geometry_name` explicitly
702
+ meta, table = read_arrow(naturalearth_lowres)
703
+
704
+ # change extension type name
705
+ idx = table.schema.get_field_index("wkb_geometry")
706
+ new_field = table.schema.field(idx).with_metadata({"ARROW:extension:name": name})
707
+ new_table = table.cast(table.schema.set(idx, new_field))
708
+
709
+ filename = tmp_path / "test_geoarrow.shp"
710
+ write_arrow(
711
+ new_table,
712
+ filename,
713
+ crs=meta["crs"],
714
+ geometry_type=meta["geometry_type"],
715
+ )
716
+ _, table_roundtripped = read_arrow(filename)
717
+ assert table_roundtripped.equals(table)
718
+
719
+
720
+ @requires_arrow_write_api
721
+ def test_write_unsupported_geoarrow(tmp_path, naturalearth_lowres):
722
+ meta, table = read_arrow(naturalearth_lowres)
723
+
724
+ # change extension type name (the name doesn't match with the column type
725
+ # for correct geoarrow data, but our writing code checks it based on the name)
726
+ idx = table.schema.get_field_index("wkb_geometry")
727
+ new_field = table.schema.field(idx).with_metadata(
728
+ {"ARROW:extension:name": "geoarrow.point"}
729
+ )
730
+ new_table = table.cast(table.schema.set(idx, new_field))
731
+
732
+ with pytest.raises(
733
+ NotImplementedError,
734
+ match="Writing a geometry column of type geoarrow.point is not yet supported",
735
+ ):
736
+ write_arrow(
737
+ new_table,
738
+ tmp_path / "test_geoarrow.shp",
739
+ crs=meta["crs"],
740
+ geometry_type=meta["geometry_type"],
741
+ )
742
+
743
+
744
+ @requires_arrow_write_api
745
+ def test_write_no_geom(tmp_path, naturalearth_lowres):
746
+ _, table = read_arrow(naturalearth_lowres)
747
+ table = table.drop_columns("wkb_geometry")
748
+
749
+ # Test
750
+ filename = tmp_path / "test.gpkg"
751
+ write_arrow(table, filename)
752
+ # Check result
753
+ assert filename.exists()
754
+ meta, result = read_arrow(filename)
755
+ assert meta["crs"] is None
756
+ assert meta["geometry_type"] is None
757
+ assert table.equals(result)
758
+
759
+
760
+ @requires_arrow_write_api
761
+ def test_write_geometry_type(tmp_path, naturalearth_lowres):
762
+ meta, table = read_arrow(naturalearth_lowres)
763
+
764
+ # Not specifying the geometry currently raises an error
765
+ with pytest.raises(ValueError, match="'geometry_type' keyword is required"):
766
+ write_arrow(
767
+ table,
768
+ tmp_path / "test.shp",
769
+ crs=meta["crs"],
770
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
771
+ )
772
+
773
+ # Specifying "Unknown" works and will create generic layer
774
+ filename = tmp_path / "test.gpkg"
775
+ write_arrow(
776
+ table,
777
+ filename,
778
+ crs=meta["crs"],
779
+ geometry_type="Unknown",
780
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
781
+ )
782
+ assert filename.exists()
783
+ meta_written, _ = read_arrow(filename)
784
+ assert meta_written["geometry_type"] == "Unknown"
785
+
786
+
787
+ @requires_arrow_write_api
788
+ def test_write_raise_promote_to_multi(tmp_path, naturalearth_lowres):
789
+ meta, table = read_arrow(naturalearth_lowres)
790
+
791
+ with pytest.raises(
792
+ ValueError, match="The 'promote_to_multi' option is not supported"
793
+ ):
794
+ write_arrow(
795
+ table,
796
+ tmp_path / "test.shp",
797
+ crs=meta["crs"],
798
+ geometry_type=meta["geometry_type"],
799
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
800
+ promote_to_multi=True,
801
+ )
802
+
803
+
804
+ @requires_arrow_write_api
805
+ def test_write_no_crs(tmp_path, naturalearth_lowres):
806
+ meta, table = read_arrow(naturalearth_lowres)
807
+
808
+ filename = tmp_path / "test.shp"
809
+ with pytest.warns(UserWarning, match="'crs' was not provided"):
810
+ write_arrow(
811
+ table,
812
+ filename,
813
+ geometry_type=meta["geometry_type"],
814
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
815
+ )
816
+ # apart from CRS warning, it did write correctly
817
+ meta_result, result = read_arrow(filename)
818
+ assert table.equals(result)
819
+ assert meta_result["crs"] is None
820
+
821
+
822
+ @requires_arrow_write_api
823
+ def test_write_non_arrow_data(tmp_path):
824
+ data = np.array([1, 2, 3])
825
+ with pytest.raises(
826
+ ValueError, match="The provided data is not recognized as Arrow data"
827
+ ):
828
+ write_arrow(
829
+ data,
830
+ tmp_path / "test_no_arrow_data.shp",
831
+ crs="EPSG:4326",
832
+ geometry_type="Point",
833
+ geometry_name="geometry",
834
+ )
835
+
836
+
837
+ @pytest.mark.skipif(
838
+ Version(pa.__version__) < Version("16.0.0.dev0"),
839
+ reason="PyCapsule protocol only added to pyarrow.ChunkedArray in pyarrow 16",
840
+ )
841
+ @requires_arrow_write_api
842
+ def test_write_non_arrow_tabular_data(tmp_path):
843
+ data = pa.chunked_array([[1, 2, 3], [4, 5, 6]])
844
+ with pytest.raises(
845
+ DataLayerError,
846
+ match=".*should be called on a schema that is a struct of fields",
847
+ ):
848
+ write_arrow(
849
+ data,
850
+ tmp_path / "test_no_arrow_tabular_data.shp",
851
+ crs="EPSG:4326",
852
+ geometry_type="Point",
853
+ geometry_name="geometry",
854
+ )
855
+
856
+
857
+ @pytest.mark.filterwarnings("ignore:.*not handled natively:RuntimeWarning")
858
+ @requires_arrow_write_api
859
+ def test_write_batch_error_message(tmp_path):
860
+ # raise the correct error and message from GDAL when an error happens
861
+ # while writing
862
+
863
+ # invalid dictionary array that will only error while writing (schema
864
+ # itself is OK)
865
+ arr = pa.DictionaryArray.from_buffers(
866
+ pa.dictionary(pa.int64(), pa.string()),
867
+ length=3,
868
+ buffers=pa.array([0, 1, 2]).buffers(),
869
+ dictionary=pa.array(["a", "b"]),
870
+ )
871
+ table = pa.table({"geometry": points, "col": arr})
872
+
873
+ with pytest.raises(DataLayerError, match=".*invalid dictionary index"):
874
+ write_arrow(
875
+ table,
876
+ tmp_path / "test_unsupported_list_type.fgb",
877
+ crs="EPSG:4326",
878
+ geometry_type="Point",
879
+ geometry_name="geometry",
880
+ )
881
+
882
+
883
+ @requires_arrow_write_api
884
+ def test_write_schema_error_message(tmp_path):
885
+ # raise the correct error and message from GDAL when an error happens
886
+ # creating the fields from the schema
887
+ # (using complex list of map of integer->integer which is not supported by GDAL)
888
+ table = pa.table(
889
+ {
890
+ "geometry": points,
891
+ "col": pa.array(
892
+ [[[(1, 2), (3, 4)], None, [(5, 6)]]] * 3,
893
+ pa.list_(pa.map_(pa.int64(), pa.int64())),
894
+ ),
895
+ }
896
+ )
897
+
898
+ with pytest.raises(FieldError, match=".*not supported"):
899
+ write_arrow(
900
+ table,
901
+ tmp_path / "test_unsupported_map_type.shp",
902
+ crs="EPSG:4326",
903
+ geometry_type="Point",
904
+ geometry_name="geometry",
905
+ )
906
+
907
+
908
+ @requires_arrow_write_api
909
+ @pytest.mark.filterwarnings("ignore:File /vsimem:RuntimeWarning")
910
+ @pytest.mark.parametrize("driver", ["GeoJSON", "GPKG"])
911
+ def test_write_memory(naturalearth_lowres, driver):
912
+ meta, table = read_arrow(naturalearth_lowres, max_features=1)
913
+ meta["geometry_type"] = "MultiPolygon"
914
+
915
+ buffer = BytesIO()
916
+ write_arrow(
917
+ table,
918
+ buffer,
919
+ driver=driver,
920
+ layer="test",
921
+ crs=meta["crs"],
922
+ geometry_type=meta["geometry_type"],
923
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
924
+ )
925
+
926
+ assert len(buffer.getbuffer()) > 0
927
+ assert list_layers(buffer)[0][0] == "test"
928
+
929
+ actual_meta, actual_table = read_arrow(buffer)
930
+ assert len(actual_table) == len(table)
931
+ assert np.array_equal(actual_meta["fields"], meta["fields"])
932
+
933
+
934
+ @requires_arrow_write_api
935
+ def test_write_memory_driver_required(naturalearth_lowres):
936
+ meta, table = read_arrow(naturalearth_lowres, max_features=1)
937
+
938
+ buffer = BytesIO()
939
+ with pytest.raises(
940
+ ValueError,
941
+ match="driver must be provided to write to in-memory file",
942
+ ):
943
+ write_arrow(
944
+ table,
945
+ buffer,
946
+ driver=None,
947
+ layer="test",
948
+ crs=meta["crs"],
949
+ geometry_type=meta["geometry_type"],
950
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
951
+ )
952
+
953
+ # Check temp file was cleaned up. Filter, as gdal keeps cache files in /vsimem/.
954
+ assert vsi_listtree("/vsimem/", pattern="pyogrio_*") == []
955
+
956
+
957
+ @requires_arrow_write_api
958
+ @pytest.mark.parametrize("driver", ["ESRI Shapefile", "OpenFileGDB"])
959
+ def test_write_memory_unsupported_driver(naturalearth_lowres, driver):
960
+ meta, table = read_arrow(naturalearth_lowres, max_features=1)
961
+
962
+ buffer = BytesIO()
963
+
964
+ with pytest.raises(
965
+ ValueError, match=f"writing to in-memory file is not supported for {driver}"
966
+ ):
967
+ write_arrow(
968
+ table,
969
+ buffer,
970
+ driver=driver,
971
+ layer="test",
972
+ crs=meta["crs"],
973
+ geometry_type=meta["geometry_type"],
974
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
975
+ )
976
+
977
+
978
+ @requires_arrow_write_api
979
+ @pytest.mark.parametrize("driver", ["GeoJSON", "GPKG"])
980
+ def test_write_memory_append_unsupported(naturalearth_lowres, driver):
981
+ meta, table = read_arrow(naturalearth_lowres, max_features=1)
982
+ meta["geometry_type"] = "MultiPolygon"
983
+
984
+ buffer = BytesIO()
985
+ with pytest.raises(
986
+ NotImplementedError, match="append is not supported for in-memory files"
987
+ ):
988
+ write_arrow(
989
+ table,
990
+ buffer,
991
+ driver=driver,
992
+ layer="test",
993
+ crs=meta["crs"],
994
+ geometry_type=meta["geometry_type"],
995
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
996
+ append=True,
997
+ )
998
+
999
+
1000
+ @requires_arrow_write_api
1001
+ def test_write_memory_existing_unsupported(naturalearth_lowres):
1002
+ meta, table = read_arrow(naturalearth_lowres, max_features=1)
1003
+ meta["geometry_type"] = "MultiPolygon"
1004
+
1005
+ buffer = BytesIO(b"0000")
1006
+ with pytest.raises(
1007
+ NotImplementedError,
1008
+ match="writing to existing in-memory object is not supported",
1009
+ ):
1010
+ write_arrow(
1011
+ table,
1012
+ buffer,
1013
+ driver="GeoJSON",
1014
+ layer="test",
1015
+ crs=meta["crs"],
1016
+ geometry_type=meta["geometry_type"],
1017
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
1018
+ )
1019
+
1020
+
1021
+ @requires_arrow_write_api
1022
+ def test_write_open_file_handle(tmp_path, naturalearth_lowres):
1023
+ """Verify that writing to an open file handle is not currently supported"""
1024
+
1025
+ meta, table = read_arrow(naturalearth_lowres, max_features=1)
1026
+ meta["geometry_type"] = "MultiPolygon"
1027
+
1028
+ # verify it fails for regular file handle
1029
+ with pytest.raises(
1030
+ NotImplementedError, match="writing to an open file handle is not yet supported"
1031
+ ):
1032
+ with open(tmp_path / "test.geojson", "wb") as f:
1033
+ write_arrow(
1034
+ table,
1035
+ f,
1036
+ driver="GeoJSON",
1037
+ layer="test",
1038
+ crs=meta["crs"],
1039
+ geometry_type=meta["geometry_type"],
1040
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
1041
+ )
1042
+
1043
+ # verify it fails for ZipFile
1044
+ with pytest.raises(
1045
+ NotImplementedError, match="writing to an open file handle is not yet supported"
1046
+ ):
1047
+ with ZipFile(tmp_path / "test.geojson.zip", "w") as z:
1048
+ with z.open("test.geojson", "w") as f:
1049
+ write_arrow(
1050
+ table,
1051
+ f,
1052
+ driver="GeoJSON",
1053
+ layer="test",
1054
+ crs=meta["crs"],
1055
+ geometry_type=meta["geometry_type"],
1056
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
1057
+ )
1058
+
1059
+ # Check temp file was cleaned up. Filter, as gdal keeps cache files in /vsimem/.
1060
+ assert vsi_listtree("/vsimem/", pattern="pyogrio_*") == []
1061
+
1062
+
1063
+ @requires_arrow_write_api
1064
+ def test_non_utf8_encoding_io_shapefile(tmp_path, encoded_text):
1065
+ encoding, text = encoded_text
1066
+
1067
+ table = pa.table(
1068
+ {
1069
+ # Point(0, 0)
1070
+ "geometry": pa.array(
1071
+ [bytes.fromhex("010100000000000000000000000000000000000000")]
1072
+ ),
1073
+ text: pa.array([text]),
1074
+ }
1075
+ )
1076
+
1077
+ filename = tmp_path / "test.shp"
1078
+ write_arrow(
1079
+ table,
1080
+ filename,
1081
+ geometry_type="Point",
1082
+ geometry_name="geometry",
1083
+ crs="EPSG:4326",
1084
+ encoding=encoding,
1085
+ )
1086
+
1087
+ # NOTE: GDAL automatically creates a cpg file with the encoding name, which
1088
+ # means that if we read this without specifying the encoding it uses the
1089
+ # correct one
1090
+ schema, table = read_arrow(filename)
1091
+ assert schema["fields"][0] == text
1092
+ assert table[text][0].as_py() == text
1093
+
1094
+ # verify that if cpg file is not present, that user-provided encoding must be used
1095
+ filename.with_suffix(".cpg").unlink()
1096
+
1097
+ # We will assume ISO-8859-1, which is wrong
1098
+ miscoded = text.encode(encoding).decode("ISO-8859-1")
1099
+ bad_schema = read_arrow(filename)[0]
1100
+ assert bad_schema["fields"][0] == miscoded
1101
+ # table cannot be decoded to UTF-8 without UnicodeDecodeErrors
1102
+
1103
+ # If encoding is provided, that should yield correct text
1104
+ schema, table = read_arrow(filename, encoding=encoding)
1105
+ assert schema["fields"][0] == text
1106
+ assert table[text][0].as_py() == text
1107
+
1108
+ # verify that setting encoding does not corrupt SHAPE_ENCODING option if set
1109
+ # globally (it is ignored during read when encoding is specified by user)
1110
+ try:
1111
+ set_gdal_config_options({"SHAPE_ENCODING": "CP1254"})
1112
+ _ = read_arrow(filename, encoding=encoding)
1113
+ assert get_gdal_config_option("SHAPE_ENCODING") == "CP1254"
1114
+
1115
+ finally:
1116
+ # reset to clear between tests
1117
+ set_gdal_config_options({"SHAPE_ENCODING": None})
1118
+
1119
+
1120
+ @requires_arrow_write_api
1121
+ def test_encoding_write_layer_option_collision_shapefile(tmp_path, naturalearth_lowres):
1122
+ """Providing both encoding parameter and ENCODING layer creation option
1123
+ (even if blank) is not allowed."""
1124
+
1125
+ meta, table = read_arrow(naturalearth_lowres)
1126
+
1127
+ with pytest.raises(
1128
+ ValueError,
1129
+ match=(
1130
+ 'cannot provide both encoding parameter and "ENCODING" layer creation '
1131
+ "option"
1132
+ ),
1133
+ ):
1134
+ write_arrow(
1135
+ table,
1136
+ tmp_path / "test.shp",
1137
+ crs=meta["crs"],
1138
+ geometry_type="MultiPolygon",
1139
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
1140
+ encoding="CP936",
1141
+ layer_options={"ENCODING": ""},
1142
+ )
1143
+
1144
+
1145
+ @requires_arrow_write_api
1146
+ @pytest.mark.parametrize("ext", ["gpkg", "geojson"])
1147
+ def test_non_utf8_encoding_io_arrow_exception(tmp_path, naturalearth_lowres, ext):
1148
+ meta, table = read_arrow(naturalearth_lowres)
1149
+
1150
+ with pytest.raises(
1151
+ ValueError, match="non-UTF-8 encoding is not supported for Arrow"
1152
+ ):
1153
+ write_arrow(
1154
+ table,
1155
+ tmp_path / f"test.{ext}",
1156
+ crs=meta["crs"],
1157
+ geometry_type="MultiPolygon",
1158
+ geometry_name=meta["geometry_name"] or "wkb_geometry",
1159
+ encoding="CP936",
1160
+ )