From ff240318bfb69f41d432fe167457623e8668ebf0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 08:45:23 -0600 Subject: [PATCH 1/5] fix(data): a streamed GeoPackage draws its features in the table's order (#1227) A view read through a GeoPackage's R-tree gave features in the index's order, fetched 500 at a time, while a whole read gives them in the table's order. A streamed layer therefore drew overlapping features stacked differently from the same layer loaded, and the stacking depended on which features the view selected. The ids the index picks are now sorted before they are fetched. The same features are picked, sampled views included. --- crates/data/src/source/gpkg.rs | 5 ++++- crates/data/src/source/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 904f805f67..10c2bb8940 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -531,13 +531,16 @@ 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 = st + let mut picked: Vec = st .query_map(args, |r| r.get(0)) .map_err(err)? .step_by(step.max(1)) .take(limit) .collect::>() .map_err(err)?; + // The index lists them in its own order. Fetched by ascending id, they come in + // the table's, as a whole read gives them: the order the map draws them in. + picked.sort_unstable(); out.complete = step == 1; for chunk in picked.chunks(CHUNK) { let marks = vec!["?"; chunk.len()].join(","); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 7fb0d4625f..95d87773fc 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -1091,6 +1091,32 @@ 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![]); + } + let p = dir().join("scattered.gpkg"); + crate::io::write_path(&ds, &p).unwrap(); + let src = open_path(&p, None).unwrap(); + assert!(src.info().indexed); + let read = + |extent, limit| -> Vec { 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); + let all = Some(Extent::new(-1.0, -1.0, 41.0, 31.0)); + assert_eq!(read(all, 10_000), whole); + // A sample of them: every other one the index lists. + let sample = read(all, 700); + assert_eq!(sample.len(), 600); + assert!(sample.is_sorted()); +} + /// The browser's GeoPackage reader (pure Rust) gives what SQLite gives, without the R-tree. #[test] fn geopackage_in_memory() { From afebe18b4e178cb33bc3889cb9e66d820cff0285 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 09:24:39 -0600 Subject: [PATCH 2/5] fix(data): keep the table's order for a GeoPackage key apart from the rowid A key declared INT rather than INTEGER is a column of its own, so ids sorted by key aren't in the table's order. For such a table the ids the R-tree picks are listed in rowid order, and each fetch says its order. --- crates/data/src/source/gpkg.rs | 29 +++++++++++++++---- crates/data/src/source/tests.rs | 49 +++++++++++++++++++++++---------- 2 files changed, 59 insertions(+), 19 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 10c2bb8940..9ab5e07b7f 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -29,6 +29,9 @@ pub struct GpkgSource { table: String, geom: String, pk: Option, + /// Whether the key isn't the table's rowid (declared `INT PRIMARY KEY`, say, not `INTEGER`), + /// so the table's order isn't the key's. + rowid_apart: bool, rtree: Option, reproject: Reproject, /// A copy written for a file opened from memory, removed when the source is dropped. @@ -286,6 +289,10 @@ impl GpkgSource { } } } + // SQLite indexes a primary key that isn't the rowid itself. A table without rowids has + // such an index too, and its order is the key's. + let rowid_apart = conn.query_row("SELECT 1 FROM pragma_index_list(?1) WHERE origin = 'pk'", [&table], |_| Ok(())).is_ok() + && conn.prepare(&format!("SELECT _rowid_ FROM {}", quote(&table))).is_ok(); // 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 = conn @@ -361,6 +368,7 @@ impl GpkgSource { table, geom, pk, + rowid_apart, rtree, reproject, temp: None, @@ -529,7 +537,15 @@ impl FeatureSource for GpkgSource { let n: i64 = conn.query_row(&format!("SELECT COUNT(*) {filter}"), args, |r| r.get(0)).map_err(err)?; out.matched = u64::try_from(n).unwrap_or(0); 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)?; + let (table, key) = (quote(&self.table), quote(pk)); + // A key apart from the rowid doesn't follow the table's order: the table lists the + // ids in it. + let ids = if self.rowid_apart { + format!("SELECT {key} FROM {table} WHERE {key} IN (SELECT id {filter}) ORDER BY _rowid_") + } else { + format!("SELECT id {filter}") + }; + let mut st = conn.prepare(&ids).map_err(err)?; // A row error (a corrupt page) fails the read rather than truncating it quietly. let mut picked: Vec = st .query_map(args, |r| r.get(0)) @@ -538,13 +554,16 @@ impl FeatureSource for GpkgSource { .take(limit) .collect::>() .map_err(err)?; - // The index lists them in its own order. Fetched by ascending id, they come in - // the table's, as a whole read gives them: the order the map draws them in. - picked.sort_unstable(); + // 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. + if !self.rowid_apart { + picked.sort_unstable(); + } + let order = if self.rowid_apart { "_rowid_" } else { &key }; out.complete = step == 1; 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 {key} IN ({marks}) ORDER BY {order}", self.select_list()); 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)? { diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 95d87773fc..f366a2081d 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -1101,20 +1101,41 @@ fn geopackage_view_reads_keep_the_tables_order() { let at = i * 719 % 1200; ds.push(Some(Geometry::Point(Coord::new(f64::from(at % 40), f64::from(at / 40)))), vec![]); } - let p = dir().join("scattered.gpkg"); - crate::io::write_path(&ds, &p).unwrap(); - let src = open_path(&p, None).unwrap(); - assert!(src.info().indexed); - let read = - |extent, limit| -> Vec { 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); - let all = Some(Extent::new(-1.0, -1.0, 41.0, 31.0)); - assert_eq!(read(all, 10_000), whole); - // A sample of them: every other one the index lists. - let sample = read(all, 700); - assert_eq!(sample.len(), 600); - assert!(sample.is_sorted()); + // The key a GeoPackage asks for is the rowid. One declared `INT` is a column of its own, here + // numbered against the table's order. + for key_is_rowid in [true, false] { + let p = dir().join(format!("scattered-{key_is_rowid}.gpkg")); + crate::io::write_path(&ds, &p).unwrap(); + if !key_is_rowid { + rusqlite::Connection::open(&p) + .unwrap() + .execute_batch( + "CREATE TABLE rows AS SELECT * FROM scattered; + CREATE TABLE places AS SELECT * FROM rtree_scattered_geom; + DROP TABLE scattered; + CREATE TABLE scattered (fid INT PRIMARY KEY, geom MULTIPOINT); + INSERT INTO scattered (fid, geom) SELECT 1201 - fid, geom FROM rows ORDER BY fid; + DELETE FROM rtree_scattered_geom; + INSERT INTO rtree_scattered_geom SELECT 1201 - id, minx, maxx, miny, maxy FROM places;", + ) + .unwrap(); + } + let src = open_path(&p, None).unwrap(); + assert!(src.info().indexed); + let read = |extent, limit| -> Vec { + src.read(&Request { extent, limit, own: None }).unwrap().features.iter().map(|f| f.id).collect() + }; + let in_order = |ids: &[u64]| ids.is_sorted_by(|a, b| if key_is_rowid { a < b } else { a > b }); + let whole = read(None, 10_000); + assert_eq!(whole.len(), 1200); + assert!(in_order(&whole)); + let all = Some(Extent::new(-1.0, -1.0, 41.0, 31.0)); + assert_eq!(read(all, 10_000), whole); + // A sample of them: every other one. + let sample = read(all, 700); + assert_eq!(sample.len(), 600); + assert!(in_order(&sample)); + } } /// The browser's GeoPackage reader (pure Rust) gives what SQLite gives, without the R-tree. From 449593c7c7ef053fe47f1a4caf41fbd279857342 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 10:24:30 -0600 Subject: [PATCH 3/5] fix(data): a view of a GeoPackage with an unusual key is sampled as before The R-tree's ids are sampled in the index's order again. Where the key is apart from the rowid, the rowids of the sampled keys then order the fetches, under a rowid name no column has taken. A table without such a name (without rowids, say) is read by a scan, which gives its own order. --- crates/data/src/source/gpkg.rs | 81 +++++++++++++++++++++++---------- crates/data/src/source/tests.rs | 43 ++++++++++------- 2 files changed, 83 insertions(+), 41 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 9ab5e07b7f..c89b5e758d 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -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, @@ -29,9 +41,7 @@ pub struct GpkgSource { table: String, geom: String, pk: Option, - /// Whether the key isn't the table's rowid (declared `INT PRIMARY KEY`, say, not `INTEGER`), - /// so the table's order isn't the key's. - rowid_apart: bool, + row_order: RowOrder, rtree: Option, reproject: Reproject, /// A copy written for a file opened from memory, removed when the source is dropped. @@ -289,10 +299,7 @@ impl GpkgSource { } } } - // SQLite indexes a primary key that isn't the rowid itself. A table without rowids has - // such an index too, and its order is the key's. - let rowid_apart = conn.query_row("SELECT 1 FROM pragma_index_list(?1) WHERE origin = 'pk'", [&table], |_| Ok(())).is_ok() - && conn.prepare(&format!("SELECT _rowid_ FROM {}", quote(&table))).is_ok(); + let row_order = row_order(&conn, &table); // 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 = conn @@ -357,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, }; @@ -368,7 +375,7 @@ impl GpkgSource { table, geom, pk, - rowid_apart, + row_order, rtree, reproject, temp: None, @@ -528,7 +535,7 @@ impl FeatureSource for GpkgSource { Row::Bad => out.skipped += 1, }; match (native, &self.rtree, &self.pk) { - (Some(e), Some(rt), Some(pk)) => { + (Some(e), Some(rt), Some(pk)) if !matches!(self.row_order, RowOrder::Scan) => { // 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. @@ -537,15 +544,7 @@ impl FeatureSource for GpkgSource { let n: i64 = conn.query_row(&format!("SELECT COUNT(*) {filter}"), args, |r| r.get(0)).map_err(err)?; out.matched = u64::try_from(n).unwrap_or(0); let step = usize::try_from(stride(out.matched, limit)).unwrap_or(usize::MAX); - let (table, key) = (quote(&self.table), quote(pk)); - // A key apart from the rowid doesn't follow the table's order: the table lists the - // ids in it. - let ids = if self.rowid_apart { - format!("SELECT {key} FROM {table} WHERE {key} IN (SELECT id {filter}) ORDER BY _rowid_") - } else { - format!("SELECT id {filter}") - }; - let mut st = conn.prepare(&ids).map_err(err)?; + 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 mut picked: Vec = st .query_map(args, |r| r.get(0)) @@ -554,16 +553,21 @@ impl FeatureSource for GpkgSource { .take(limit) .collect::>() .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. - if !self.rowid_apart { - picked.sort_unstable(); - } - let order = if self.rowid_apart { "_rowid_" } else { &key }; - out.complete = step == 1; + let by = match self.row_order { + RowOrder::Rowid(rowid) => { + picked = rowids(conn, &table, rowid, "e(pk), &picked).map_err(err)?; + 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 {table} WHERE {key} IN ({marks}) ORDER BY {order}", self.select_list()); + let sql = format!("SELECT {} FROM {table} WHERE {by} IN ({marks}) ORDER BY {by}", self.select_list()); 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)? { @@ -673,6 +677,33 @@ impl FeatureSource for GpkgSource { } } +/// How to fetch rows of `table` in a scan's order ([`RowOrder`]). +fn row_order(conn: &Connection, table: &str) -> 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(())).is_err() { + return RowOrder::Key; + } + // A column takes a rowid's name from it; a table without rowids has none of them. + let free = |name: &&str| { + let taken = "SELECT 1 FROM pragma_table_xinfo(?1) WHERE lower(name) = ?2"; + conn.query_row(taken, [table, name], |_| Ok(())).is_err() && conn.prepare(&format!("SELECT {name} FROM {}", quote(table))).is_ok() + }; + ["rowid", "_rowid_", "oid"].into_iter().find(free).map_or(RowOrder::Scan, RowOrder::Rowid) +} + +/// 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> { + 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)> { diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index f366a2081d..bd0d25e4cb 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -1101,40 +1101,51 @@ fn geopackage_view_reads_keep_the_tables_order() { let at = i * 719 % 1200; ds.push(Some(Geometry::Point(Coord::new(f64::from(at % 40), f64::from(at / 40)))), vec![]); } - // The key a GeoPackage asks for is the rowid. One declared `INT` is a column of its own, here - // numbered against the table's order. - for key_is_rowid in [true, false] { - let p = dir().join(format!("scattered-{key_is_rowid}.gpkg")); + // 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 !key_is_rowid { + 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( + .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 (fid INT PRIMARY KEY, geom MULTIPOINT); - INSERT INTO scattered (fid, geom) SELECT 1201 - fid, geom FROM rows ORDER BY fid; + 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 1201 - id, minx, maxx, miny, maxy FROM places;", - ) + 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(); - assert!(src.info().indexed); let read = |extent, limit| -> Vec { src.read(&Request { extent, limit, own: None }).unwrap().features.iter().map(|f| f.id).collect() }; - let in_order = |ids: &[u64]| ids.is_sorted_by(|a, b| if key_is_rowid { a < b } else { a > b }); let whole = read(None, 10_000); assert_eq!(whole.len(), 1200); - assert!(in_order(&whole)); + // 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); - // A sample of them: every other one. + 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!(in_order(&sample)); + assert!(sample.is_sorted_by_key(|id| whole.iter().position(|w| w == id)), "{layout:?}"); } } From 6e316861623dbd79dad5a957149e04c9bc39f202 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 11:10:23 -0600 Subject: [PATCH 4/5] fix(data): a GeoPackage view counts by its index, reads in one snapshot, and whole reads name their order A count alone stays on the R-tree path for a table read by a scan. Picking ids, looking up their rowids and fetching by them run in one read, so a write between them can't hand back a row that wasn't picked. Whole reads order by the key or rowid a view read fetches by, which a scan of the table gives without a sort, so the planner can't read them down another index. --- crates/data/src/source/gpkg.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index c89b5e758d..0c04b1595c 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -441,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. + 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`. @@ -535,7 +548,12 @@ impl FeatureSource for GpkgSource { Row::Bad => out.skipped += 1, }; match (native, &self.rtree, &self.pk) { - (Some(e), Some(rt), Some(pk)) if !matches!(self.row_order, RowOrder::Scan) => { + // 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. @@ -583,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 @@ -656,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() }; From 4c9ed9ad370529628738e664ed64a83b82bacd7e Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 11:54:19 -0600 Subject: [PATCH 5/5] fix(data): a failed statement fails a GeoPackage's open instead of choosing its read order Only "no such row" answers whether a table has a primary-key index or a column takes a rowid's name; another failure now fails the open, as the rest of it does, instead of picking an order unseen. --- crates/data/src/source/gpkg.rs | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 0c04b1595c..404f313fc8 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -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; @@ -299,7 +299,7 @@ impl GpkgSource { } } } - let row_order = row_order(&conn, &table); + 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 = conn @@ -695,18 +695,25 @@ impl FeatureSource for GpkgSource { } } -/// How to fetch rows of `table` in a scan's order ([`RowOrder`]). -fn row_order(conn: &Connection, table: &str) -> RowOrder { +/// 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 { // 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(())).is_err() { - return RowOrder::Key; + 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. - let free = |name: &&str| { + // 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"; - conn.query_row(taken, [table, name], |_| Ok(())).is_err() && conn.prepare(&format!("SELECT {name} FROM {}", quote(table))).is_ok() - }; - ["rowid", "_rowid_", "oid"].into_iter().find(free).map_or(RowOrder::Scan, RowOrder::Rowid) + 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`.