Introduction
GeoPackage is an OGC standard for storing geospatial data in a single SQLite database file. A GeoPackage can hold vector features, attribute tables and raster tiles, together with the spatial reference systems and spatial indexes that go with them. QGIS, GDAL and most other desktop GIS software can read it, and because it is just a file, there is no server to run.
This book shows you how to read and write GeoPackage files from Rust with the
geopackage crate, and how to use the gpkg command-line tool built on it.
The crates
The project is split into four crates:
geopackageis the library most people want. It creates and opens files, reads and writes feature and attribute layers, manages spatial indexes, handles tile pyramids and tiled gridded coverages, and can move data in and out as Apache Arrow record batches.geopackage-corecontains the parts of the format that don’t need a database, such as the geometry encoding and the table definitions. You only need it directly if you’re working with the format without SQLite.geopackage-cliprovidesgpkg, a command-line tool for inspecting, validating, indexing, repairing and copying files, and for reading tiles and coverages.geopackage-ffiis a C library over the same code, which passes data through the Arrow C Data Interface.
Installation
To use the library in a Rust project:
$ cargo add geopackage
By default, the library links against your system’s SQLite, which must include
the RTree module (SQLITE_ENABLE_RTREE). The SQLite that ships with macOS and
with Linux distributions has it. On Linux you also need the development
package, such as libsqlite3-dev on Debian and Ubuntu.
If you’d rather not depend on the system SQLite, or you’re on Windows, which
doesn’t have one, enable the bundled feature. It compiles its own copy of
SQLite, so you’ll need a C compiler:
$ cargo add geopackage --features bundled
Then set these SQLite compile flags in your project’s .cargo/config.toml:
[env]
LIBSQLITE3_FLAGS = "-USQLITE_ENABLE_MEMORY_MANAGEMENT -DSQLITE_DEFAULT_MEMSTATUS=0"
Without them, all connections in a process share one SQLite page cache behind one mutex, and the threads of a threaded Arrow read wait for each other.
Each GitHub release has binaries of the command-line tool for Linux, macOS and
Windows, which cargo binstall installs:
$ cargo binstall geopackage-cli
To build it from crates.io instead, set the SQLite compile flags in the environment:
$ LIBSQLITE3_FLAGS="-USQLITE_ENABLE_MEMORY_MANAGEMENT -DSQLITE_DEFAULT_MEMSTATUS=0" \
cargo install geopackage-cli
The tool uses the bundled SQLite by default. To link the system library
instead, pass --no-default-features.
All the crates need Rust 1.95 or newer.
How this book is organised
The book has four parts:
- The tutorial walks you through creating and querying your first GeoPackage. Start there if you’re new to the library.
- The how-to guides show you how to do specific tasks, such as adding a spatial index or copying features between files.
- The explanation chapters describe how parts of the format work, and why the library behaves as it does.
- The reference page links to the API documentation on
docs.rs, the C header, and a summary of the
gpkgcommands.
Still to come
These chapters haven’t been written yet:
- Migration notes for people coming from
gdal,gpkg-rsorrusqlite-gpkg, showing the equivalent calls and where the models differ. - A guide to the C library: building and linking
geopackage-ffi, its conventions for handles and errors, and passing data through the Arrow C Data Interface. Until then, the five example programs listed on the reference page are the best place to start. - More how-to guides, covering tile pyramids, attribute tables, metadata and the Related Tables Extension.
Your first GeoPackage
In this tutorial we start from an empty directory and build a GeoPackage file
containing four cities. We query it by bounding box from Rust, then inspect it
from the shell with the gpkg command-line tool.
You need a Rust toolchain, version 1.95 or newer, and an SQLite to link
against. On Linux (install libsqlite3-dev or your distribution’s equivalent)
and macOS that is the system library. On Windows, use the vendored copy via the
bundled feature (see the introduction).
Create the project
First, we make a new binary project and change into it:
$ cargo new cities
$ cd cities
Now we add two dependencies. geopackage is the library, and geo-types
provides our point geometries:
$ cargo add geopackage geo-types
The output ends with a summary of what was added:
Adding geopackage v0.14.4 to dependencies
Adding geo-types v0.7.20 to dependencies
The first build compiles every dependency, so it takes a minute or so. Later builds are quick.
Create the file
Open src/main.rs and replace its contents with this:
use geopackage::GeoPackage;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let gpkg = GeoPackage::create("cities.gpkg")?;
println!("created cities.gpkg");
gpkg.close()?;
Ok(())
}
GeoPackage::create fails rather than overwrite an existing file, so we delete
the previous file before each run. That way every run starts from nothing:
$ rm -f cities.gpkg && cargo run
The output should end with:
created cities.gpkg
Let’s check the directory:
$ ls
Cargo.lock Cargo.toml cities.gpkg src target
cities.gpkg is a single file, with no -wal or -shm files beside it. This
is the library’s default, so you can hand the file to someone else as it is.
Define a layer
The file has no layers yet, so it contains nothing. Next we declare a table
called cities with a text column, an integer column and a point geometry
column in EPSG:4326.
Add the two new use lines and the create_layer call, so that main.rs
reads:
use geopackage::core::types::{ColumnType, GeometryType};
use geopackage::{ColumnSpec, GeoPackage, GeometrySpec, TableSchemaBuilder};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let gpkg = GeoPackage::create("cities.gpkg")?;
println!("created cities.gpkg");
gpkg.create_layer(
&TableSchemaBuilder::new("cities")
.column(ColumnSpec::new("name", ColumnType::Text(None)))
.column(ColumnSpec::new("population", ColumnType::Integer))
.geometry(GeometrySpec::new(GeometryType::Point, 4326)),
)?;
println!("created layer \"cities\"");
gpkg.close()?;
Ok(())
}
Run it again:
$ rm -f cities.gpkg && cargo run
created cities.gpkg
created layer "cities"
create_layer also built an empty RTree spatial index on the geometry column,
which we will use shortly. The spatial index
explains why the index is built now, while empty, rather than after the rows
arrive.
Write four cities
Now we add some data. write_all takes an iterator of features and a batch
size. A batch size of 0 writes all of them in one transaction.
Add the geo_types::Point import, extend the geopackage import, and append
the write:
use geo_types::Point;
use geopackage::core::types::{ColumnType, GeometryType};
use geopackage::{ColumnSpec, GeoPackage, GeometrySpec, NewFeature, TableSchemaBuilder, Value};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let gpkg = GeoPackage::create("cities.gpkg")?;
println!("created cities.gpkg");
gpkg.create_layer(
&TableSchemaBuilder::new("cities")
.column(ColumnSpec::new("name", ColumnType::Text(None)))
.column(ColumnSpec::new("population", ColumnType::Integer))
.geometry(GeometrySpec::new(GeometryType::Point, 4326)),
)?;
println!("created layer \"cities\"");
let layer = gpkg.layer("cities")?;
layer.write_all(
vec![
NewFeature::new(
Point::new(-6.26, 53.35),
vec![Value::Text("Dublin".into()), Value::Integer(592_713)],
),
NewFeature::new(
Point::new(-0.13, 51.51),
vec![Value::Text("London".into()), Value::Integer(8_866_180)],
),
NewFeature::new(
Point::new(2.35, 48.86),
vec![Value::Text("Paris".into()), Value::Integer(2_048_472)],
),
NewFeature::new(
Point::new(13.40, 52.52),
vec![Value::Text("Berlin".into()), Value::Integer(3_662_381)],
),
],
0,
)?;
println!("wrote {} features", layer.features()?.len());
gpkg.close()?;
Ok(())
}
Run it:
$ rm -f cities.gpkg && cargo run
created cities.gpkg
created layer "cities"
wrote 4 features
The values in each NewFeature follow the order in which the columns were
declared. The geometry and the feature id are not in that list. Each is handled
separately.
Query by bounding box
Rather than read every city back, let’s ask a spatial question. features_in
returns the rows whose geometry intersects a box given in the layer’s own
coordinates.
Add BoundingBox to the import list, and add the loop after the write:
use geo_types::Point;
use geopackage::core::types::{ColumnType, GeometryType};
use geopackage::{
BoundingBox, ColumnSpec, GeoPackage, GeometrySpec, NewFeature, TableSchemaBuilder, Value,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let gpkg = GeoPackage::create("cities.gpkg")?;
println!("created cities.gpkg");
gpkg.create_layer(
&TableSchemaBuilder::new("cities")
.column(ColumnSpec::new("name", ColumnType::Text(None)))
.column(ColumnSpec::new("population", ColumnType::Integer))
.geometry(GeometrySpec::new(GeometryType::Point, 4326)),
)?;
println!("created layer \"cities\"");
let layer = gpkg.layer("cities")?;
layer.write_all(
vec![
NewFeature::new(
Point::new(-6.26, 53.35),
vec![Value::Text("Dublin".into()), Value::Integer(592_713)],
),
NewFeature::new(
Point::new(-0.13, 51.51),
vec![Value::Text("London".into()), Value::Integer(8_866_180)],
),
NewFeature::new(
Point::new(2.35, 48.86),
vec![Value::Text("Paris".into()), Value::Integer(2_048_472)],
),
NewFeature::new(
Point::new(13.40, 52.52),
vec![Value::Text("Berlin".into()), Value::Integer(3_662_381)],
),
],
0,
)?;
println!("wrote {} features", layer.features()?.len());
println!("features in the box:");
for feature in layer.features_in(BoundingBox::new(-7.0, 53.0, -6.0, 54.0))? {
let feature = feature?;
let name = feature.value("name").and_then(|v| v.as_str()).unwrap_or("");
let population = feature
.value("population")
.and_then(|v| v.as_i64())
.unwrap_or(0);
println!(" {name}: {population}");
}
gpkg.close()?;
Ok(())
}
Run it again:
$ rm -f cities.gpkg && cargo run
created cities.gpkg
created layer "cities"
wrote 4 features
features in the box:
Dublin: 592713
Only Dublin came back, although we wrote four cities. The box spans one degree
of longitude west of Greenwich and one degree of latitude north of 53, and
Dublin is the only one of our cities inside it. The spatial index that
create_layer built answered the query. A layer without an index returns
exactly the same rows from a full scan.
Read the geometries back
So far we have read back the name and population, but not the point itself. A
feature returns its geometry lazily. feature.geometry() parses the stored
blob into a wrapper over its bytes, and to_geo on that wrapper converts it to
an owned
geo_types::Geometry.
This mirrors the write side, which accepted our geo_types::Point values
directly. to_geo returns an Option because a GeoPackage can hold curve
types that geo-types cannot represent. Our points are not among them.
Extend the loop body to fetch the location:
use geo_types::Point;
use geopackage::core::types::{ColumnType, GeometryType};
use geopackage::{
BoundingBox, ColumnSpec, GeoPackage, GeometrySpec, NewFeature, TableSchemaBuilder, Value,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let gpkg = GeoPackage::create("cities.gpkg")?;
println!("created cities.gpkg");
gpkg.create_layer(
&TableSchemaBuilder::new("cities")
.column(ColumnSpec::new("name", ColumnType::Text(None)))
.column(ColumnSpec::new("population", ColumnType::Integer))
.geometry(GeometrySpec::new(GeometryType::Point, 4326)),
)?;
println!("created layer \"cities\"");
let layer = gpkg.layer("cities")?;
layer.write_all(
vec![
NewFeature::new(
Point::new(-6.26, 53.35),
vec![Value::Text("Dublin".into()), Value::Integer(592_713)],
),
NewFeature::new(
Point::new(-0.13, 51.51),
vec![Value::Text("London".into()), Value::Integer(8_866_180)],
),
NewFeature::new(
Point::new(2.35, 48.86),
vec![Value::Text("Paris".into()), Value::Integer(2_048_472)],
),
NewFeature::new(
Point::new(13.40, 52.52),
vec![Value::Text("Berlin".into()), Value::Integer(3_662_381)],
),
],
0,
)?;
println!("wrote {} features", layer.features()?.len());
println!("features in the box:");
for feature in layer.features_in(BoundingBox::new(-7.0, 53.0, -6.0, 54.0))? {
let feature = feature?;
let name = feature.value("name").and_then(|v| v.as_str()).unwrap_or("");
let population = feature
.value("population")
.and_then(|v| v.as_i64())
.unwrap_or(0);
let location = match feature.geometry()?.and_then(|g| g.to_geo()) {
Some(geo_types::Geometry::Point(p)) => format!("{}, {}", p.x(), p.y()),
_ => "no location".into(),
};
println!(" {name}: {population} at {location}");
}
gpkg.close()?;
Ok(())
}
Run it again:
$ rm -f cities.gpkg && cargo run
created cities.gpkg
created layer "cities"
wrote 4 features
features in the box:
Dublin: 592713 at -6.26, 53.35
The point comes back exactly as we wrote it. You don’t have to convert,
though. An algorithm written against the geo-traits interfaces can read
coordinates directly from the wrapper, without ever creating an owned geometry.
The geometry chapter covers this.
Look at the file from outside
So far only our own program has reported on the file. Let’s check it with a separate tool. Install the command-line tool, which downloads a binary from the project’s GitHub release:
$ cargo binstall geopackage-cli
If you don’t have cargo binstall, run cargo install geopackage-cli to build
the tool from source instead.
Then ask it what our file contains:
$ gpkg info cities.gpkg
cities.gpkg
version: 1.4
layer "cities" (features)
rows: 4
geometry: geom (POINT, srs_id 4326)
srs: WGS 84 geodetic (EPSG:4326)
index: current
columns:
fid INTEGER PRIMARY KEY
name TEXT
population INTEGER
geom POINT
extensions:
gpkg_rtree_index cities.geom implemented [write-only]
rows: 4 matches what our program reported, and index: current is the spatial index we never named: create_layer built it, and it
uses the GeoPackage 1.4 trigger set. We never declared the fid and geom
columns either. fid is the default primary key and geom the default
geometry column name. You can change both with
TableSchemaBuilder.
Let’s also check that the file is well formed:
$ gpkg validate cities.gpkg
cities.gpkg
no findings (this crate's checks; the OGC ETS is the authority)
What we have built
We wrote a program that creates a GeoPackage, declares an indexed point layer,
writes features into it, answers a spatial query and reads the geometries back
as geo-types values. We then confirmed the result with a separate tool.
cities.gpkg is an ordinary GeoPackage, so QGIS, GDAL and anything else that
reads the format will open it.
From here:
- The how-to guides cover specific tasks: indexing an existing layer, repairing a file, copying features between files, reading a layer as Arrow batches, and validating a file.
- The explanation chapters cover why the extent, the transactions, the spatial index, the geometry encoding and tiled gridded coverages work the way they do.
- The reference page points at the full API documentation.
How to add a spatial index to an existing layer
A feature layer without an RTree index answers bounding-box queries by a full scan. This guide shows you how to build the index so those queries can use it.
From the shell
If the file is on disk and you don’t need to do anything else to it:
$ gpkg index roads.gpkg roads
roads: index built over 1204553 rows
gpkg index only builds an index where none exists. If the layer already has
one, the command reports what it found and exits non-zero:
$ gpkg index roads.gpkg roads
gpkg: roads already has an index (legacy trigger set); run `gpkg repair`
In that case, see How to repair a file’s spatial indexes.
From Rust
Open the file read-write and take the layer handle:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::GeoPackage;
let gpkg = GeoPackage::open("roads.gpkg")?;
let layer = gpkg.layer("roads")?;
Ok(()) }
Check the status first. create_spatial_index fails with
Error::SpatialIndexExists if the rtree_<table>_<column> virtual table
already exists, whatever state it is in:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{GeoPackage, SpatialIndexStatus};
let gpkg = GeoPackage::open("roads.gpkg")?;
let layer = gpkg.layer("roads")?;
match layer.spatial_index_status()? {
SpatialIndexStatus::Absent => layer.create_spatial_index()?,
SpatialIndexStatus::Current => {}
// Present but not usable: repair it instead of building over it.
SpatialIndexStatus::Legacy | SpatialIndexStatus::Stale => {
layer.repair_spatial_index()?
}
_ => {}
}
Ok(()) }
create_spatial_index creates the virtual table, installs the GeoPackage 1.4
trigger set, populates the index from the existing rows, and registers
gpkg_rtree_index in gpkg_extensions, all in one transaction. Like the
triggers, it skips NULL and empty geometries.
Choose the build path explicitly
The index is populated by one of two paths, chosen by comparing the row count
with BulkIndexOptions::bulk_threshold (10,000 rows by default). To choose the
path yourself, use create_spatial_index_with:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{BulkIndexOptions, BulkVerification};
use geopackage::GeoPackage;
let gpkg = GeoPackage::open("roads.gpkg")?;
let layer = gpkg.layer("roads")?;
// Force the bulk build, and verify the result.
layer.create_spatial_index_with(
BulkIndexOptions::always_bulk().with_verification(BulkVerification::Structure),
)?;
Ok(()) }
Set a verification level if a bad build must be caught at build time rather than found later:
BulkVerification::Noneis the default and checks nothing.BulkVerification::Contentsreads every entry back and checks it against the envelopes accumulated while writing.BulkVerification::Structureaddsrtreecheckover the tree.BulkVerification::Databaseadds a whole-databasePRAGMA integrity_check, which is O(database) rather than O(index).
Every level above None enables an automatic fallback to the per-row
triggered build. A failed check makes the build slower, not wrong.
If you will append many rows to the layer after the build, lower the node fill so that the first append into a node doesn’t split it immediately:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{BulkIndexOptions, GeoPackage};
let gpkg = GeoPackage::open("roads.gpkg")?;
let layer = gpkg.layer("roads")?;
layer.create_spatial_index_with(BulkIndexOptions::default().with_fill_factor(0.7))?;
Ok(()) }
Index a layer as it is written
If the rows are not in the file yet, don’t build the index afterwards. Leave
TableSchemaBuilder::spatial_index at its default of true, which creates an
empty index, and let write_all fill it. The bulk path reuses the envelopes
computed while encoding the geometries, which is between 20% and 47% cheaper
than a separate build.
Then
- Confirm the result with
gpkg info <file>, whoseindex:line reports the status, or withLayer::spatial_index_status. - The spatial index: structure, contents, and the bulk build explains why checking an index’s structure and checking its contents differ in cost, and what the bulk build does.
- API reference:
Layer::create_spatial_index,Layer::create_spatial_index_with,BulkIndexOptions,BulkVerification.
How to repair a file’s spatial indexes
An index in a file you receive may be maintained by a pre-1.4 trigger set, or
may have lost some or all of its triggers. This library does not trust an index
that has lost triggers for queries, so bounding-box reads fall back to a full
scan until the index is repaired. A complete pre-1.4 set is still used, but
corrupts the index under UPSERT.
This guide shows you how to repair it.
Repair is never automatic. The library rewrites an existing trigger set only when you ask it to.
From the shell
To repair every layer in a file that needs it:
$ gpkg repair places.gpkg
points: legacy trigger set index repaired to the 1.4 trigger set
To repair one named layer, add its name:
$ gpkg repair places.gpkg points
If nothing needs repairing, the command says so and exits zero:
$ gpkg repair places.gpkg
nothing to repair
gpkg repair leaves a layer with no index alone, because an unindexed layer
reads correctly. If you want an index built, see
How to add a spatial index to an existing layer.
From Rust
Open the file read-write, preferably with the lenient open. A file that needs
repair already has something wrong with it, and a strict open can fail on a
legacy application_id before you reach the index.
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{GeoPackage, SpatialIndexStatus};
let gpkg = GeoPackage::open_lenient("places.gpkg")?;
for layer in gpkg.layers()? {
if layer.geometry_column().is_none() {
continue;
}
match layer.spatial_index_status()? {
SpatialIndexStatus::Legacy | SpatialIndexStatus::Stale => {
layer.repair_spatial_index()?;
}
// Current needs nothing; Absent is a choice, not a defect.
_ => {}
}
}
Ok(()) }
repair_spatial_index drops every RTree trigger on the table, installs the
1.4 set, and rebuilds the index content, in one transaction. It returns
without doing anything when the index is already current, and fails with
Error::NoSpatialIndex when there is no index to repair.
If the structure is right but the contents are in doubt
spatial_index_status checks only the structure. It cannot tell whether the
entries agree with the geometries. An index can be Current and still be
wrong if another tool wrote rows with the triggers disabled, or
populated it incompletely. To check the contents, audit the index:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::GeoPackage;
let gpkg = GeoPackage::open_lenient("places.gpkg")?;
let layer = gpkg.layer("points")?;
let audit = layer.audit_spatial_index()?;
if !audit.is_consistent() {
eprintln!(
"{} missing, {} extra, {} not covering",
audit.missing, audit.extra, audit.not_covering
);
layer.rebuild_spatial_index()?;
}
Ok(()) }
The audit reads every geometry in the layer, so run it as a deliberate check,
not before each query. It writes nothing. To fix what it finds, call
rebuild_spatial_index. It does unconditionally what the repair does only when
the structure is wrong.
gpkg validate runs the same audit across the whole file. This is the cheaper
way to find out whether any layer needs rebuilding. See
How to validate a GeoPackage and act on the findings.
Then
- The spatial index: structure, contents, and the bulk build explains why repair is never automatic, and why a legacy trigger set is worth replacing.
- API reference:
Layer::spatial_index_status,Layer::repair_spatial_index,Layer::audit_spatial_index,Layer::rebuild_spatial_index,SpatialIndexAudit.
How to repair geometry and datetime encodings
Some writers store values in forms that GDAL reads but that the GeoPackage standard does not give them:
- a geometry whose WKB gives Z or M by a high-bit flag in a type code
(
0x80000003for a polygon with Z), where a GeoPackage body uses the ISO code (1003); DATETIMEtext in another ISO 8601 form, such as2017-08-01T00:00:00.0Z, where the standard gives2017-08-01T00:00:00.000Z.
This library reads both, but by default it rejects the second, and a reader
that follows the standard can reject either. gpkg validate reports them as
NonIsoWkbTypeCode and NonStandardDateTime. This guide shows you how to
rewrite them in the standard form.
Repair is never automatic, and it changes the file in place. Work on a copy if you need to keep the original.
From the shell
gpkg repair makes both repairs, as well as the spatial index repair, on
every feature layer and attribute table that needs them:
$ gpkg repair boundaries.gpkg
boundaries: 9071 geometries rewritten with ISO WKB type codes
boundaries: 136065 DATETIME values rewritten in the GeoPackage form
To repair one layer or attribute table, add its name:
$ gpkg repair boundaries.gpkg boundaries
From QGIS
With the GeoPackage toolkit plugin installed, run Repair geometry and
datetime encodings from the Processing toolbox or the plugin’s menu. Leave
Layer or table empty to repair every table. The report has one row per
table, with how many geometries and DATETIME values were rewritten.
Validate GeoPackage names the algorithm that repairs each finding in its
plugin_algorithm column.
From Rust
Open the file read-write with the lenient open, then call the two repairs on each layer. Both return how many values they rewrote.
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::GeoPackage;
let gpkg = GeoPackage::open_lenient("boundaries.gpkg")?;
for layer in gpkg.layers()? {
let geometries = layer.repair_wkb_type_codes()?;
let datetimes = layer.repair_datetimes()?;
println!("{}: {geometries} geometries, {datetimes} datetimes", layer.table_name());
}
Ok(()) }
An attribute table can have DATETIME columns too. Open it with
GeoPackage::attributes and call repair_datetimes on it.
Each repair runs in one transaction, and writes only the rows that need it. The rewritten geometries keep their coordinates and SRS id, and get an envelope in their header. The RTree triggers keep the spatial index in step.
What the repairs leave alone
- A geometry whose header or body cannot be read.
gpkg validatereports it asUnreadableGeometry; its data has to come from the tool that wrote it. - A WKB type code with the EWKB SRID flag, which this library does not read.
DATETIMEtext that the lenient parser does not read, or that has a part smaller than a millisecond, which the standard form would lose.DATEcolumns, which have only one form.
Run gpkg validate afterwards to see anything that is left.
Then
- How to validate a GeoPackage and act on the findings
- How to repair a file’s spatial indexes
- API reference:
Layer::repair_wkb_type_codes,Layer::repair_datetimes,curve::to_iso_wkb.
How to copy features between files without decoding geometry
If you read a geometry into a geo-types value and write it back, every
coordinate is parsed for nothing, and the non-linear curve types are lost
entirely, because geo-traits has no representation for an arc. This guide
copies rows between files as WKB bytes instead. Nothing is re-encoded, and a
CIRCULARSTRING arrives unchanged.
From the shell
For a whole file, gpkg copy already works this way:
$ gpkg copy places.gpkg places-copy.gpkg
It copies feature and attribute layers, with their schemas, spatial reference systems and rows, and a spatial index wherever the source had one. It does not copy tile pyramids, tiled gridded coverages or the extension tables, and it names whatever it left behind at the end.
Mirror the source layer
In Rust, start with the source file open and the destination file created.
The destination’s geometry column must match the source in three respects:
the geometry type, the z and m flags, and the SRS. These are easy to leave
at their defaults, and the copy then fails on the first row.
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::core::types::ColumnType;
use geopackage::{ColumnSpec, GeoPackage, GeometrySpec, TableSchemaBuilder};
let src = GeoPackage::open_read_only("places.gpkg")?;
let dst = GeoPackage::create("subset.gpkg")?;
let source = src.layer("points")?;
let geom = source.geometry_column().expect("a feature layer");
// The SRS must exist in the destination before a layer can refer to it.
// `add_srs` does nothing if it is already there.
if let Some(srs) = src.srs(geom.srs_id)? {
dst.add_srs(&srs)?;
}
let mut builder = TableSchemaBuilder::new("points").geometry(
GeometrySpec::new(geom.geometry_type, geom.srs_id)
.column_name(geom.column_name.clone())
.z(geom.z)
.m(geom.m),
);
// Copy every column except the geometry and the primary key. Those two are
// declared elsewhere, and `Feature::values` skips them.
for column in &source.schema().columns {
if column.is_primary_key() || column.name == geom.column_name {
continue;
}
// A declared type outside the spec vocabulary parses to `None`. BLOB is
// the typeless case under SQLite's affinity rules.
let column_type = column
.column_type
.clone()
.unwrap_or(ColumnType::Blob(None));
builder = builder.column(ColumnSpec::new(column.name.clone(), column_type));
}
dst.create_layer(&builder)?;
Ok(()) }
If you leave z and m at their defaults, the dimension is declared
prohibited, and the first geometry with a Z fails. If the source’s primary key
is not named fid, also pass its name to TableSchemaBuilder::primary_key.
Copy the rows by their bytes
Feature::geometry_bytes returns the stored GPB blob, including its header.
gpb::body_offset reads the header to find where the ISO WKB body starts.
FeatureWriter::insert_wkb copies the body into the new blob without
re-serialising it. The geometry is never parsed.
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::core::gpb;
use geopackage::GeoPackage;
let src = GeoPackage::open_read_only("places.gpkg")?;
let dst = GeoPackage::create("subset.gpkg")?;
let source = src.layer("points")?;
let target = dst.layer("points")?;
let mut writer = target.writer()?;
let mut cursor = source.cursor()?;
for feature in cursor.features()? {
let feature = feature?;
let values: Vec<_> = feature.values().collect();
match feature.geometry_bytes() {
Some(blob) => {
let offset =
gpb::body_offset(blob).map_err(|e| geopackage::Error::Core(e.into()))?;
writer.insert_wkb(Some(feature.fid()), &blob[offset..], &values)?;
}
// A NULL geometry cell, or an attribute table.
None => {
writer.insert_row(Some(feature.fid()), &values)?;
}
}
}
writer.commit()?;
Ok(()) }
Feature::values yields borrowed ValueRefs, so text and blob cells bind
into the destination statement without being copied.
To update rows in place instead of inserting them, use update_wkb. It gives
the same guarantee.
For a long copy
A single writer is a single transaction, so the journal grows for the whole
length of the copy. Commit periodically and open a new writer, as gpkg copy does every 10,000 rows. Add a counter to the loop above, and end each
batch with:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::GeoPackage;
let dst = GeoPackage::create("subset.gpkg")?;
let target = dst.layer("points")?;
let mut writer = target.writer()?;
let mut in_batch = 0usize;
const BATCH: usize = 10_000;
in_batch += 1;
if in_batch >= BATCH {
writer.commit()?;
writer = target.writer()?;
in_batch = 0;
}
Ok(()) }
If the copy then fails part-way, only the current batch is rolled back, not the whole layer.
If you have opened your own transaction on GeoPackage::connection, these
commits only stage the rows, and you must issue the durable commit yourself. See
Transactions.
Then
- Geometry storage: GPB, WKB, and curve types
explains what the GPB header contains, why the WKB body passes through
untouched, and what
geo-traitscannot represent. - API reference:
Feature::geometry_bytes,FeatureWriter::insert_wkb,FeatureWriter::update_wkb,gpb::body_offset.
How to read a layer as Arrow record batches
The columnar path builds Arrow arrays directly from the statement’s column
values, without creating a feature object for each row. This guide shows you
how to read a layer as RecordBatches, filter the read, and pass the result to
the rest of the Arrow ecosystem.
Enable the feature
The columnar paths are off by default, because they add the arrow-array and
arrow-schema dependencies, which you don’t need if you only use the scalar
API:
$ cargo add geopackage --features arrow
Read the whole layer
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::GeoPackage;
use geopackage::arrow::ArrowReadOptions;
let gpkg = GeoPackage::open_read_only("roads.gpkg")?;
let layer = gpkg.layer("roads")?;
for batch in layer.read_arrow(ArrowReadOptions::default())? {
let batch = batch?;
println!("{} rows", batch.num_rows());
}
Ok(()) }
Attribute columns follow the type mapping documented on the
arrow module.
The geometry column is WKB with the geoarrow.wkb extension name, and its
metadata includes the CRS as PROJJSON. Batches arrive in primary-key order,
whether or not the read is threaded.
Filter the read
Three variants take filters. All three are single-threaded:
-
To read the rows intersecting a box, use
read_arrow_in:fn main() -> Result<(), Box<dyn std::error::Error>> { use geopackage::{BoundingBox, GeoPackage}; use geopackage::arrow::ArrowReadOptions; let gpkg = GeoPackage::open_read_only("roads.gpkg")?; let layer = gpkg.layer("roads")?; let bbox = BoundingBox::new(-7.0, 53.0, -6.0, 54.0); let batches = layer.read_arrow_in(bbox, ArrowReadOptions::default())?; Ok(()) }It uses the RTree index if the layer has one, and a full scan if not. Either way, it re-tests every candidate against its true
f64envelope. The candidate set is fixed when the read is opened, so a row inserted while you are still pulling batches is not returned. -
To filter on attributes, use
read_arrow_where, which appends a raw SQLWHEREclause. The library trusts the clause and does not parse or sanitise it. Its placeholders are?1to?N, bound in slice order:fn main() -> Result<(), Box<dyn std::error::Error>> { use geopackage::{GeoPackage, ValueRef}; use geopackage::arrow::ArrowReadOptions; let gpkg = GeoPackage::open_read_only("roads.gpkg")?; let layer = gpkg.layer("roads")?; let batches = layer.read_arrow_where( "class = ?1", &[ValueRef::Text("motorway")], ArrowReadOptions::default(), )?; Ok(()) }You can also use it to read a single row in columnar form: pass
fid = ?1with the key as its parameter. -
To apply both at once, use
read_arrow_in_where, which intersects the two.
Tune the read
ArrowReadOptions controls three things:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::arrow::ArrowReadOptions;
let options = ArrowReadOptions::with_batch_size(16_384)
.with_threads(1)
.with_max_batch_bytes(256 * 1024 * 1024);
Ok(()) }
with_batch_size creates a new set of options from the defaults. The other
two chain onto any options value.
batch_sizeis rows per batch, 65,536 by default.threadsdefaults tomin(4, available parallelism). Set it to1to keep the read on your own thread. The read uses threads only when the database is a file, the primary key spans at least two batches of values, and the layer reads every column (nowith_columnsorwithout_geometry). Otherwise it runs single-threaded rather than failing. On threads, a batch holds fewer rows where the key has gaps.max_batch_byteslimits the geometry bytes in one batch, and defaults tomin(INT32_MAX, RAM / 4). The geometry column’s Arrow offsets are 32-bit, so 2 GB is a hard ceiling. A batch that would cross the limit is emitted with fewer rows. Lower it for a layer of very large geometries, where the default multiplied by the thread count is more memory than you want in use at once.
Hand the batches to something else
ArrowBatches implements RecordBatchReader, so you can pass it to anything
in the Arrow ecosystem that consumes one, such as a Parquet writer or the Arrow
C Data Interface:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::GeoPackage;
use geopackage::arrow::ArrowReadOptions;
use arrow_array::RecordBatchReader;
let gpkg = GeoPackage::open_read_only("roads.gpkg")?;
let layer = gpkg.layer("roads")?;
let batches = layer.read_arrow(ArrowReadOptions::default())?;
let schema = batches.schema();
Ok(()) }
Copy a layer through Arrow
Layer::arrow_schema and TableSchemaBuilder::from_arrow_schema apply the
same type mapping in opposite directions, so you can copy a layer without
restating its schema:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{GeoPackage, TableSchemaBuilder};
use geopackage::arrow::ArrowReadOptions;
let src = GeoPackage::open_read_only("roads.gpkg")?;
let roads = src.layer("roads")?;
let dst = GeoPackage::create("copy.gpkg")?;
let schema = roads.arrow_schema()?;
dst.create_layer(&TableSchemaBuilder::new("roads").from_arrow_schema(&schema)?)?;
let batches = roads.read_arrow(ArrowReadOptions::default())?;
dst.layer("roads")?.write_arrow(batches, 0)?;
Ok(()) }
Here the geometry column is declared with its source type. A layer built from
an Arrow schema alone gets GEOMETRY, because the GeoArrow WKB encoding does
not record a specific type.
Then
- Each batch is a separate query, paginated on the primary key, so a
concurrent writer can change the table between batches. If you need one
snapshot of the whole layer, open your own transaction on
GeoPackage::connection. See Transactions. - API reference:
Layer::read_arrow,Layer::read_arrow_in,Layer::read_arrow_where,ArrowReadOptions, and thearrowmodule for the type mapping.
How to read values from a coverage
A tiled gridded coverage stores measurements, such as elevations, as TIFF or 16-bit PNG tiles. This guide shows you how to look up the value at a position, calculate a tile’s statistics, and check that a coverage contains no NaN or infinite samples.
Enable the feature
The decoders are off by default, because they add the tiff and png
dependencies, which you don’t need if you only read coverages as bytes:
$ cargo add geopackage --features coverage-samples
Look up the value at a position
Coverage::value_at takes a zoom level and a position in the coverage’s
spatial reference system, and returns the value there, with the tile’s and the
coverage’s scale and offset applied:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{GeoPackage, Interpolation};
let gpkg = GeoPackage::open_read_only("dem.gpkg")?;
let coverage = gpkg.coverage("elevation")?;
let zoom = *coverage.zoom_levels().last().expect("a zoom level");
match coverage.value_at(zoom, 1250.0, 4875.0, Interpolation::Bilinear)? {
Some(value) => println!("{value} {}", coverage.ancillary().uom.as_deref().unwrap_or("")),
None => println!("no data here"),
}
Ok(()) }
None means that there is no value: the position is outside the extent, the
coverage stores no tile there, or a sample the lookup needs is the coverage’s
data_null. A bilinear lookup needs the four samples around the position, so
one null among them gives None, as does a missing tile next to the position.
Look up many positions
Each call to value_at decodes the tiles it reads. For a profile along a line,
or any set of positions, open a sampler, which keeps the tiles it has decoded:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{GeoPackage, Interpolation};
let gpkg = GeoPackage::open_read_only("dem.gpkg")?;
let coverage = gpkg.coverage("elevation")?;
let mut sampler = coverage.sampler(0)?;
for step in 0..100 {
let x = 100.0 + f64::from(step) * 50.0;
let height = sampler.value_at(x, 3000.0, Interpolation::Nearest)?;
println!("{x}: {height:?}");
}
Ok(()) }
Where the samples are
The coverage’s grid_cell_encoding says where in its cell each sample sits,
and the lookup follows it:
grid-value-is-center, the default: the sample is at the centre of the cell.grid-value-is-corner: the sample is at the lower-left corner of the cell. The extension does not name the corner, and this library reads the lower-left, as NGA’s implementation does.grid-value-is-area: the value holds across the whole cell, so a bilinear lookup returns the cell’s value, as a nearest lookup does.
An encoding the extension does not define is read as the default.
Write tiles with their statistics
CoverageWriter::put_with_statistics decodes a payload before it writes it,
refuses one that contains NaN or an infinity
(Requirement 21), and records
the minimum, maximum, mean and standard deviation in the tile’s ancillary row:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::core::tiles::TileCoord;
use geopackage::{GeoPackage, TileAncillary};
let gpkg = GeoPackage::open("dem.gpkg")?;
let coverage = gpkg.coverage("elevation")?;
let payload: Vec<u8> = Vec::new();
let mut writer = coverage.writer()?;
writer.put_with_statistics(TileCoord::new(0, 0, 0), &payload, &TileAncillary::defaults())?;
writer.commit()?;
Ok(()) }
The statistics are of values, after the scale and offset, as the extension
specifies. Samples equal to data_null are left out, and the standard
deviation is that of the population. GDAL records its statistics in the same
way.
Check a coverage’s samples
With the feature enabled, GeoPackage::validate decodes every coverage tile
and reports tiles with a NaN or infinite sample as
Requirement 21, and tiles
whose data does not decode as the requirement of their encoding. To check one
tile yourself, decode it and call check_samples:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::core::tiles::TileCoord;
use geopackage::GeoPackage;
let gpkg = GeoPackage::open_read_only("dem.gpkg")?;
let coverage = gpkg.coverage("elevation")?;
if let Some(samples) = coverage.samples(TileCoord::new(0, 0, 0))? {
coverage.check_samples(&samples)?;
}
Ok(()) }
Decode larger tiles
A tile’s header states its size, and a decoder allocates for that size before
it reads the data. So a decode first compares the header with the tile’s zoom
level, as GDAL does, and refuses a tile of any other size. On top
of that, it refuses a tile of more than 4096 by 4096 samples, which is the
largest tile GDAL writes by default: these calls return Error::Tile with
TileError::PayloadTooLarge for it, and validate skips its samples.
If your coverages have larger tiles, raise the limit when you open the file. Each sample costs eight bytes decoded:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::OpenOptions;
let gpkg = OpenOptions::new()
.max_decoded_samples(8192 * 8192)
.open_read_only("dem.gpkg")?;
let _ = gpkg;
Ok(()) }
Decode without SQLite
The decode, the statistics and the lookup arithmetic are in
geopackage-core, under its own coverage-samples feature, so code that
reads tiles some other way can use them. You supply the bytes of a tile and
its ancillary rows; SampleLookup says which samples a position reads, and
you fetch them:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::core::coverage::{
CoverageAncillary, Interpolation, SampleLookup, TileAncillary, decode_samples,
};
use geopackage::core::tiles::{TileMatrix, TileMatrixSet};
let tile_data: Vec<u8> = Vec::new();
// One 256 by 256 tile over its extent, from your own reader.
let set = TileMatrixSet::new(3857, 0.0, 0.0, 256.0, 256.0);
let matrix = TileMatrix::new(0, 1, 1, 256, 256, 1.0, 1.0);
let coverage = CoverageAncillary::new("elevation", "float");
let tile = TileAncillary::defaults();
let samples = decode_samples(&tile_data)?;
if let Some(lookup) =
SampleLookup::new(&set, &matrix, &coverage, 100.0, 50.0, Interpolation::Bilinear)
{
let value = lookup.value(|sample| {
// This grid has one tile, so every sample is in it.
let (_, column, row) = sample.tile(&matrix).expect("a positive tile size");
Ok::<_, std::convert::Infallible>(samples.value(column, row, &coverage, &tile))
})?;
println!("{value:?}");
}
Ok(()) }
How to validate a GeoPackage and act on the findings
GeoPackage::validate checks a file in one pass and returns what is wrong
with it. It modifies nothing. This guide shows you how to run the check, read
the result, and apply the repairs it names.
The report covers only what these checks can see. It does not establish conformance in every respect the spec defines. For that, the OGC executable test suite remains the authority.
In a script or a CI job
$ gpkg validate places.gpkg
places.gpkg
warning: spatial index on "points" is maintained by a pre-1.4 or mixed trigger set
repair: upgrade the trigger set with Layer::repair_spatial_index
0 errors, 1 warning, 0 advisories
Exit codes:
- Zero when there are no findings, or only warnings and advisories.
- Non-zero when any finding is an error. An error means a reader can get a wrong answer from the file.
To fail on warnings too, add --strict:
$ gpkg validate --strict places.gpkg
$ echo $?
1
The command opens the file read-only and leniently, so a file with problems is reported on rather than rejected.
In Rust
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{GeoPackage, Severity};
let gpkg = GeoPackage::open_read_only_lenient("places.gpkg")?;
let findings = gpkg.validate()?;
for finding in &findings {
println!("{}: {finding}", finding.severity());
if let Some(repair) = finding.repair() {
println!(" repair: {repair}");
}
}
let failed = findings.iter().any(|f| f.severity() == Severity::Error);
Ok(()) }
Findings are sorted most severe first, in a stable order within each severity. If you diff the output of two runs, any differences are in the findings, not in their order.
Read the severities
Severity reflects the consequence of a problem, not how hard it is to fix:
Severity::Error: a reader can get a wrong answer. For example, agpkg_contentsrow naming a missing table, a spatial index that no longer describes its rows, or a metadata or relation row that points at something that no longer exists.Severity::Warning: the file reads correctly but does not follow the current spec. For example, a pre-1.2application_id, a pre-1.4 index trigger set, an extension these checks cannot identify, or a tile pyramid that breaks the matrix rules.Severity::Advisory: a remark, not a defect. The advisory case is a feature table with no spatial index. It reads correctly, and someone may have chosen not to index the layer.
Apply the repairs
Finding::repair returns the advice as text, naming the method that performs
it. None means this library cannot make the fix. It needs the writer that
produced the file, or a decision about the data that the library should not
make for you. To act on the findings instead of printing them, match on the
variant:
fn main() -> Result<(), Box<dyn std::error::Error>> {
use geopackage::{Finding, GeoPackage};
let gpkg = GeoPackage::open_lenient("places.gpkg")?;
for finding in gpkg.validate()? {
match finding {
// Contents disagree with the geometries: rebuild.
Finding::SpatialIndexOutOfStep { table_name, .. } => {
gpkg.layer(&table_name)?.rebuild_spatial_index()?;
}
// Structure is a pre-1.4 or mixed trigger set, or the virtual
// table or its triggers are missing: repair.
Finding::LegacySpatialIndexTriggers { table_name }
| Finding::StaleSpatialIndex { table_name } => {
gpkg.layer(&table_name)?.repair_spatial_index()?;
}
// An advisory, so build one only if you want the queries indexed.
Finding::NoSpatialIndex { table_name } => {
gpkg.layer(&table_name)?.create_spatial_index()?;
}
_ => {}
}
}
Ok(()) }
The handle must be open read-write for any of these repairs. Finding is
#[non_exhaustive], so a variant added in a later version falls through to the
catch-all arm instead of breaking the build.
To repair indexes without validating the whole file first, see How to repair a file’s spatial indexes.
Then
- The spatial index: structure, contents, and the bulk build explains what an audit checks that a status cannot.
- API reference:
GeoPackage::validate,Finding,Severity.
How to install the QGIS plugin and add a layer through it
The GeoPackage Toolkit plugin puts this library in QGIS. It adds a data
provider, geopackage_rs, which reads and edits GeoPackage layers through
the library instead of GDAL. It also adds Processing algorithms that
validate and repair files, and that read coverages. This guide shows you
how to install it from the project’s plugin repository, and how to add a
layer through its provider.
The plugin works in QGIS 3.28 and later, on Linux (x86_64 and aarch64, glibc 2.28 or later), macOS and Windows (x86_64). It needs nothing else installed. It is experimental: work on copies of files you can’t lose.
Install the plugin
- In QGIS, open Plugins → Manage and Install Plugins, and select Settings.
- Tick Show also experimental plugins.
- Under Plugin Repositories, select Add, and enter:
- Name:
GeoPackage Toolkit - URL:
https://urschrei.github.io/geopackage/qgis/plugins.xml
- Name:
- Select OK, then Reload all repositories.
- Select All, search for
GeoPackage Toolkit, and select Install Plugin.
QGIS then offers each new release under Upgradeable.
If you can’t reach the repository from QGIS, download
gpkg_toolkit-<version>.zip from the newest qgis-plugin-v<version>
release on GitHub, and
install it with Install from ZIP. Install the zip as it is: don’t
unpack it.
Check which provider serves the layers
Open View → Panels → Log Messages, and select the GeoPackage Toolkit tab. At startup the plugin writes one of these:
Using the native data provider: <path>: the compiled provider, built for your QGIS minor version, serves the layers.Using the Python data provider: <reason>: the plugin has no native build for your QGIS, and its Python provider serves the layers instead, more slowly. On QGIS 3 this is always the case.
Both serve the same layers, so a project opens with either.
Add a layer through the provider
- Select Plugins → GeoPackage Toolkit → Add GeoPackage layer with this plugin.
- Choose the file. If it has more than one layer or attribute table, choose one.
The layer is added to the project. Its source is the same as an OGR
layer’s, /path/to/file.gpkg|layername=roads, with the provider
geopackage_rs. To add one from the Python console:
layer = QgsVectorLayer("/data/roads.gpkg|layername=roads", "roads", "geopackage_rs")
QgsProject.instance().addMapLayer(layer)
You can edit the layer as you would any other. Each commit writes through the library, so the layer’s spatial index and extent stay up to date. Adding, deleting and renaming fields isn’t possible through this provider.
Run the algorithms
Select an algorithm from Plugins → GeoPackage Toolkit, or open Processing → Toolbox and expand GeoPackage Toolkit. Both list the same algorithms.
Start with Validate GeoPackage. Its plugin_algorithm column names the
algorithm that repairs each finding. The repair algorithms change the file
in place, so run them on a copy if you need to keep the original.
Then
- QGIS plugin reference: every algorithm’s parameters and outputs, and how the provider serves QGIS’s requests.
- How to validate a GeoPackage and act on the findings
- How to repair geometry and datetime encodings
The layer extent
Every row of gpkg_contents has four bounding-box columns: min_x, min_y,
max_x and max_y. Much software reads them as the layer’s extent, but the
standard does not require them to be accurate.
What the spec says
The relevant text is prose, not a numbered requirement, and it is identical in every version from 1.2.0 to 1.4.0. The bounding box “provides an informative bounding box of the content”. Applications “may use this bounding box as the extents of a default view”. And “there are no requirements that this bounding box be exact or represent the minimum bounding box of the content”. The columns are nullable, and no requirement governs their values.
The GeoPackage SWG considered adding a test that features fall inside the recorded extent, and declined in 2018, because maintaining that invariant on every insert and delete is too expensive to require of a writer.
A conformant file can therefore record an extent that is stale, larger than the data, or that does not cover all of it.
No query uses the recorded extent
No read path in this library consults the recorded extent. features_in and
cursor_in go through the RTree index, or through a full scan when there is
none, and re-filter every candidate against its exact f64 envelope.
In particular, a query whose box misses the recorded extent still runs. Skipping it would be correct only when the recorded extent covers the layer. That holds for files this library wrote, but not in general, and on other files the query would return no rows when matching rows exist.
NULL and incorrect extents
GDAL checks only that the four values are present and that min <= max on
each axis. It returns a well-ordered extent as stored and does not recompute
it, even when the caller passes bForce. A NULL extent makes GDAL compute the
actual one. QGIS behaves the same way, and since 3.34 its “Update Extents”
action does nothing for a local GeoPackage, so a user cannot correct a stored
extent there without a full edit session.
A NULL extent therefore costs a reader one scan, after which GDAL can store the computed value. An incorrect extent is used as stored, and is hard for a user to correct.
This library records an extent only when it is guaranteed to cover the layer, and otherwise leaves it NULL, which the spec permits. Four rules follow.
The writer grows the recorded box to cover what it writes, and never shrinks it. The result is exact or larger than the data, which the spec permits. A delete leaves the box unchanged and does not trigger a rescan.
When the stored extent is absent, NULL or inverted but the table already contains rows, the writer leaves it unchanged. A box covering only the rows this writer wrote would exclude every existing row.
A layer with no geometry to measure gets NULL. GDAL does the same, through
UpdateContentsToNullExtent.
A measurement is recorded only when the whole layer could be measured inside one transaction. If another writer changes the layer first, the measurement is returned to the caller but not recorded, and this is not an error.
Reading an extent can write one
Layer::extent records the extent it measures. If the stored extent is
unusable, calling it changes the file’s contents and modification time.
This is the only read operation in the library that writes. Later readers, in
this library or elsewhere, then find a usable extent without scanning. GDAL
does the same, storing a computed extent through SaveExtent on any dataset
open for update.
A pipeline that checksums its inputs will see them change. To avoid the
write, open the file read-only, which still returns the measurement, or read
GeoPackage::contents, which reports the stored values without measuring
anything.
Compared with index repair
The library never repairs a spatial index unless asked, but it does record an extent when reading finds the stored one unusable. Two differences account for this.
Rebuilding an index reads every geometry in the layer and rewrites the tree,
which is too expensive to do as a side effect of a query. And a stale or
older-generation index is not used: has_spatial_index reports it as
unusable, and queries fall back to a full scan, so results stay correct. An
extent is cheaper to measure, and GDAL and QGIS use an incorrect one without
checking it. See The spatial index for the index side.
One difference from GDAL
When GDAL computes an extent, it uses the RTree if there is one. That is
faster, but the result is rounded outward to f32, and it is only as accurate
as the index.
This library always reads the geometries, so the stored extent is exact and does not depend on the index being up to date.
Transactions
SQLite has no nested transactions. A BEGIN issued while one is already open
fails with “cannot start a transaction within a transaction”.
A caller can open a transaction of their own, through GeoPackage::connection
in Rust or gpkg_begin in the C ABI, and then use the ordinary write API. So
every write path in this library checks whether a transaction is already open
before it begins one.
Inheriting a transaction
If a transaction is open, a write path runs its statements inside it. The
statements still commit or roll back together, but the caller’s COMMIT or
ROLLBACK decides when.
This applies to every write path, from a single FeatureWriter insert to a
bulk write_all and the extent recording described in
The layer extent.
What inheritance changes for the caller
commit leaves the transaction open when it was inherited. It still does
everything else a commit does, including flushing the gpkg_contents
last_change and bounding box, but the caller issues the durable commit.
Dropping a writer does not roll back when the transaction was inherited. An error part-way through leaves partial work staged in the caller’s transaction, and the caller has to discard it.
write_all’s batch_size no longer bounds transactions, because every
batch belongs to the caller’s transaction. The rows are written in the same
order, through the same statements.
A writer does not report whether its transaction was inherited. Only a caller who opened a transaction can be in this situation, and that caller already knows.
Beginning without locking
Layer::writer opens a transaction without writing anything, and does not
take a lock. SQLite’s BEGIN DEFERRED acquires nothing until the first
statement needs it, so the first failure a caller sees comes from the first
row, not from the call that returned the writer.
On a read-only connection, opening a writer succeeds and writing the first row fails. Under contention, the wait for another connection’s lock happens at the first write. A successful call to open a writer does not show that the file is writable.
Reading and writing on one connection at once
A writer and a feature cursor share the connection, so a scan can drive its own updates: read a row, recompute a column, write it back.
SQLite does not define what such a scan sees. Its isolation documentation
says that a SELECT on one connection has no isolation from writes on that
same connection, and that an application “can UPDATE the current row or any
prior row, though doing so might cause that row to reappear in a subsequent
sqlite3_step()”. SQLite guarantees that the file will not be corrupted, but
not that the result set is stable, complete, or free of repeats.
In practice the scan is stable when all three of these are true:
- the cursor is a plain table scan, not one driven by an index;
- the columns written are not ones the scan’s index reads;
- the primary key is not written, since changing a row’s id moves it within a rowid scan.
Do not write a geometry during a bounding-box cursor. That cursor is driven by a join against the RTree, and writing a geometry moves the row within that index through the triggers, which can make the scan return rows it has already returned. To recompute geometries, use two passes: collect the feature ids, finish the scan, then write.
This is SQLite’s documented behaviour for one connection. A second connection avoids it, but has its own locking to manage.
Getting the work done
- How to copy features between files without decoding geometry shows a long write committed in batches, and what changes when the caller owns the transaction.
GeoPackage::connectionreturns the underlying connection, on which a caller can open a transaction.
The spatial index: structure, contents, and the bulk build
A GeoPackage indexes a feature layer with an SQLite RTree virtual table named
rtree_<table>_<column>. A set of triggers, written out in Annex F.3 of the
spec, keeps it in step with the rows. The table and the triggers can each go
wrong, in different ways, and checking each costs a different amount.
Structure and contents
The first check is structural: does the virtual table exist, and which generation of trigger set maintains it? The SQLite catalogue answers this cheaply, and repair acts on the answer. It cannot tell you whether the entries in the index agree with the geometries in the table.
The second check is about contents: does the index describe exactly the rows it should, and cover each one? Answering it means reading every geometry in the layer and comparing. It reports the indexable rows, the entries, the rows with no entry, the entries whose row is gone, and the entries that fail to cover their geometry’s true envelope.
An index can pass the first check and fail the second. This happens in a file where rows were written while the triggers were absent, or that another tool populated incompletely. This library’s own writes aren’t expected to produce it, but with bulk verification off, which is the default, nothing checks each bulk build for it. Because an index can pass one check and fail the other, the two have separate remedies. Repair puts the structure right and rebuilds the content, and does nothing when the structure is already current. Rebuild does the content work unconditionally.
A file can arrive in one of four structural states:
- Absent: neither the virtual table nor any trigger is there.
- Current: the virtual table exists with the complete GeoPackage 1.4 trigger set.
- Legacy: a complete pre-1.4 or mixed trigger set.
- Stale: the two halves disagree: a virtual table with none or only some of its triggers, or triggers but no table.
A trigger set is complete when every kind of write has a trigger that keeps the index in step: insert, delete, and each kind of update. The check is by role, so a complete pre-1.4 set counts. A set that has lost even one trigger is Stale, not Current or Legacy, because the writes that trigger handled have been reaching the table without reaching the index.
A legacy trigger set is a real problem, not just untidy. The pre-1.4 update1
trigger corrupts the index under UPSERT. That is why 1.4 renamed the fixed
triggers, and why the repaired state can be detected by name. QGIS tracked the
same failure in
QGIS#36935. A mixed set, with
triggers from more than one generation, is the worst case. You get one when
two tools have edited a file in turn.
This library does not use a Stale index. has_spatial_index reports it as
unusable, so a bounding-box query falls back to a full scan, which returns the
correct rows. A Legacy index is used, because a complete pre-1.4 set keeps the
index in step except under UPSERT; repair it before writing to the file with
UPSERT.
Why repair is not automatic
This library writes during a read in one place: reading a layer’s extent records the measurement when the recorded bounds are unusable. It does not do the same for an index.
The two operations differ in cost, and in what happens without them. Rebuilding an index reads every geometry in the layer and rewrites the tree. That is too expensive to run as the side effect of a question, and a caller who asked about an index’s state has not consented to it. Without a usable index, queries fall back to a scan and still return the correct rows, more slowly.
An extent differs on both counts. Measuring it is comparatively cheap, and GDAL and QGIS use an incorrect one without checking it. See The layer extent for that side of the comparison.
There is a second reason to keep repair explicit. Repairing a legacy trigger set rewrites triggers in a file the caller may only have opened to look at. Doing that unasked would change files on disk just because someone inspected them.
Populating an index
Once the virtual table and the triggers exist, the index has to be filled from the rows already in the table. There are two ways to do it.
Below a threshold, currently 10,000 candidate rows, population is a single
INSERT INTO rtree SELECT over the existing rows. It uses the registered
ST_* functions and skips empty and NULL geometries exactly as the triggers
do. It is simple, it goes through SQLite’s own RTree module, and for a small
table it is cheaper.
At or above that threshold, the library uses the bulk build.
The bulk build
SQLite’s RTree module has no bulk-load entry point. Its only write path is the per-row virtual-table update, so every insert descends the tree and may split nodes. Populating an index one row at a time pays that cost for every row. GDAL reached the same conclusion in gdal#7614.
The obvious alternative is to build the RTree in an ATTACHed scratch
database, through the RTree module, and copy its shadow tables into the
target. Measurements show that this build has the same dominant cost, because
it still inserts every entry through the module one row at a time. The work
moves but does not go away.
So the library builds the tree directly. It lays out the rtree_%_node,
_rowid and _parent contents in memory from the accumulated entry set, and
writes them as ordinary rows. No RTree module logic, no ST_* calls, no
triggers, and no scratch database. This works because the GeoPackage RTree is
always rtree(id, minx, maxx, miny, maxy), two-dimensional with no auxiliary
columns. The three shadow tables therefore have a fixed shape whatever the
index is named.
Avoiding the scratch database also matters for a reason more important than
speed. ATTACH requires autocommit, which would force the build out of the
caller’s transaction and leave a window in which a crash commits the rows but
not the index. Built directly, the whole build is one transaction: dropping the
triggers, every row insert, the gpkg_contents flush, the index work and
reinstalling the triggers all commit together. The rows can never be
committed against an index that was not brought up to date with them. The
exception is a write inside a transaction you opened yourself. A failed call
leaves its work staged there, and committing it anyway leaves a stale index.
The entry set comes either from a scan of the table, which parses each geometry once in Rust, or, when the caller can account for every indexable row, from the envelopes computed while encoding the geometries. Because of that second source, building the index during a write costs between 20% and 47% less than building it afterwards. It is also why creating a layer leaves an empty index in place for the first bulk write to fill.
The verification gate, and its cost
A hand-written RTree uses an on-disk format that SQLite does not document as an interface, so the library can check the result before anything relies on it.
The check has three levels. The first reads the index back and requires
exactly the accumulated (fid, envelope) set, by row count and by a per-row
containment check. The second adds rtreecheck on the index, and the third
adds a whole-database PRAGMA integrity_check. Any anomaly discards the built
index and falls back to the triggered population, so a failed check costs
time, not correctness.
The cost is substantial. Profiled over one million points, the second level is
about 45% of the build: roughly 745 ms of a 1593 ms build. The time is split
about evenly between the bijection scan, which reads every entry back out of
the index, and rtreecheck, which walks the whole tree. GDAL’s builder runs no
equivalent check. With that check on, this library is level with GDAL, not
ahead of it.
Verification is therefore opt-in, and off by default. With verification off, nothing is read back, so a build cannot fail its check and cannot fall back to the triggered path. The automatic fallback exists only where a check does. If you are writing files that matter, or bisecting a suspected index problem, turn verification on to get both.
Node fill
By default the bulk build packs each RTree node full. This gives the smallest tree, the shallowest descent and the best queries, and suits a bulk load.
A full node has no room for a later insert, so the first append into it splits immediately. Appends after a bulk load go through the triggers, which is the per-row path the bulk build exists to avoid. The default therefore favours the load and the queries. A lower fill factor suits a freshly built index that you are about to append to heavily.
Getting the work done
Geometry storage: GPB, WKB, and curve types
A GeoPackage stores each geometry as a blob in an ordinary SQLite column, in an encoding the spec calls GeoPackage Binary, or GPB. A GPB blob is a small header followed by a body in ISO Well-Known Binary (WKB). Most of how this library reads and writes geometry follows from the layout of that header, and from one thing WKB can express that the Rust geometry traits cannot.
The blob
The header is eight bytes: the magic GP, a version byte, a flags byte, and a
32-bit srs_id. The flags byte records the byte order of the header and
envelope, an envelope indicator, an empty-geometry flag, and an extended-GPB
flag. After the header comes an optional envelope of four, six or eight
doubles depending on the indicator, and after that the WKB body, which
declares its own byte order and includes its own type code.
The envelope is optional in the format, but this library always writes one:
XY, or XYZ when the geometry has a Z. It does this for write throughput. The
spec’s RTree triggers call the ST_MinX family of functions four times per
row. These functions can answer from a header envelope in constant time, and
otherwise have to traverse the WKB body. Writing 32 extra bytes per row is
cheap compared with traversing every point of every geometry on every insert.
For points the trade looks unfavourable, because a point’s envelope is larger than the point. This library writes one for points anyway, because uniformity is worth more than the saving. GDAL omits envelopes for points, and that is the practical reason a traversal fallback has to exist at all. Blobs without envelopes are common in files this library did not write, and they still need bounds computed for them.
Reading without materialising
A geometry read from a row is a lazy wrapper, which pairs the parsed header
with the WKB body that follows it. The body is read through the georust wkb
crate, and the wrapper implements geo_traits::GeometryTrait by delegating to
it.
This means you can traverse coordinates without ever creating an owned
geometry object. An algorithm written against geo_traits reads coordinates
directly from the stored bytes. The write path accepts any
impl GeometryTrait<T = f64>, so you can stream a geometry out of one file,
measure it, and write it into another without converting it to a geo-types
value in either direction. Conversion to geo-types is available behind a
default feature if you want it. You choose when to convert, and the read path
does not do it for you.
Two things still allocate: each row’s blob, which is copied out of SQLite, and the new blob the writer serialises. An algorithm that produces new geometry also allocates its output. What you avoid is the intermediate object, not every allocation.
Parsing arbitrary bytes never panics. A malformed header, a truncated body, or a type the reader cannot handle all produce a typed error.
Bytes in, bytes out
Writes normally go through the trait, but you can also pass WKB bytes to the writer directly. They are copied into the new blob rather than re-serialised, so a body read out of one GeoPackage passes into another unchanged, with only the header rebuilt around it. The rest of this chapter explains why this path exists.
What the traits cannot represent
The GeoPackage geometry vocabulary in Annex G includes five non-linear types:
CIRCULARSTRING, COMPOUNDCURVE, CURVEPOLYGON, MULTICURVE and
MULTISURFACE. Their defining feature is the circular arc, which is given by
three points. The first and last are the arc’s ends, and the middle one fixes
the circle the arc lies on.
geo-traits, the interface this library uses to read and write geometry, has
no representation for an arc, and neither does geo-types. This is not an
oversight in either. An arc is not a sequence of coordinates, and a library
built on sequences of coordinates has nowhere to put one. Densifying an arc
into a linestring to approximate it would be a lossy transformation that no
caller requested.
This library therefore handles the non-linear types as bytes. You can write
them, index them and query them by extent, and their WKB is returned as
stored. Only the call that would return a geometry object fails on them,
because there is no object to return. For this reason, anything that moves
geometry between files should use the byte path. Reading into a geo-types
value and writing it back loses the curve types entirely, and also parses
every coordinate for no purpose.
Why an arc’s envelope has to be exact
Indexing and querying a curve by extent requires an envelope, and that envelope has to be computed from the arc rather than from the three points that define it.
A circular arc bulges away from the chord joining its endpoints, and may bulge past its middle control point too. The bounding box of the three control points can therefore be strictly smaller than the arc’s own. An envelope that is too small is a correctness problem, not a tuning or quality question. The GPB header envelope and the RTree entry are both derived from it, and a reader that trusts either will silently drop features that do intersect the query window.
The exact box can be computed in closed form. The arc lies on a circle through
the three points, so its extremes in x and y are either the endpoints or the
points of that circle furthest along each axis. The chord between the
endpoints decides which of those four candidates the arc actually reaches.
This is the approach PostGIS takes in lw_arc_calculate_gbox_cartesian_2d.
GDAL computes the same box by a different route, from swept angles, in
OGRCircularString::ExtendEnvelopeWithCircular.
A degenerate case explains why the arithmetic uses a tolerance. As the three points approach collinearity, cancellation error dominates the circumcentre and the radius diverges. In that limit the arc is treated as its chord. This is correct, not a fudge. As the points straighten, the bulge past them falls to zero, so the error the tolerance admits shrinks with it.
Arcs are planar by definition
An arc is a circle in the coordinate space of the layer’s CRS, including when that CRS is geographic. Three longitude and latitude points define a circle in degree space, not a small circle on the ellipsoid.
This is not peculiar to this library. PostGIS and GDAL both read arcs the same way, and the GeoPackage RTree indexes the same degree space. A geodesic reading would produce envelopes that disagreed with the index they were stored in. The envelope computation therefore uses no geodesic arithmetic. Nor does it involve a coordinate transformation, which this library never performs.
Tight envelopes, and where slack is added
The computed box is the minimum bounding box, with no outward margin. Slack is
added later, in the index, where it can be reasoned about. RTree columns are
32-bit floats, so each bound is rounded outward when it is narrowed. A stored
cell therefore contains the f64 box it was derived from, with two exceptions
in SQLite’s RTree module. A coordinate beyond the f32 range becomes an
infinite bound on its own side, so a point at y = 1e39 has a cell from +inf to
+inf. A coordinate in the f32 subnormal range becomes the nearest f32,
which can be inward by less than one f32 step. features_in widens its query
box by one f32 step outward, so it still selects both.
Annex F.3 of the spec also tells clients to expand query windows to absorb
exactly that rounding.
Keeping the geometry-level envelope tight and the index-level entry loose puts the widening in one place, where it is a property of the index rather than of the data.
Two envelope walkers
As a result, the codebase has two envelope computations rather than one. The
ordinary path traverses a geometry through the wkb reader, which cannot read
the non-linear types. The curve path walks the WKB structure itself, byte by
byte. It handles every Annex G type and every XY, XYZ, XYM and XYZM variant,
so it yields an envelope for a curve body without waiting on upstream support.
The curve walker also has some defensive properties. It skips non-finite coordinates, so an empty point, which by convention has NaN coordinates, yields no envelope rather than a NaN-valued box. It caps nesting at 32 containers deep, so a hostile body cannot drive the recursion into a stack overflow. It allocates nothing, so a bad element count in a curve body fails immediately instead of reserving memory for it. The reader used for the linear types does not behave this way.
The split creates one error case of its own: a body whose own type is a core
type but which contains a non-linear member, such as a GEOMETRYCOLLECTION
containing a CIRCULARSTRING. The body’s own type code decides which walker
it gets, so such a container reaches the reader that cannot read the member.
This is reported as a distinct error rather than as a malformed body, because
the body is not malformed, and otherwise no caller could tell the two apart.
Getting the work done
Tiled gridded coverages, and why they are not tile pyramids
A GeoPackage can store two kinds of tiled raster. One is a basemap: PNG or JPEG tiles that a renderer draws. The other is a tiled gridded coverage: a grid of measurements, usually elevation, stored tile by tile in the same pyramid structure. The two look similar on disk, but their uses are different, so this library keeps them separate.
What the extension adds
Coverages are an extension to the core standard, published separately as
OGC 17-066r2 and registered
in a file as gpkg_2d_gridded_coverage. The extension adds three things to a
tile pyramid:
- a different
gpkg_contents.data_type:2d-gridded-coverage, nottiles; gpkg_2d_gridded_coverage_ancillary, one row for each coverage, which states what the samples mean: integer or float, the scale and offset that convert a stored sample to a value, the value for “no data”, and the unit of measure;gpkg_2d_gridded_tile_ancillary, one row for each tile, with the scale and offset of that tile and, optionally, its minimum, maximum, mean and standard deviation.
The payload of a tile is a TIFF or a 16-bit greyscale PNG, and the extension constrains it closely: one sample per grid cell, 32-bit float or 8, 16 or 32-bit integer samples, no compression or LZW compression, one image per file, and no internal tiles.
A coverage payload is not a GeoTIFF
The TIFF payloads of a coverage are often assumed to be GeoTIFFs. They are not.
The georeferencing is in gpkg_tile_matrix_set, the same extent and grid that
a basemap pyramid uses, so the payload does not need any. The extension does
not use GeoKeyDirectory, ModelPixelScale or ModelTiepoint. It specifies
a small profile of baseline TIFF, and each rule in the profile is a
statement about a tag, not about a pixel.
So this library can check a coverage payload completely without an image
codec. geopackage_core::coverage::coverage_tiff walks the first IFD,
reads seven tags, and checks the encoding requirements against them.
coverage_png does the same for IHDR. Neither function decodes a sample.
The limits of a header check
A header check cannot check one requirement, Requirement 21, because it is a statement about samples, and a check of the samples needs a decoder. By default, a payload that this library accepts conforms in structure only, and the check says nothing about its contents.
The decoder is behind the coverage-samples feature, which adds the tiff and
png crates. With it, the library checks Requirement 21,
looks up values at a position, and calculates per-tile statistics. How to read
values from a coverage shows each of these. The
feature stays off by default because a reader that only copies or serves tiles
never needs a sample.
The decode is in geopackage-core, behind a feature of the same name that
geopackage turns on. A coverage’s samples are its data, and the rules about
them (Requirement 21, the scale and offset, data_null,
grid_cell_encoding, what the statistics columns mean) are part of the format,
which is what the core crate holds. Image tiles are different: the spec says
nothing about their pixels, so neither crate decodes them.
Without the feature, the same limit applies to the write path. The four
per-tile statistics come from the samples, so they are None unless you supply
them:
use geopackage::core::tiles::TileCoord;
use geopackage::{GeoPackage, TileAncillary};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let gpkg = GeoPackage::open("dem.gpkg")?;
let coverage = gpkg.coverage("elevation")?;
let payload: Vec<u8> = Vec::new();
let mut writer = coverage.writer()?;
writer.put_with_ancillary(
TileCoord::new(0, 0, 0),
&payload,
// Values from the code that decoded the samples. Without them, the row has
// nulls. That conforms, but the row has less data than a row from GDAL.
&TileAncillary::defaults().with_statistics(0.5, 96.5, 48.53, 27.99),
)?;
writer.commit()?;
Ok(()) }
Requirement 21
The extension numbers its rules, and the library’s errors, findings and documentation cite them by number. Requirement 21 of OGC 17-066r2 is the only one about the samples of a tile, not the structure of its payload:
All pixels in a tile of coverage data SHALL be set with a valid component value … Special floating point values such as NaN and Inf SHALL NOT be used.
Only a float coverage can break it, because an integer sample cannot hold NaN
or an infinity. A cell with no data holds the coverage’s data_null value, not
NaN. Many raster tools mark a missing float cell with NaN, so a tile converted
from another format can break the requirement although its header is correct.
What checks it, and what does not:
Coverage::put_tile,CoverageWriter::putandCoverageWriter::put_with_ancillarycheck the header only, so they do not check Requirement 21. If you write payloads from another source, their samples are your responsibility.- With the
coverage-samplesfeature,CoverageWriter::put_with_statisticsdecodes the payload and refuses a tile with a NaN or infinite sample. - With the feature,
GeoPackage::validatedecodes every coverage tile and reports such a tile as a breach of Requirement 21. A tile whose header declares more samples thanOpenOptions::max_decoded_samplesallows is not decoded, so its samples are not checked. Without the feature,validatedoes not check the requirement. - With the feature,
Coverage::check_sampleschecks one decoded tile. How to read values from a coverage shows it.
Why a coverage has a separate handle
GeoPackage::tiles rejects a coverage, and GeoPackage::coverage rejects a
basemap. There are three reasons.
Every tile needs a second row. Requirement 10 specifies a matching
gpkg_2d_gridded_tile_ancillary row for each tile in the user table. The
normative table definition has no ON DELETE CASCADE, so the database does not
keep the rows paired. CoverageWriter writes both rows and deletes both rows.
A TilePyramid writer does not know about the second row, and a coverage
written through it would collect tiles without rows.
The payload rules are opposites. A tile pyramid can store PNG, JPEG or WebP, and must not store TIFF. A coverage must store TIFF or 16-bit PNG, and nothing else. Both checks are strict, and neither is a special case of the other.
The result of a read is different. From a basemap, you need bytes for a decoder. From a coverage, you need a value: the stored sample, converted by two scale and offset pairs, and compared with the null:
use geopackage::core::tiles::TileCoord;
use geopackage::GeoPackage;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let gpkg = GeoPackage::open_read_only("dem.gpkg")?;
let coverage = gpkg.coverage("elevation")?;
let tile = coverage.tile_ancillary(TileCoord::new(0, 0, 0))?.unwrap();
// `sample` comes from a decode of the payload: your code's, or, with the
// `coverage-samples` feature, `Coverage::samples`.
let sample = 1234.0;
if coverage.is_null(sample) {
println!("no data here");
} else {
println!("{} {}", coverage.value(&tile, sample),
coverage.ancillary().uom.as_deref().unwrap_or(""));
}
Ok(()) }
In this example, the null is compared with the stored sample, before the scale and offset apply, because the extension says that the scale and offset do not apply to the null. If you apply them first, you lose your no-data cells, and nothing reports an error.
Files from other writers
As elsewhere in this library, a read accepts more than a write. A coverage with a
datatype value that the requirement does not permit still opens, and
Coverage::datatype returns None. A read accepts a payload with Deflate
compression, although Requirement 15 specifies baseline TIFF and Deflate is not
part of it. A write rejects the same payload.
GeoPackage::validate reports the defects in a file, requirement by
requirement: ancillary rows that point to no tile, tiles without a row, a float
coverage that scales its samples, and a payload that contradicts the datatype
of its coverage. The last is an error, not a warning, because a reader that
uses the ancillary row gets incorrect values.
Before you call validate on a large file, note that the coverage check is the
only check with work that scales with the size of the file, not with the number
of tables. The encoding requirements are statements about payloads, so the
check must read every payload.
Reference
This page points to the reference documentation, which is generated from the source.
Crates
| Crate | Contents | Reference |
|---|---|---|
geopackage | The main library: files, feature and attribute layers, spatial indexes, tile pyramids, tiled gridded coverages, Arrow I/O. | docs.rs/geopackage |
geopackage-core | Format code with no I/O or SQLite: the GPB geometry codec, table definitions, RTree triggers, identifier quoting, application_id and user_version handling, coverage payload rules and, behind coverage-samples, the coverage sample decode. | docs.rs/geopackage-core |
geopackage-ffi | The C API: opaque handles over the same library, with data passed through the Arrow C Data Interface. Packaged with cargo-c. The only crate that uses unsafe. | docs.rs/geopackage-ffi |
geopackage-cli | The gpkg command-line tool. | gpkg --help |
The C API
The header, geopackage-ffi/include/geopackage.h, is generated with cbindgen
and checked in. cargo cinstall -p geopackage-ffi installs it with a
versioned library and a pkg-config file named geopackage.
geopackage-ffi/examples/ has five C programs. CI compiles each against the
committed header and runs it.
| Program | Contents |
|---|---|
smoke.c | Open a file, list its layers, read one as an Arrow stream, and check that closing fails while the stream is open. |
inspect.c | Open a file leniently and read-only, then check everything before writing: open warnings, layers and tile pyramids, extensions and their support levels, and validation findings. |
query.c | Open a layer with only the columns it needs, resolve its CRS, and read by bounding box, by bounding box and WHERE clause with a bound parameter, and by feature ID. |
roundtrip.c | Create a layer from another layer’s Arrow schema, and copy the rows in one transaction. |
tilepipe.c | Create a Web Mercator tile pyramid, fill it, and copy it tile by tile with a cursor. |
gpkg commands
| Command | Description |
|---|---|
gpkg info <file> | Version, layers with their schemas and row counts, spatial reference systems, spatial-index state including its trigger generation, tile pyramids, and the extension catalogue. |
gpkg validate <file> | The findings of GeoPackage::validate, most severe first, each with its repair advice. Nothing is modified. --strict also exits non-zero for warnings. |
gpkg index <file> <layer> | Builds a spatial index on a layer that has none. A layer whose index is present but broken exits non-zero. |
gpkg repair <file> [layer] | Rebuilds legacy and desynchronised indexes onto the 1.4 trigger set, rewrites geometries whose WKB type codes use the high-bit Z or M flags with ISO codes, and rewrites DATETIME text in the GeoPackage form where nothing is lost. Works on one named layer or attribute table, or on every one that needs it. A layer with no index is left alone. |
gpkg copy <src> <dst> | Copies the feature and attribute layers of one file into a new one. |
gpkg tiles info <file> [pyramid] | Each pyramid’s extent, spatial reference system and zoom ladder, with the tiles stored at each level. |
gpkg tiles get <file> <pyramid> <zoom> <column> <row> | Writes one tile’s stored bytes to --out or to standard output. |
gpkg coverage info <file> [coverage] | Each tiled gridded coverage’s sample type, field, scale and offset, null value, grid-cell convention, spatial reference system, extent and zoom levels, and the payload format of its first tile. |
gpkg coverage get <file> <coverage> <zoom> <column> <row> | Writes one coverage tile’s stored bytes to --out or to standard output, and prints the values its payload header and ancillary row declare. Samples are not decoded. |
Every command opens the file leniently. gpkg validate exits non-zero when a
finding is an error. Every other command exits non-zero only when it fails.
Format and toolchain
- Specification: OGC GeoPackage 1.4.
- Minimum supported Rust version: 1.95.
QGIS plugin reference
The GeoPackage Toolkit plugin for QGIS: its data provider and its Processing algorithms. To install it, see How to install the QGIS plugin and add a layer through it.
Requirements
| QGIS | 3.28 or later |
| Plugin repository | https://urschrei.github.io/geopackage/qgis/plugins.xml |
| Release zips | gpkg_toolkit-<version>.zip, attached to each plugin release, tagged qgis-plugin-v<version>, on GitHub |
| Changelog | qgis-plugin/CHANGELOG.md |
| Status | Experimental |
The zip holds compiled code for each platform it supports. A file is chosen when the plugin loads.
| Platform | geopackage_rs module | Native provider |
|---|---|---|
| Linux x86_64 (glibc 2.28 or later) | yes | QGIS 4.0, 4.2 |
| Linux aarch64 (glibc 2.28 or later) | yes | QGIS 4.0, 4.2 |
| macOS (arm64 and x86_64) | yes | QGIS 4.0, 4.2 |
| Windows x86_64 | yes | QGIS 4.0, 4.2 |
On Linux and macOS, both use the SQLite that QGIS has loaded. On Windows, each has its own.
Data provider
| Provider key | geopackage_rs |
| URI | /path/to/file.gpkg|layername=<table>, as OGR’s. Without layername, the file’s only layer or attribute table. |
| Layers | Feature layers and attribute tables |
| Opened | Leniently: DATETIME text in the common ISO 8601 forms other than GeoPackage’s own is read |
Implementations
The key is served by one of two implementations. They give the same results.
| Implementation | Serves the key when |
|---|---|
Native (Rust behind a C++ shim, geopackage-qgis) | QGIS 4, and the plugin has a build for the running minor version |
Python (gpkg_toolkit/data_provider.py) | Otherwise, including every QGIS 3 |
The GeoPackage Toolkit tab of the Log Messages panel names the implementation in use, and why the native one isn’t used.
| Environment variable | Effect |
|---|---|
GPKG_TOOLKIT_NATIVE_PROVIDER=<path> | Loads the native build at <path> instead of the one in the plugin |
GPKG_TOOLKIT_NATIVE_PROVIDER=0 | Uses the Python implementation |
Reads
| QGIS request | How the provider serves it |
|---|---|
| Bounding box | The layer’s RTree, then QGIS’s exact-intersection test when asked |
| One feature id, or several | fid = <id>, or fid IN (...) |
| Subset string | An SQLite WHERE clause, as in OGR. An invalid one is rejected when it is set |
| Attributes without geometry | A column projection: unread columns and geometry are not fetched |
| Filter expression | Evaluated by QGIS on the rows read |
| Destination CRS, limit, order by, distance within | As QGIS’s core providers serve them |
Edits
| Capability | Supported |
|---|---|
| Add, delete features | Yes |
| Change attribute values, geometries | Yes |
| Add, delete, rename fields | No |
Each edit call is one transaction. A geometry is converted to the column’s type, as multi, and given or stripped of Z and M, on the way in. A commit writes through the library, which keeps the spatial index and the extent up to date.
Algorithms
Each algorithm’s identifier is gpkgtoolkit:<name>. An algorithm that
opens a GeoPackage opens it leniently.
Validate GeoPackage (validate)
Group: Inspect and repair. Read-only.
| Parameter | Type | Description |
|---|---|---|
INPUT | File (.gpkg) | The GeoPackage |
OUTPUT | Table | Findings |
Fields of OUTPUT: severity (error, warning or advisory), code,
table_name, message, repair, plugin_algorithm, the name of the
algorithm here that makes the repair.
Outputs: ERRORS, WARNINGS, ADVISORIES, the number of findings of each
severity. The findings are this library’s checks, not the OGC test suite’s.
Repair spatial indexes (repairspatialindexes)
Group: Inspect and repair. Modifies the file.
| Parameter | Type | Description |
|---|---|---|
INPUT | File (.gpkg) | The GeoPackage |
LAYER | String, optional | One layer; every feature layer if empty |
BUILD_MISSING | Boolean, default false | Build an index for a layer that has none |
OUTPUT | Table | Index report |
Fields of OUTPUT: layer, status_before and status_after (current,
legacy, stale or absent), action, missing, extra.
Output: REPAIRED, the number of layers changed.
A legacy (pre-1.4 or mixed) or stale trigger set is replaced with the 1.4
triggers and the index is rebuilt; the action is rebuilt with 1.4 triggers. An index that is out of step with its table is rebuilt
(rebuilt), and with BUILD_MISSING, an absent one is built (built).
Otherwise the action is none.
Repair geometry and datetime encodings (repairencodings)
Group: Inspect and repair. Modifies the file.
| Parameter | Type | Description |
|---|---|---|
INPUT | File (.gpkg) | The GeoPackage |
LAYER | String, optional | One layer or attribute table; all if empty |
OUTPUT | Table | Repair report |
Fields of OUTPUT: layer, geometries and datetimes, the number of
values rewritten.
Output: REPAIRED, the number of tables changed.
A geometry whose WKB gives Z or M by a high-bit flag in a type code is
rewritten with ISO type codes and a header envelope. DATETIME text in
another ISO 8601 form is rewritten in the GeoPackage form, unless that
would lose precision. See
How to repair geometry and datetime encodings.
List extensions (listextensions)
Group: Inspect and repair. Read-only.
| Parameter | Type | Description |
|---|---|---|
INPUT | File (.gpkg) | The GeoPackage |
OUTPUT | Table | Extensions |
Fields of OUTPUT: name, table_name, column_name, scope, support,
definition. support is implemented, known (recognised, not
implemented; writes to a table it covers are refused when its scope is
read-write), removed (withdrawn from the standard) or unrecognised.
Sample coverage at points (samplecoverage)
Group: Coverages. Read-only.
| Parameter | Type | Description |
|---|---|---|
INPUT | File (.gpkg) | The GeoPackage |
COVERAGE | String, optional | The coverage; the file’s only one if empty |
POINTS | Point layer | The points to sample, transformed into the coverage’s CRS |
ZOOM | Integer, optional | The zoom level; the most detailed if empty |
INTERPOLATION | nearest (default) or bilinear | |
FIELD | String, default value | The name of the new field |
OUTPUT | Point layer | The points, with the new field |
A point outside the coverage, in a tile the coverage does not store, or on
a null sample gets NULL. A multipart or non-point geometry is sampled at
its centroid. On a grid-value-is-area coverage, bilinear gives the same
values as nearest.
Coverage tile statistics (coveragestatistics)
Group: Coverages. Read-only.
| Parameter | Type | Description |
|---|---|---|
INPUT | File (.gpkg) | The GeoPackage |
COVERAGE | String, optional | The coverage; the file’s only one if empty |
ZOOM | Integer, optional | The zoom level; the most detailed if empty |
OUTPUT | Polygon layer | One footprint per stored tile |
Fields of OUTPUT: coverage, zoom, tile_column, tile_row; the
statistics recorded in gpkg_2d_gridded_tile_ancillary, rec_min,
rec_max, rec_mean, rec_std_dev; the statistics calculated from the
decoded samples after scale and offset, without null samples, min, max,
mean, std_dev, count; and error, why a tile could not be decoded.
Find NaN and infinite values in coverages (checkcoveragesamples)
Group: Coverages. Read-only.
| Parameter | Type | Description |
|---|---|---|
INPUT | File (.gpkg) | The GeoPackage |
COVERAGE | String, optional | The coverage; every coverage if empty |
OUTPUT | Polygon layer | The outline of each failing tile, in the coverage’s CRS |
Fields of OUTPUT: coverage, zoom, tile_column, tile_row,
message.
Output: FAILURES, the number of failing tiles.
A tile fails when it contains a NaN or infinite value, which the GeoPackage standard does not allow in a coverage (Requirement 21), or when it cannot be read. Validate GeoPackage reads only the header of each tile, so it does not make this check.
Export layer to GeoPackage (exportlayer)
Group: Import and export.
| Parameter | Type | Description |
|---|---|---|
INPUT | Vector layer | The layer to write |
OUTPUT | File (.gpkg) | A new file, or an existing one to add a table to |
LAYER_NAME | String, optional | The table’s name; the input’s name if empty |
SPATIAL_INDEX | Boolean, default true | Build a spatial index |
Outputs: OUTPUT_LAYER, the written layer; WRITTEN, the number of rows.
The table is a GeoPackage 1.4 table with the 1.4 trigger set, and the index
is built in bulk. An integer field named fid gives the feature ids;
otherwise they are assigned. A field type with no GeoPackage equivalent is
written as TEXT. A single geometry in a multi layer is written as multi.
The CRS is added from the EPSG registry when it has an EPSG code, and from
its WKT otherwise.
Menu
Plugins → GeoPackage Toolkit:
| Entry | Effect |
|---|---|
| Add GeoPackage layer with this plugin | Asks for a file and a layer, and adds the layer through geopackage_rs |
| Each algorithm, in the toolbox’s groups | Opens the algorithm’s dialog |
The menu has no entries when the geopackage_rs module does not load. The
GeoPackage Toolkit tab of the Log Messages panel gives the reason.