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
//! Read and write [OGC GeoPackage](https://www.geopackage.org/spec140/) files.
//!
//! A GeoPackage is an SQLite database with a standardised schema for vector
//! features and raster tiles. [`GeoPackage::create`], [`GeoPackage::open`] and
//! [`GeoPackage::open_read_only`] open the container with pragma and schema
//! validation;
//! [`GeoPackage::layer`] returns a [`Layer`] handle for reading and writing
//! features, and [`GeoPackage::layers`] enumerates them.
//! [`GeoPackage::tiles`] returns a [`TilePyramid`] handle for the tile side,
//! described under [Tiles](#tiles) below.
//!
//! # Quick start
//!
//! Create a file, define a point layer, write features, query by bounding box:
//!
//! ```
//! use geo_types::Point;
//! use geopackage::core::types::{ColumnType, GeometryType};
//! use geopackage::{
//! BoundingBox, ColumnSpec, GeoPackage, GeometrySpec, NewFeature, TableSchemaBuilder, Value,
//! ValueRef,
//! };
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let dir = tempfile::tempdir()?;
//! # let path = dir.path().join("cities.gpkg");
//! let gpkg = GeoPackage::create(path)?;
//!
//! gpkg.create_layer(
//! &TableSchemaBuilder::new("cities")
//! .column(ColumnSpec::new("name", ColumnType::Text(None)))
//! .geometry(GeometrySpec::new(GeometryType::Point, 4326)),
//! )?;
//!
//! let layer = gpkg.layer("cities")?;
//! layer.write_all(
//! vec![
//! NewFeature::new(Point::new(-6.26, 53.35), vec![Value::Text("Dublin".into())]),
//! NewFeature::new(Point::new(-0.13, 51.51), vec![Value::Text("London".into())]),
//! ],
//! 0,
//! )?;
//!
//! // Served by the layer's RTree index, which `create_layer` builds unless
//! // `TableSchemaBuilder::spatial_index(false)` declines it.
//! for feature in layer.features_in(BoundingBox::new(-7.0, 53.0, -6.0, 54.0))? {
//! let feature = feature?;
//! assert_eq!(feature.value("name"), Some(ValueRef::Text("Dublin")));
//! }
//! # Ok(()) }
//! ```
//!
//! [`Layer::features`] iterates every row as an owned [`Feature`];
//! [`Layer::select`] appends a caller-supplied raw SQL `WHERE` clause;
//! [`Layer::features_in`] runs the bounding-box query, served by the RTree
//! index when one is present and a full scan otherwise, with identical
//! results. Each has a streaming counterpart ([`Layer::cursor`],
//! [`Layer::cursor_select`], [`Layer::cursor_in`]) that reads one row at a
//! time and holds no result set. For writing, [`Layer::write_all`] batch-loads
//! and [`Layer::writer`] opens a transaction with per-row
//! `insert`/`update`/`delete` ([`FeatureWriter`]).
//! [`GeoPackage::create_attributes_table`] and [`GeoPackage::attributes`] are
//! the same for non-spatial attribute tables, and [`GeoPackage::add_epsg_srs`]
//! registers an EPSG code in `gpkg_spatial_ref_sys`.
//! [`GeoPackage::open_lenient`] tolerates legacy and lightly malformed files,
//! collecting [`OpenWarning`]s instead of failing.
//!
//! # Geometry round trips
//!
//! [`Feature::geometry`] parses the stored blob into a
//! [`GpbGeometry`](core::GpbGeometry), a view over the row's bytes that
//! implements [`geo_traits::GeometryTrait`], and every write method accepts
//! any `impl GeometryTrait<T = f64>`. A geometry can therefore be streamed
//! out of one file, measured, and written into another without being
//! converted to a `geo-types` value in either direction if need be: the analysis reads
//! coordinates from the stored encoding, and the writer encodes WKB from the
//! same view. What _does_ allocate is each row's blob, copied out of SQLite,
//! and the new blob the writer serialises; an algorithm that produces new
//! geometry also allocates its output.
//!
//! ```
//! use geo_traits::{CoordTrait, GeometryTrait, GeometryType as Kind, LineStringTrait};
//! use geopackage::core::types::{ColumnType, GeometryType};
//! use geopackage::{ColumnSpec, GeoPackage, GeometrySpec, TableSchemaBuilder, Value, ValueRef};
//!
//! /// Planar length, read from the trait: no geometry object is built.
//! fn length(geometry: &impl GeometryTrait<T = f64>) -> f64 {
//! let Kind::LineString(line) = geometry.as_type() else {
//! return 0.0;
//! };
//! let mut sum = 0.0;
//! let mut prev: Option<(f64, f64)> = None;
//! for coord in line.coords() {
//! let (x, y) = (coord.x(), coord.y());
//! if let Some((px, py)) = prev {
//! sum += ((x - px).powi(2) + (y - py).powi(2)).sqrt();
//! }
//! prev = Some((x, y));
//! }
//! sum
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let dir = tempfile::tempdir()?;
//! # let src_path = dir.path().join("roads.gpkg");
//! # let dst_path = dir.path().join("measured.gpkg");
//! # {
//! # let src = GeoPackage::create(&src_path)?;
//! # src.create_layer(
//! # &TableSchemaBuilder::new("roads")
//! # .geometry(GeometrySpec::new(GeometryType::LineString, 4326)),
//! # )?;
//! # src.layer("roads")?.write_all(
//! # vec![
//! # geopackage::NewFeature::new(
//! # geo_types::LineString::from(vec![(0.0, 0.0), (3.0, 4.0)]),
//! # vec![],
//! # ),
//! # geopackage::NewFeature::new(
//! # geo_types::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)]),
//! # vec![],
//! # ),
//! # ],
//! # 0,
//! # )?;
//! # }
//! let src = GeoPackage::open_read_only(&src_path)?;
//! let dst = GeoPackage::create(&dst_path)?;
//! dst.create_layer(
//! &TableSchemaBuilder::new("measured")
//! .column(ColumnSpec::new("length", ColumnType::Double))
//! .geometry(GeometrySpec::new(GeometryType::LineString, 4326)),
//! )?;
//!
//! let roads = src.layer("roads")?;
//! let measured = dst.layer("measured")?;
//! let mut writer = measured.writer()?;
//! let mut cursor = roads.cursor()?;
//! for feature in cursor.features()? {
//! let feature = feature?;
//! if let Some(geometry) = feature.geometry()? {
//! // `geometry` borrows the row's blob; `length` reads coordinates
//! // from it, and `insert` encodes WKB from the same view.
//! let l = length(&geometry);
//! writer.insert(None, &geometry, &[ValueRef::Float(l)])?;
//! }
//! }
//! writer.commit()?;
//!
//! let mut total = 0.0;
//! for feature in measured.features()? {
//! if let Some(l) = feature?.value("length").and_then(|v| v.as_f64()) {
//! total += l;
//! }
//! }
//! assert_eq!(total, 7.0);
//! # Ok(()) }
//! ```
//!
//! # Tiles
//!
//! A tile pyramid is the container's other data type: pre-rendered raster
//! tiles, addressed by zoom level, column and row, with a
//! `gpkg_tile_matrix_set` row fixing the ground extent they are indexed
//! against and a `gpkg_tile_matrix` row per zoom level.
//! [`GeoPackage::create_tile_pyramid`] writes one (from a
//! [`TilePyramidBuilder`]), [`GeoPackage::tiles`] opens one, and
//! [`GeoPackage::tile_pyramids`] enumerates them.
//!
//! **Payloads are opaque.** This crate stores, indexes and validates tiles; it
//! decodes none of them, and depends on no image codec. It reads each
//! payload's *header*, which is how a tile written at the wrong pixel size, or
//! in a format the table may not hold, is rejected rather than stored. Turning
//! a tile into pixels, or a source raster into a pyramid, needs an image
//! library or GDAL on top of this one.
//!
//! Rows count from the **top** of the extent downwards, as WMTS and XYZ do and
//! TMS does not, and the indices are relative to the pyramid's own extent
//! rather than to a global grid. [`TileMatrix::flip_row`](core::tiles::TileMatrix::flip_row)
//! converts to and from the TMS sense, and
//! [`TileMatrixSet::xyz_to_tile`](core::tiles::TileMatrixSet::xyz_to_tile)
//! refuses rather than mis-addressing when a pyramid is not the standard web
//! mercator quad.
//!
//! ```
//! use geopackage::core::tiles::{TileCoord, TileMatrixSet, ZoomLadder};
//! use geopackage::{GeoPackage, TilePyramidBuilder};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let dir = tempfile::tempdir()?;
//! # let path = dir.path().join("basemap.gpkg");
//! # let png = |w: u32, h: u32| {
//! # let mut b = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
//! # b.extend_from_slice(&13u32.to_be_bytes());
//! # b.extend_from_slice(b"IHDR");
//! # b.extend_from_slice(&w.to_be_bytes());
//! # b.extend_from_slice(&h.to_be_bytes());
//! # b.extend_from_slice(&[8, 6, 0, 0, 0, 0, 0, 0, 0]);
//! # b
//! # };
//! let gpkg = GeoPackage::create(path)?;
//! gpkg.add_epsg_srs(3857)?;
//!
//! // The spec's default arrangement: each zoom level doubles the grid, with
//! // pixel sizes derived from the extent so they span it exactly.
//! let matrix_set = TileMatrixSet::web_mercator_quad();
//! let matrices = matrix_set.ladder(ZoomLadder::new(0, 4))?;
//! let tiles = gpkg.create_tile_pyramid(
//! &TilePyramidBuilder::new("basemap", matrix_set).matrices(matrices),
//! )?;
//!
//! tiles.put_tile(TileCoord::new(1, 0, 0), &png(256, 256))?;
//! assert!(tiles.get_tile(TileCoord::new(1, 0, 0))?.is_some());
//!
//! // Streaming a pyramid lends each payload out of the row it was read from,
//! // so nothing is copied to walk one.
//! let mut cursor = tiles.cursor()?;
//! let mut stream = cursor.tiles()?;
//! while let Some(tile) = stream.next()? {
//! assert_eq!(tile.data().len(), 33);
//! }
//! # Ok(()) }
//! ```
//!
//! # Columnar I/O
//!
//! Enabled by the `arrow` feature, [`Layer::read_arrow`] reads a layer as Arrow
//! record batches, multithreaded by default, and [`Layer::write_arrow`]
//! writes batches back through the same path as [`Layer::write_all`].
//! Geometry is a GeoArrow WKB column whose metadata includes the CRS as
//! PROJJSON. [`TableSchemaBuilder::from_arrow_schema`] is the layer
//! definition an Arrow schema implies, so a layer can be copied without its
//! schema being restated; the type mapping both directions share is
//! documented on the [`arrow`] module.
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # #[cfg(feature = "arrow")]
//! # {
//! # use geo_types::Point;
//! # use geopackage::core::types::{ColumnType, GeometryType};
//! # use geopackage::{ColumnSpec, GeoPackage, GeometrySpec, NewFeature, TableSchemaBuilder, Value};
//! # let dir = tempfile::tempdir()?;
//! # let src_path = dir.path().join("cities.gpkg");
//! # let dst_path = dir.path().join("copy.gpkg");
//! # {
//! # let src = GeoPackage::create(&src_path)?;
//! # src.create_layer(
//! # &TableSchemaBuilder::new("cities")
//! # .column(ColumnSpec::new("name", ColumnType::Text(None)))
//! # .geometry(GeometrySpec::new(GeometryType::Point, 4326)),
//! # )?;
//! # src.layer("cities")?.write_all(
//! # vec![
//! # NewFeature::new(Point::new(-6.26, 53.35), vec![Value::Text("Dublin".into())]),
//! # NewFeature::new(Point::new(-0.13, 51.51), vec![Value::Text("London".into())]),
//! # ],
//! # 0,
//! # )?;
//! # }
//! use geopackage::arrow::ArrowReadOptions;
//!
//! let src = GeoPackage::open_read_only(&src_path)?;
//! let cities = src.layer("cities")?;
//!
//! let dst = GeoPackage::create(&dst_path)?;
//! let schema = cities.arrow_schema()?;
//! dst.create_layer(&TableSchemaBuilder::new("cities").from_arrow_schema(&schema)?)?;
//!
//! let batches = cities.read_arrow(ArrowReadOptions::default())?;
//! dst.layer("cities")?.write_arrow(batches, 0)?;
//! assert_eq!(dst.layer("cities")?.features()?.len(), 2);
//! # }
//! # Ok(()) }
//! ```
//!
//! # Extensions
//!
//! `gpkg_extensions` is where a file declares what it uses beyond the core
//! spec. [`GeoPackage::extensions`] reads that catalogue, and
//! [`Layer::extensions`] and [`TilePyramid::extensions`] narrow it to one
//! table. Every row identifies as an [`Extension`] and carries an
//! [`ExtensionSupport`]: read and written here, identified and left alone,
//! removed from the standard in 2016 and tolerated on read, or not recognised
//! at all.
//!
//! That last one is not only informational. Writing to a table covered by an
//! extension this crate cannot identify is refused with
//! [`Error::UnsupportedExtension`], because such an extension may constrain
//! the rows, triggers or encodings of the table it covers and writing beside
//! it could produce a file its own producer can no longer read. Reading is
//! never refused for this reason. [`GeoPackage::blocking_extension`] asks the
//! question directly, and
//! [`OpenOptions::allow_unsupported_extension_writes`] overrides the refusal.
//!
//! Two extensions are surfaced as part of the model rather than as catalogue
//! rows. `gpkg_crs_wkt` puts a WKT2 CRS definition and a coordinate epoch on
//! [`Srs`], which is how a CRS with no WKT1 form is carried at all.
//! `gpkg_schema` describes columns and constrains their values:
//! [`GeoPackage::data_columns`] and [`Column::data_column`] give the
//! descriptions, [`GeoPackage::column_constraint`] resolves what a column's
//! values are limited to, and [`GeoPackage::set_data_column`] and
//! [`GeoPackage::add_column_constraint`] write them.
//!
//! ```
//! use geopackage::{ColumnConstraint, ConstraintKind, DataColumn, GeoPackage, OpenOptions};
//! # use geopackage::core::types::{ColumnType, GeometryType};
//! # use geopackage::{ColumnSpec, GeometrySpec, TableSchemaBuilder};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let dir = tempfile::tempdir()?;
//! # let path = dir.path().join("sites.gpkg");
//! # {
//! # let gpkg = GeoPackage::create(&path)?;
//! # gpkg.create_layer(
//! # &TableSchemaBuilder::new("sites")
//! # .column(ColumnSpec::new("year", ColumnType::Integer))
//! # .geometry(GeometrySpec::new(GeometryType::Point, 4326)),
//! # )?;
//! let gpkg = GeoPackage::open(&path)?;
//! gpkg.add_column_constraint(&ColumnConstraint {
//! name: "years".into(),
//! kind: ConstraintKind::Range {
//! min: 1900.0,
//! min_is_inclusive: true,
//! max: 2000.0,
//! max_is_inclusive: false,
//! },
//! description: None,
//! })?;
//! gpkg.set_data_column(
//! "sites",
//! &DataColumn {
//! column_name: "year".into(),
//! name: Some("Year surveyed".into()),
//! title: None,
//! description: None,
//! mime_type: None,
//! constraint_name: Some("years".into()),
//! },
//! )?;
//! # }
//!
//! // The constraints are advisory in the format, so checking written values
//! // against them is asked for rather than assumed.
//! let gpkg = OpenOptions::new()
//! .enforce_column_constraints(true)
//! .open(&path)?;
//! # let layer = gpkg.layer("sites")?;
//! # let mut writer = layer.writer()?;
//! # use geopackage::ValueRef;
//! # assert!(writer.insert(None, &geo_types::Point::new(0.0, 0.0), &[ValueRef::Integer(1850)]).is_err());
//! # Ok(()) }
//! ```
//!
//! # Cargo features
//!
//! - **`geo-types`** (on by default): forwards `geopackage-core`'s feature of
//! the same name, which adds
//! [`GpbGeometry::to_geo`](geopackage_core::geometry::GpbGeometry::to_geo).
//! Decline it with `default-features = false`.
//! - **`arrow`** (off by default): the columnar paths above. It pulls in
//! `arrow-array` and `arrow-schema`, which a caller using only the scalar API
//! does not need.
//!
//! # Configuration
//!
//! The defaults are intended to support the common case: a single-file GeoPackage, an indexed
//! feature layer, and values read in keeping with other popular implementations.
//! Each of these types documents possible trade-off behind its defaults:
//!
//! - [`OpenOptions`]: the journal mode ([`JournalMode`], where
//! [`JournalMode::Wal`] is opt-in), the `synchronous` durability level
//! ([`Synchronous`]), and how long a statement waits for another
//! connection's lock ([`OpenOptions::busy_timeout`], default
//! [`DEFAULT_BUSY_TIMEOUT`], five seconds, against SQLite's own default of
//! not waiting at all). Left unset, the file keeps SQLite's own defaults for
//! the first two. A
//! handle that opted into WAL resets the file to a single `DELETE`-journal
//! file on close, so the `.gpkg` handed on has no sidecar files; see
//! [`GeoPackage`].
//! - [`TableSchemaBuilder`]: a new layer's columns ([`ColumnSpec`]), primary
//! key (default [`DEFAULT_PRIMARY_KEY`], `fid`), geometry column
//! ([`GeometrySpec`], named [`DEFAULT_GEOMETRY_COLUMN`], `geom`, unless told
//! otherwise), and whether it is indexed
//! ([`TableSchemaBuilder::spatial_index`], default `true`).
//! [`Layer::create_spatial_index`], [`Layer::drop_spatial_index`],
//! [`Layer::repair_spatial_index`], [`Layer::audit_spatial_index`] and
//! [`Layer::rebuild_spatial_index`] manage the index after creation.
//! - [`BulkIndexOptions`]: how an RTree index is built, for
//! [`Layer::create_spatial_index_with`] and [`Layer::write_all_with`]: the
//! row count at which the bulk build takes over from the per-row triggers
//! ([`BulkIndexOptions::bulk_threshold`], default [`DEFAULT_BULK_THRESHOLD`],
//! 10,000 rows), how much of the result it checks before trusting it
//! ([`BulkVerification`], default [`BulkVerification::None`]), and how full
//! each node of the tree is
//! packed ([`BulkIndexOptions::fill_factor`], default
//! [`DEFAULT_FILL_FACTOR`], `1.0`).
//! - [`TilePyramidBuilder`]: a new pyramid's extent and spatial reference
//! system ([`TileMatrixSet`](core::tiles::TileMatrixSet)), its zoom levels
//! ([`TileMatrix`](core::tiles::TileMatrix), usually from
//! [`TileMatrixSet::ladder`](core::tiles::TileMatrixSet::ladder)), and
//! whether zoom levels that do not step by factors of two are allowed
//! ([`TilePyramidBuilder::allow_zoom_other`], off by default, since that
//! needs the `gpkg_zoom_other` extension registered).
//! - **Column projection**, through [`Layer::with_columns`] and
//! [`Layer::without_geometry`]: which columns a read of that handle fetches
//! and carries. Everything, by default. Worth setting on a layer whose
//! geometries are large and whose attributes are what you are after, since
//! the geometry is otherwise fetched and copied into every row whether or
//! not anything looks at it.
//! - [`ConversionOptions`]: how stored values are read back, through
//! [`Layer::with_conversion_options`]: which `DATETIME` text forms are
//! accepted ([`DateTimeParsing`], default [`DateTimeParsing::Strict`]) and
//! whether a value its declared type does not strictly permit is read or
//! rejected ([`StorageStrictness`], default [`StorageStrictness::Lenient`]).
//!
//! Two settings are available outside the options types. [`Layer::write_all`] and
//! [`Layer::write_arrow`] take a `batch_size`, the number of rows sharing a
//! transaction, where `0` writes all of them in one.
//! [`Layer::with_geometry_type_validation`] checks each geometry against its
//! column's declared type while reading, and is **off** by default.
//!
//! Under the `arrow` feature, [`ArrowReadOptions`](arrow::ArrowReadOptions)
//! configures the columnar read: rows per batch
//! ([`batch_size`](arrow::ArrowReadOptions::batch_size), default
//! [`DEFAULT_BATCH_SIZE`](arrow::DEFAULT_BATCH_SIZE), 65,536), how many
//! threads may read at once ([`threads`](arrow::ArrowReadOptions::threads),
//! default `0`, meaning `min(4, available parallelism)`), and a ceiling on
//! the geometry bytes one batch may hold
//! ([`max_batch_bytes`](arrow::ArrowReadOptions::max_batch_bytes), default
//! [`default_max_batch_bytes`](arrow::default_max_batch_bytes),
//! `min(INT32_MAX, RAM / 4)`): the geometry column's Arrow offsets are
//! 32-bit, so no batch can address more than 2 GB of WKB, and a batch that
//! would cross the ceiling is emitted short so a layer of very large
//! geometries still reads. The columnar write has no options type of its own:
//! [`Layer::write_arrow_with`] takes the same [`BulkIndexOptions`] as
//! [`Layer::write_all_with`].
//!
//! Anything not covered here is reachable as SQL: [`GeoPackage::connection`]
//! hands back the underlying rusqlite connection.
//!
//! # What writes, and when
//!
//! Most of this crate divides cleanly into reads and writes, but three calls do
//! not, so the whole surface is tabulated here rather than left to be inferred
//! from the names. [`Layer::extent`] records what it had to measure;
//! [`Layer::repair_spatial_index`] writes only when there is something to
//! repair; and [`Layer::writer`] opens without writing, because SQLite's
//! `BEGIN DEFERRED` takes no lock, so the first failure lands on the first row.
//!
//! | Call | Writes to the file | On a read-only connection |
//! |---|---|---|
//! | [`Layer::features`], [`Layer::cursor`], [`Layer::features_in`], [`Layer::select`] | never | works |
//! | [`Layer::spatial_index_status`], [`Layer::has_spatial_index`] | never | works |
//! | [`Layer::audit_spatial_index`] | never | works |
//! | [`GeoPackage::contents`] | never | works |
//! | [`Layer::extent`] | only where the recorded bounds are unusable | works: measures, returns, records nothing |
//! | [`Layer::repair_spatial_index`] | only where the trigger set is not current | works where there is nothing to repair |
//! | [`Layer::recompute_extent`] | always | fails |
//! | [`Layer::create_spatial_index`], [`Layer::drop_spatial_index`], [`Layer::rebuild_spatial_index`] | always | fails |
//! | [`Layer::writer`] | on its row methods and its commit, not on the call | opens; the first row written fails |
//! | [`Layer::write_all`], [`Layer::write_arrow`] | always | fails |
//! | [`GeoPackage::tiles`], [`TilePyramid::get_tile`], [`TilePyramid::cursor`] | never | works |
//! | [`TilePyramid::validate`] | never | works |
//! | [`TilePyramid::put_tile`], [`TilePyramid::delete_tile`], [`TilePyramid::write_all`] | always | fails |
//! | [`TilePyramid::writer`] | on its tile methods and its commit, not on the call | opens; the first tile written fails |
//!
//! Reading an extent therefore modifies the file when the recorded bounds are
//! unusable, which is deliberate and matches GDAL: the file stops being wrong
//! for every later reader rather than only for this one. [`Layer::extent`]
//! documents why, and the two ways to avoid it.
//!
//! ## What can fail, and why
//!
//! - **A read-only connection**, per the table: [`Error::Sqlite`] carrying
//! SQLite's `SQLITE_READONLY`. [`Layer::extent`] is the exception that treats
//! this as a non-event, since it has an answer either way.
//! - **Another connection holding the write lock**: the statement waits up to
//! [`OpenOptions::busy_timeout`] and then fails with `SQLITE_BUSY`. Again
//! [`Layer::extent`] is the exception: contention means the measurement
//! describes a layer being changed underneath it, so the file keeps what it
//! had and the measurement is returned rather than an error. Note that SQLite
//! skips the wait entirely for a read-to-write upgrade that would deadlock
//! under a rollback journal, and for a stale snapshot under WAL.
//! - **No spatial index**: [`Error::NoSpatialIndex`] from
//! [`Layer::audit_spatial_index`] and [`Layer::rebuild_spatial_index`], and
//! from [`Layer::repair_spatial_index`] when there is nothing there at all.
//! - **No geometry column**: [`Error::NoGeometryColumn`] from
//! [`Layer::extent`], [`Layer::recompute_extent`], [`Layer::features_in`] and
//! [`Layer::cursor_in`].
//! - **A store that cannot be written for any other reason**, an unwritable
//! directory, a full disk, an I/O error: [`Error::ExtentPersist`] from
//! [`Layer::extent`], which carries the measurement so the answer is not lost
//! with the failure, and [`Error::Sqlite`] from everything else.
//!
//! # Reading untrusted files
//!
//! The `wkb` 0.9.2 reader this crate parses geometry with pre-allocates from
//! element counts read out of the blob without bounding them against the
//! buffer, so a malformed geometry declaring a `0xFFFFFFFF`-member collection
//! drives a multi-gigabyte allocation. The fix belongs upstream in
//! [georust/wkb](https://github.com/georust/wkb); until it lands and this crate
//! bumps its dependency, you should take care when parsing GeoPackage files from untrusted sources.
// `unsafe_code = "forbid"` and `missing_docs = "warn"` come from the
// workspace lints table (root Cargo.toml). This crate never uses `unsafe`; the
// planned `geopackage-ffi` crate (M3) is the sole intended exception, and will
// opt out of the workspace lints rather than relax them here.
pub use ;
pub use ;
pub use ;
pub use ExtensionRow;
pub use geopackage_core as core;
pub use GpkgVersion;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use OpenWarning;
pub use ;
pub use NewRelation;
pub use ;
pub use Srs;
pub use ;
pub use ;
pub use ;
pub use ;
use ;
use ;
use Path;
/// An open GeoPackage.
///
/// # Interchange-first close
///
/// A handle opened or created in [`JournalMode::Wal`] creates `-wal`/`-shm`
/// sidecar files while it is live. On [`GeoPackage::close`] and on drop such a
/// handle checkpoints the WAL and resets the file to [`JournalMode::Delete`], so
/// the resulting`.gpkg` is a single file. Prefer the explicit
/// [`GeoPackage::close`], which surfaces any error; the drop path is
/// best-effort and never panics. [`GeoPackage::into_connection`] opts out of
/// this guarantee: the returned connection keeps whatever journal mode it was
/// in.
/// Apply `options` to a freshly opened connection, returning the journal mode
/// the resulting handle is responsible for finalising.
///
/// The synchronous level, when set, is always applied. The journal mode is
/// applied only when `apply_journal` is true (false for a read-only connection,
/// which cannot change it) and a mode is set; an unset journal mode leaves the
/// file as it is. The returned [`JournalMode`] is [`JournalMode::Wal`] only when
/// WAL was actually applied, so only then do close/drop reset the file.
/// Checkpoint a WAL database fully into the main file and reset it to the
/// `DELETE` rollback journal, removing the `-wal`/`-shm` sidecars.
/// Read a 32-bit SQLite database-header pragma (`application_id` or
/// `user_version`) as a `u32`.
///
/// SQLite reports these fields sign-extended into an `i64`; the values are
/// 32-bit magics, so reinterpreting the low 32 bits as unsigned (which is what
/// the sign-extension preserves) is the intended read.
pub
pub
/// Resolve `name` to the actual SQLite table (or view) name, matching
/// case-insensitively.
///
/// SQLite object names resolve case-insensitively, but joins between catalogue
/// tables (`gpkg_contents`, `gpkg_geometry_columns`) compare the stored strings
/// exactly. This returns the physical name as SQLite stores it, identical to
/// `name` for a well-formed file, differing only in case for the wrong-case
/// files [`GeoPackage::open_lenient`] tolerates. `None` when no such table
/// exists under any casing.
pub
/// A row of `gpkg_contents`.
/// `gpkg_contents.data_type` values.