Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 85 additions & 7 deletions crates/data/src/source/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp
use crate::raster::Crs;
use crate::{DataError, Feature, Field, FieldType, GeometryType, Result, Value, wkb};
use rusqlite::types::ValueRef;
use rusqlite::{Connection, OpenFlags, params_from_iter};
use rusqlite::{Connection, OpenFlags, OptionalExtension, params_from_iter};
use rustgis_geom::Extent;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
Expand All @@ -21,6 +21,18 @@ pub use crate::io::{GpkgMode, GpkgTable, GpkgWritten};
/// Rows fetched by id per query.
const CHUNK: usize = 500;

/// What a view read through the R-tree fetches a table's rows by, so they come in the order a
/// scan of the table gives them.
#[derive(Clone, Copy)]
enum RowOrder {
/// The key, which is the rowid (a GeoPackage's `INTEGER PRIMARY KEY`).
Key,
/// The rowid, by this name, where the key is apart from it (declared `INT`, say).
Rowid(&'static str),
/// Neither: no rowid, or columns have taken all its names. A view is read by a scan.
Scan,
}

/// A feature table in a GeoPackage.
pub struct GpkgSource {
info: SourceInfo,
Expand All @@ -29,6 +41,7 @@ pub struct GpkgSource {
table: String,
geom: String,
pk: Option<String>,
row_order: RowOrder,
rtree: Option<String>,
reproject: Reproject,
/// A copy written for a file opened from memory, removed when the source is dropped.
Expand Down Expand Up @@ -286,6 +299,7 @@ impl GpkgSource {
}
}
}
let row_order = row_order(&conn, &table).map_err(err)?;
// Looked up without regard to case, as SQLite names are; the real name is kept.
let rtree_name = format!("rtree_{table}_{geom}");
let rtree: Option<String> = conn
Expand Down Expand Up @@ -350,7 +364,7 @@ impl GpkgSource {
// A system the definition gives, by its PROJ definition, so the layer keeps it
// (`SourceInfo::coordinate_system`), as a Shapefile's .prj does (#1476).
crs: reproject.info_crs(),
indexed: rtree.is_some(),
indexed: rtree.is_some() && !matches!(row_order, RowOrder::Scan),
notes,
zm_dropped: false,
};
Expand All @@ -361,6 +375,7 @@ impl GpkgSource {
table,
geom,
pk,
row_order,
rtree,
reproject,
temp: None,
Expand Down Expand Up @@ -426,6 +441,19 @@ impl GpkgSource {
cols.join(", ")
}

/// The order a scan of the table gives, written out (` ORDER BY …`) so that SQLite can't read
/// it another way, such as down a covering index: the order a view read through the R-tree
/// fetches in.
Comment on lines +444 to +446

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doc says the order is "written out ( ORDER BY …) so that SQLite can't read it another way". That holds for the Key and Rowid arms, but the RowOrder::Scan arm writes no ORDER BY at all. For a table with no usable rowid (WITHOUT ROWID, or rowid names taken by columns), SQLite may still pick a covering secondary index and return rows in that index's order. The whole read and the view read use the same statement there, so they agree with each other, but the "table's order" the doc and the PR promise is not enforced for those tables. The Key arm's comment ("The rowid itself, or a name of it no column has taken") also describes only the Rowid arm.

Confidence: the wording mismatch is certain; that a covering index actually reorders a scan here is low to medium (about 30%), and the test has no secondary index, so it doesn't cover it.

Suggested change
/// The order a scan of the table gives, written out (` ORDER BY …`) so that SQLite can't read
/// it another way, such as down a covering index: the order a view read through the R-tree
/// fetches in.
/// The order a view read through the R-tree fetches in, written out (` ORDER BY …`) so that SQLite
/// can't read the rows another way, such as down a covering index. A table read by a scan (no
/// usable rowid) writes none, so it keeps SQLite's own scan order, the same for the whole read and
/// a view read of it.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point on the wording: the comment inside order_by says why those arms are empty, but the doc above it could say so too. Left for the release quality pass.

fn order_by(&self) -> String {
match (self.row_order, &self.pk) {
// The rowid itself, or a name of it no column has taken: no sort.
(RowOrder::Key, Some(pk)) => format!(" ORDER BY {}", quote(pk)),
(RowOrder::Rowid(rowid), _) => format!(" ORDER BY {rowid}"),
// Without a key no view is read through the R-tree, so there's no order to match.
(RowOrder::Key, None) | (RowOrder::Scan, _) => String::new(),
}
}

/// Turns a row (id, geometry, fields…) into a feature; `None` for an unreadable geometry.
/// Dates that aren't ones are counted in `unread_dates` ([`Batch::unread_dates`]), date-times
/// rounded to the microsecond in `rounded_dates`.
Expand Down Expand Up @@ -520,7 +548,12 @@ impl FeatureSource for GpkgSource {
Row::Bad => out.skipped += 1,
};
match (native, &self.rtree, &self.pk) {
(Some(e), Some(rt), Some(pk)) => {
// A count alone (`limit` 0) fetches no rows, so it needs no order: the index counts it.
(Some(e), Some(rt), Some(pk)) if limit == 0 || !matches!(self.row_order, RowOrder::Scan) => {
// One read, so a write between picking the ids and fetching them (and, for a key
// apart from the rowid, between looking up their rowids and fetching by them)
// can't hand back a row that wasn't picked. A read rolls nothing back.
let _read = conn.unchecked_transaction().map_err(err)?;
// The index gives the matching ids; an evenly spread sample of them is fetched.
// Counted first, then streamed keeping every `step`-th, so a huge match never sits
// in memory as a list of ids.
Expand All @@ -531,17 +564,28 @@ impl FeatureSource for GpkgSource {
let step = usize::try_from(stride(out.matched, limit)).unwrap_or(usize::MAX);
let mut st = conn.prepare(&format!("SELECT id {filter}")).map_err(err)?;
// A row error (a corrupt page) fails the read rather than truncating it quietly.
let picked: Vec<i64> = st
let mut picked: Vec<i64> = st
.query_map(args, |r| r.get(0))
.map_err(err)?
.step_by(step.max(1))
.take(limit)
.collect::<rusqlite::Result<_>>()
.map_err(err)?;
out.complete = step == 1;
let table = quote(&self.table);
// The index lists them in its own order. They are fetched in the table's, as a
// whole read gives them: the order the map draws them in.
let by = match self.row_order {
RowOrder::Rowid(rowid) => {
picked = rowids(conn, &table, rowid, &quote(pk), &picked).map_err(err)?;
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
rowid.to_string()
}
_ => quote(pk),
};
picked.sort_unstable();
for chunk in picked.chunks(CHUNK) {
let marks = vec!["?"; chunk.len()].join(",");
let sql = format!("SELECT {} FROM {} WHERE {} IN ({marks})", self.select_list(), quote(&self.table), quote(pk));
let sql = format!("SELECT {} FROM {table} WHERE {by} IN ({marks}) ORDER BY {by}", self.select_list());
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
let mut st = conn.prepare(&sql).map_err(err)?;
let mut rows = st.query(params_from_iter(chunk.iter())).map_err(err)?;
while let Some(r) = rows.next().map_err(err)? {
Expand All @@ -557,7 +601,7 @@ impl FeatureSource for GpkgSource {
}
_ => {
// A scan: the envelope in each geometry's header tests the extent before decoding.
let sql = format!("SELECT {} FROM {}", self.select_list(), quote(&self.table));
let sql = format!("SELECT {} FROM {}{}", self.select_list(), quote(&self.table), self.order_by());
let mut st = conn.prepare(&sql).map_err(err)?;
let mut rows = st.query([]).map_err(err)?;
// A whole read knows its count, unless the file's own; an extent, bounded natively
Expand Down Expand Up @@ -630,7 +674,7 @@ impl FeatureSource for GpkgSource {
same_file()?;
let req = Request { extent, limit: usize::MAX, own: None };
let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e));
let sql = format!("SELECT {} FROM {}", self.select_list(), quote(&self.table));
let sql = format!("SELECT {} FROM {}{}", self.select_list(), quote(&self.table), self.order_by());
let mut st = conn.prepare(&sql).map_err(err)?;
let mut rows = st.query([]).map_err(err)?;
let mut out = Batch { complete: true, ..Batch::default() };
Expand All @@ -651,6 +695,40 @@ impl FeatureSource for GpkgSource {
}
}

/// How to fetch rows of `table` in a scan's order ([`RowOrder`]). Only "no such row" answers a
/// question here; a statement that fails fails the open, rather than picking an order unseen.
fn row_order(conn: &Connection, table: &str) -> rusqlite::Result<RowOrder> {
// SQLite indexes a primary key that isn't the rowid itself.
if conn.query_row("SELECT 1 FROM pragma_index_list(?1) WHERE origin = 'pk'", [table], |_| Ok(())).optional()?.is_none() {
return Ok(RowOrder::Key);
}
// A column takes a rowid's name from it; a table without rowids has none of them, and a query
// naming one doesn't prepare (where it fails otherwise, the table is read by a scan: slower,
// never out of order).
for name in ["rowid", "_rowid_", "oid"] {
let taken = "SELECT 1 FROM pragma_table_xinfo(?1) WHERE lower(name) = ?2";
if conn.query_row(taken, [table, name], |_| Ok(())).optional()?.is_none()
&& conn.prepare(&format!("SELECT {name} FROM {}", quote(table))).is_ok()
{
return Ok(RowOrder::Rowid(name));
}
}
Ok(RowOrder::Scan)
}

/// The rowids (named `rowid`) of the rows of `table` whose `key` is among `keys`.
fn rowids(conn: &Connection, table: &str, rowid: &str, key: &str, keys: &[i64]) -> rusqlite::Result<Vec<i64>> {
let mut found = Vec::with_capacity(keys.len());
for chunk in keys.chunks(CHUNK) {
let marks = vec!["?"; chunk.len()].join(",");
let mut st = conn.prepare(&format!("SELECT {rowid} FROM {table} WHERE {key} IN ({marks})"))?;
for id in st.query_map(params_from_iter(chunk.iter()), |r| r.get(0))? {
found.push(id?);
}
}
Ok(found)
}

/// A file's device and inode, which tell it from another file put at its path since; `None`
/// where the system doesn't say them.
fn file_identity(path: &Path) -> Option<(u64, u64)> {
Expand Down
58 changes: 58 additions & 0 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,64 @@ fn geopackage_reprojects_and_uses_its_rtree() {
assert!(open_path(&p2, Some("missing")).is_err());
}

/// A read through the R-tree gives its features in the table's order, as a whole read does,
/// though the index lists them in another: the map draws them in it, each over the ones before.
#[test]
fn geopackage_view_reads_keep_the_tables_order() {
// Places scattered against the ids, in more than one fetch of them.
let mut ds = Dataset::new("scattered", GeometryType::Point, vec![]);
for i in 0..1200u32 {
let at = i * 719 % 1200;
ds.push(Some(Geometry::Point(Coord::new(f64::from(at % 40), f64::from(at / 40)))), vec![]);
}
// The table as written, keyed by its rowid as a GeoPackage asks; then made again with other
// keys, `fid` numbering the places against the order they were added in.
let layouts = [
None,
// A key of its own, apart from the rowid.
Some("(fid INT PRIMARY KEY, geom MULTIPOINT)"),
// And a column that takes one of the rowid's names, holding the keys.
Some("(fid INT PRIMARY KEY, geom MULTIPOINT, rowid INTEGER)"),
// No rowid: the table is in its key's order, here downward.
Some("(fid INTEGER PRIMARY KEY DESC, geom MULTIPOINT) WITHOUT ROWID"),
];
for (n, layout) in layouts.into_iter().enumerate() {
let p = dir().join(format!("scattered-{n}.gpkg"));
crate::io::write_path(&ds, &p).unwrap();
if let Some(layout) = layout {
let taken = if layout.contains("rowid INTEGER") { ", 1201 - fid" } else { "" };
let new_fid = if layout.contains("DESC") { "fid" } else { "1201 - fid" };
rusqlite::Connection::open(&p)
.unwrap()
.execute_batch(&format!(
"CREATE TABLE rows AS SELECT * FROM scattered;
CREATE TABLE places AS SELECT * FROM rtree_scattered_geom;
DROP TABLE scattered;
CREATE TABLE scattered {layout};
INSERT INTO scattered SELECT {new_fid}, geom{taken} FROM rows ORDER BY fid;
DELETE FROM rtree_scattered_geom;
INSERT INTO rtree_scattered_geom SELECT {}, minx, maxx, miny, maxy FROM places;",
new_fid.replace("fid", "id")
))
.unwrap();
}
let src = open_path(&p, None).unwrap();
let read = |extent, limit| -> Vec<u64> {
src.read(&Request { extent, limit, own: None }).unwrap().features.iter().map(|f| f.id).collect()
};
let whole = read(None, 10_000);
assert_eq!(whole.len(), 1200);
// The table's order is the keys' only where the first is written.
assert_eq!(whole.first(), Some(if n == 0 { &1 } else { &1200 }), "{layout:?}");
let all = Some(Extent::new(-1.0, -1.0, 41.0, 31.0));
assert_eq!(read(all, 10_000), whole, "{layout:?}");
// A sample of them, in the same order.
let sample = read(all, 700);
assert_eq!(sample.len(), 600);
assert!(sample.is_sorted_by_key(|id| whole.iter().position(|w| w == id)), "{layout:?}");
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
}
}

/// The browser's GeoPackage reader (pure Rust) gives what SQLite gives, without the R-tree.
#[test]
fn geopackage_in_memory() {
Expand Down
Loading