From 70a0aafec24b6248e9ef4967c2e366bc14027404 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 07:01:27 -0500 Subject: [PATCH 01/10] fix(data): take a GeoPackage table's count from gpkg_ogr_contents and stop at the first table read in place (#2849) Add Data counted every table of a GeoPackage with COUNT(*) before asking whether to copy or link it, and layer.addData counted them again. A table's count is now the one GDAL keeps in gpkg_ogr_contents when the file has a whole, non-negative one; otherwise its rows are counted as before. A table with Z or M on every geometry keeps its single scan, which also counts its geometries. link_choice stops at the first table read in place, since one links them all. --- crates/data/src/source/gpkg.rs | 35 ++++++++-- crates/data/src/source/tests.rs | 57 +++++++++++++++++ crates/engine/src/cmd/layer.rs | 27 ++++---- .../engine/tests/integration/link_choice.rs | 64 +++++++++++++++++++ docs/user-guide/data-formats.md | 2 +- 5 files changed, 168 insertions(+), 17 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index a6f86f2dbc..df6ab6122b 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -151,6 +151,26 @@ fn has_table(conn: &Connection, name: &str) -> Result { .map_err(err) } +/// The feature count GDAL keeps for `table` in `gpkg_ogr_contents`, used as the table's count +/// when the file also has the two triggers that keep it up to date +/// (`trigger_insert_feature_count_` and `trigger_delete_feature_count_
`, which add or +/// take one per insert and delete, RustGIS's edits included); GDAL answers a table's count with it +/// too. GDAL may drop the triggers while it writes and create them again when it saves the file, +/// so a file without them may hold an out-of-date count. `None` then, when there is no such table +/// or row (a file GDAL didn't write), or when the count isn't a whole number from zero up (NULL, +/// text, a negative): the table is counted instead. +fn kept_count(conn: &Connection, table: &str) -> Option { + conn.query_row( + "SELECT feature_count FROM gpkg_ogr_contents + WHERE lower(table_name) = lower(?1) AND typeof(feature_count) = 'integer' AND feature_count >= 0 + AND (SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND lower(name) IN + (lower('trigger_insert_feature_count_' || ?1), lower('trigger_delete_feature_count_' || ?1))) = 2", + [table], + |r| r.get(0), + ) + .ok() +} + fn feature_tables(conn: &Connection) -> Result> { if !has_geometry_columns(conn)? { if !has_table(conn, "gpkg_contents")? { @@ -280,15 +300,20 @@ impl GpkgSource { Ok((r.get(0)?, r.get(1)?)) }) .ok(); - // Rows; with Z or M declared for every geometry, also the rows with one (what the note on - // them counts), in the same scan. Counting geometries reads every blob, so only then. + // Rows: the count GDAL keeps ([`kept_count`]), so a large table isn't scanned to count it + // (#2849), else counted. With Z or M declared for every geometry, also the rows with one + // (what the note on them counts), in the same scan. Counting geometries reads every blob, + // so only then. let mandatory = zm.is_some_and(|(z, m)| z == 1 || m == 1); let counted = if mandatory { format!("COUNT({})", quote(&geom)) } else { "0".into() }; - let counts = conn - .query_row(&format!("SELECT COUNT(*), {counted} FROM {}", quote(&table)), [], |r| { + let kept = if mandatory { None } else { kept_count(&conn, &table) }; + // The second value is read only when `mandatory`, which a kept count never is. + let counts = kept.map(|n| (n, 0)).or_else(|| { + conn.query_row(&format!("SELECT COUNT(*), {counted} FROM {}", quote(&table)), [], |r| { Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)) }) - .ok(); + .ok() + }); let count = counts.and_then(|(n, _)| u64::try_from(n).ok()); let geometries = counts.filter(|_| mandatory).and_then(|(_, g)| u64::try_from(g).ok()); let geometry_type = match geom_type.to_ascii_uppercase().as_str() { diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 665e7d1807..66c555d1ab 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3785,6 +3785,63 @@ fn gpkg_tables(path: &Path) -> Vec { st.query_map([], |r| r.get(0)).unwrap().collect::>().unwrap() } +/// A table's count is the one GDAL keeps in `gpkg_ogr_contents`, when it keeps one with the +/// triggers that keep it up to date, so a large table isn't scanned to count it (#2849); else its +/// rows are counted, as before. A table with Z or M on every geometry is still scanned, as that +/// scan also counts its geometries. +#[test] +fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { + let workspace = tempfile::tempdir().unwrap(); + let mut parcels = Dataset::new("parcels", GeometryType::Point, vec![Field::new("apn", FieldType::Text)]); + for i in 0..3 { + parcels.push(Some(Geometry::Point(Coord::new(f64::from(i), 2.0))), vec![Value::Text(format!("00{i}"))]); + } + // The table of counts and the triggers GDAL keeps it with, as GDAL writes them. + let kept = "DROP TABLE IF EXISTS gpkg_ogr_contents; + CREATE TABLE gpkg_ogr_contents (table_name TEXT NOT NULL PRIMARY KEY, feature_count INTEGER DEFAULT NULL); + CREATE TRIGGER \"trigger_insert_feature_count_parcels\" AFTER INSERT ON \"parcels\" BEGIN UPDATE gpkg_ogr_contents + SET feature_count = feature_count + 1 WHERE lower(table_name) = lower('parcels'); END; + CREATE TRIGGER \"trigger_delete_feature_count_parcels\" AFTER DELETE ON \"parcels\" BEGIN UPDATE gpkg_ogr_contents + SET feature_count = feature_count - 1 WHERE lower(table_name) = lower('parcels'); END;"; + // The file's three rows, against what the table of counts says. + let cases = [ + ("kept", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000);"), 250_000), + ("kept zero", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 0);"), 0), + ("upper-case name", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('PARCELS', 7);"), 7), + // The column's INTEGER affinity stores text digits as a number. + ("digits as text", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', '250000');"), 250_000), + // Without either trigger nothing kept it up to date (GDAL drops them while it writes). + ( + "no insert trigger", + format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000); DROP TRIGGER trigger_insert_feature_count_parcels;"), + 3, + ), + ( + "no delete trigger", + format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000); DROP TRIGGER trigger_delete_feature_count_parcels;"), + 3, + ), + ("null", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', NULL);"), 3), + ("no table", "DROP TABLE IF EXISTS gpkg_ogr_contents;".to_string(), 3), + ("no row", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('roads', 9);"), 3), + ("negative", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', -5);"), 3), + ("text", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 'many');"), 3), + ("fraction", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 2.5);"), 3), + ( + "z on every geometry", + format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000); UPDATE gpkg_geometry_columns SET z = 1;"), + 3, + ), + ]; + for (case, sql, count) in cases { + let path = workspace.path().join(format!("{}.gpkg", case.replace(' ', "-"))); + crate::io::write_path(&parcels, &path).unwrap(); + rusqlite::Connection::open(&path).unwrap().execute_batch(&sql).unwrap(); + let src = open_path(&path, Some("parcels")).unwrap(); + assert_eq!(src.info().count, Some(count), "{case}"); + } +} + /// Text in a date-time field with digits past the microsecond is written as a read takes it: as /// that date-time, to the millisecond and counted, not kept as text a read would call no date. #[test] diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 7c51753a1d..89781a808c 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -27,7 +27,7 @@ pub fn commands() -> Vec { ), C::new("info.fileLayers", "List Layers in File", "Home › Add › Add Data", file_layers).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .params(r#"{"path": string, "crs"?: "EPSG:… for a CityJSON model (.city.json, a .json, or in a zip) or a CityGML model (.gml, .xml, or in a zip): it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows (as layer.addData)", "link"?: "bool: for a file Add Data can link instead of copying (GeoPackage, GeoParquet, FlatGeobuf, Shapefile, .geojson; desktop), also say how it would take it, as link: linked (what it does without stream; for a .geojson, by its size alone, so Add Data sends the answer, as layer.addData unasked also looks at its count) and copy (whether it can be read whole); it opens each table, so only when asked"}"#), + .params(r#"{"path": string, "crs"?: "EPSG:… for a CityJSON model (.city.json, a .json, or in a zip) or a CityGML model (.gml, .xml, or in a zip): it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows (as layer.addData)", "link"?: "bool: for a file Add Data can link instead of copying (GeoPackage, GeoParquet, FlatGeobuf, Shapefile, .geojson; desktop), also say how it would take it, as link: linked (what it does without stream; for a .geojson, by its size alone, so Add Data sends the answer, as layer.addData unasked also looks at its count) and copy (whether it can be read whole); it opens the tables, up to the first read in place, so only when asked"}"#), C::new("info.fileColumns", "List Columns in File", "Home › Add › Add Data › Delimited Text", file_columns).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().params( r#"{"path": "a delimited text file (CSV, TSV, TXT, DAT, or gzip-compressed text) or a spreadsheet", "delimiter"?: ","|";"|"\\t"|"|", "layer"?: "a spreadsheet's sheet (the first by default)", "crs"?: "EPSG:… (or WKT), as layer.addData: a projected system keeps the columns found by name"}"#, ), @@ -2525,12 +2525,13 @@ fn streams_by_count(count: Option) -> bool { /// before), files read whole, and those it can't open (`layer.addData` then says why). /// `linked` is what `layer.addData` does without `"stream"`, by the same rules /// ([`streams_geojson`], [`past_cap_shapefile`] and [`streams_shapefile`], [`streams_by_count`], -/// linked when any table would be), except a `.geojson` file: by its size alone, as reading its -/// count means parsing it, so Add Data always sends the answer (`layer.addData` unasked, once it -/// reads such a file in place, also copies one of few features). A Cancel stops it between -/// tables, with no question. `copy` is whether it can be read whole: a GeoJSON file or a -/// Shapefile (and its `.dbf`) within [`rustgis_data::io::max_bytes`]; a source's whole read is -/// bounded where it is read. +/// linked when any table would be: the tables are opened in turn up to the first that would), +/// except a `.geojson` file: by its size alone, as reading its count means parsing it, so Add +/// Data always sends the answer (`layer.addData` unasked, once it reads such a file in place, +/// also copies one of few features). A Cancel is looked at before each table is opened: the table +/// being opened when it comes finishes, and no question is made. `copy` is whether it can be read +/// whole: a GeoJSON file or a Shapefile (and its `.dbf`) within [`rustgis_data::io::max_bytes`]; +/// a source's whole read is bounded where it is read. #[cfg(not(target_arch = "wasm32"))] fn link_choice(path: &str, tables: &[String]) -> Option { let lower = path.to_ascii_lowercase(); @@ -2546,10 +2547,14 @@ fn link_choice(path: &str, tables: &[String]) -> Option { let gpkg = lower.ends_with(".gpkg"); let mut linked = false; for table in tables.iter().map(|t| gpkg.then_some(t.as_str())) { - // Cancel (the chooser closed) is looked at between tables: each open counts its rows. + // Cancel (the chooser closed) is looked at between tables: an open may count its rows. rustgis_data::progress::check().ok()?; let src = rustgis_data::source::open_path(Path::new(path), table).ok()?; - linked |= streams_by_count(src.info().count); + // One table read in place links them all, so those after it aren't opened. + if streams_by_count(src.info().count) { + linked = true; + break; + } } (linked, true) } else { @@ -3119,8 +3124,8 @@ fn apply_styles(s: &mut Session, id: u32, styles: &[(String, rustgis_data::kml:: /// The layers a file holds, without adding them: a GeoPackage's feature tables, a GDAL dataset's /// layers, or the one layer of other files. `layer.addData` takes a name with `"layer"`. A file /// Add Data can link instead of copying says how it would take it, in `"link"`, when `"link": true` -/// asks ([`link_choice`]): it opens each of a GeoPackage's tables, which the other callers (List -/// Tables, Repair Data Source) don't need. +/// asks ([`link_choice`]): it opens a GeoPackage's tables, up to the first read in place, which +/// the other callers (List Tables, Repair Data Source) don't need. fn file_layers(s: &mut Session, p: &Value) -> CmdResult { #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] let mut v = listed_layers(s, p)?; diff --git a/crates/engine/tests/integration/link_choice.rs b/crates/engine/tests/integration/link_choice.rs index 14657f4630..96658b1fcf 100644 --- a/crates/engine/tests/integration/link_choice.rs +++ b/crates/engine/tests/integration/link_choice.rs @@ -111,6 +111,70 @@ fn a_geopackage_of_several_tables_has_one_choice_for_them_all() { assert!(plain.get("link").is_none(), "{plain}"); } +/// Sets the count GDAL keeps for `table` in `gpkg_ogr_contents`, with the triggers it keeps it by. +fn keep_count(path: &Path, table: &str, count: u64) { + rusqlite::Connection::open(path) + .unwrap() + .execute_batch(&format!( + "CREATE TABLE IF NOT EXISTS gpkg_ogr_contents (table_name TEXT NOT NULL PRIMARY KEY, feature_count INTEGER DEFAULT NULL); + INSERT OR REPLACE INTO gpkg_ogr_contents VALUES ('{table}', {count}); + CREATE TRIGGER \"trigger_insert_feature_count_{table}\" AFTER INSERT ON \"{table}\" BEGIN UPDATE gpkg_ogr_contents + SET feature_count = feature_count + 1 WHERE lower(table_name) = lower('{table}'); END; + CREATE TRIGGER \"trigger_delete_feature_count_{table}\" AFTER DELETE ON \"{table}\" BEGIN UPDATE gpkg_ogr_contents + SET feature_count = feature_count - 1 WHERE lower(table_name) = lower('{table}'); END;" + )) + .unwrap(); +} + +#[test] +fn a_geopackage_is_linked_by_the_count_gdal_keeps() { + // One row in the file, but GDAL's count says it is past what is read whole: the question + // and `layer.addData` both go by that count, without counting the rows (#2849). + let f = Fixture::new("link-gpkg-kept"); + let path = f.file("survey.gpkg"); + gpkg_file(&path, &["roads", "wells"]); + keep_count(&path, "wells", rustgis_engine::map::source::STREAM_ABOVE + 1); + let mut s = session(); + assert_eq!(listed(&mut s, &path)["link"], json!({"linked": true, "copy": true})); + let mut s = session(); + let id = s.run("layer.addData", &json!({"path": path, "layer": "wells"})).unwrap()["layer"].as_u64().unwrap() as u32; + assert!(s.map().layer(id).unwrap().is_streamed(), "layer.addData reads it in place too"); +} + +#[test] +fn a_geopackage_stops_at_its_first_table_read_in_place() { + // Tables are listed by name. One read in place links them all, so those after it aren't + // opened: a table that can't be opened after it no longer leaves the file without a + // question (`layer.addData` says why when it is added); before it, it still does. + let f = Fixture::new("link-gpkg-first"); + let broken = |path: &Path, table: &str| { + // A table whose geometry column names no coordinate system can't be opened. + rusqlite::Connection::open(path) + .unwrap() + .execute(&format!("UPDATE gpkg_geometry_columns SET srs_id = NULL WHERE table_name = '{table}'"), []) + .unwrap(); + }; + let mut s = session(); + let after = f.file("after.gpkg"); + gpkg_file(&after, &["a_large", "b_broken"]); + keep_count(&after, "a_large", rustgis_engine::map::source::STREAM_ABOVE + 1); + broken(&after, "b_broken"); + assert_eq!(listed(&mut s, &after)["link"], json!({"linked": true, "copy": true})); + // Adding it is where the broken table is said. + assert!(s.run("layer.addData", &json!({"path": after, "layer": "b_broken", "stream": true})).is_err()); + let before = f.file("before.gpkg"); + gpkg_file(&before, &["a_broken", "b_large"]); + keep_count(&before, "b_large", rustgis_engine::map::source::STREAM_ABOVE + 1); + broken(&before, "a_broken"); + let v = listed(&mut s, &before); + assert!(v.get("link").is_none(), "{v}"); + // The last table read in place links them all too. + let last = f.file("last.gpkg"); + gpkg_file(&last, &["a_small", "b_small", "c_large"]); + keep_count(&last, "c_large", rustgis_engine::map::source::STREAM_ABOVE + 1); + assert_eq!(listed(&mut s, &last)["link"], json!({"linked": true, "copy": true})); +} + #[test] fn a_geojson_file_read_whole_is_copied_whatever_its_count() { // Up to its size it is read whole, so many features still give a copy, as the question says. diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 8fb6e945c8..280c4700cf 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -38,7 +38,7 @@ export names its feature. | AutoCAD DXF | `.dxf` (ASCII) | Add Data › DXF…, drop the file, or upload | Points, lines and polygons layers from the drawing's entities: POINT, LINE, LWPOLYLINE and POLYLINE (bulges drawn as arcs; closed ones stay lines; polyface meshes become polygons), CIRCLE, ARC, ELLIPSE, SPLINE, HELIX, LEADER, MLINE (its centre line), TEXT, MTEXT, ATTRIB and constant ATTDEF (points with their text, at the alignment point of justified text), HATCH boundaries (holes found by nesting), SOLID, TRACE and 3DFACE (polygons). Blocks (named in any case) are drawn where INSERTs place them (scaled, rotated, in arrays, nested up to 8 deep), and so are DIMENSIONs' blocks (a linear dimension without one draws its lines and measured text); `"blocks": false` leaves them out, with a notice of how many. Entities in an object's own coordinate system are turned into the drawing's. Fields: `layer`, `entity`, `color` (ACI, BYLAYER and BYBLOCK resolved), `linetype`, `text`, `height`, `rotation`, `block`, `elevation` and `paperspace`. `elevation` keeps the first placed vertex's height; varying heights are dropped with a counted notice. Unreadable POLYLINE XY vertices are left out with a counted notice. In a 3D POLYLINE, a vertex whose supplied Z cannot be read is also left out; an absent Z still means zero. Spline-path vertices without Y, short HATCH rings and coordinates beyond the per-entity limit in LWPOLYLINE/POLYLINE paths and bulged HATCH boundaries are left out with counted notices. The drawing's layouts (paper space: title blocks, viewport frames) are left out, with a notice, unless `"paperSpace": true`. A drawing never says its coordinate system: give `"crs"` (such as `EPSG:2263`) — the import dialog offers the map's — or its coordinates are kept as they are, with a notice. `"layer"` picks one of the drawing's own layers, and `info.fileLayers` lists them. Text is read as UTF-8, and otherwise in the drawing's `$DWGCODEPAGE` (GBK, Big5, Shift_JIS, Windows-1252…), so Chinese layer names and labels come through; an unknown or missing code page is read as Latin-1, with a notice. Up to 2 million features (500,000 in the web app). Not read: binary DXF, MULTILEADER, WIPEOUT, IMAGE and ACIS solids (3DSOLID, REGION), named in a notice. | | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | | LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Converted from the file's WKT or GeoTIFF-key record; without one, coordinates are kept with a notice. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | -| GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | +| GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. On the desktop, a table's feature count is the one GDAL keeps in `gpkg_ogr_contents`, when the file has one along with the triggers GDAL keeps it up to date by, so a large table isn't scanned to count it; otherwise its rows are counted (a table with Z or M on every geometry is always counted, as that also counts its geometries). Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | | GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | | Esri File Geodatabase | `.gdb` folder (desktop) | In Add Data pick a `.gdbtable` file inside it; or double-click the `.gdb` in the Browser, or drop the folder | The native reader loads up to 512 feature classes and tables, up to 2 GiB per table. Feature classes become layers and non-spatial tables standalone tables; dates are text. Coordinates use the EPSG/Esri code, else WKT; the WKT comes first when it gives another datum transformation than an EPSG code's, or another body's system. An Esri-only code still comes first, as ArcGIS keeps transformations apart from the system, with a notice when the WKT gives another one; a grid shift the WKT gives isn't applied, with a notice. `"layer"` picks one; `info.fileLayers` lists them. Multipatches become footprints with `z_min`, `z_max` and `height`; large or wall-only ones may use a convex hull. Curves become straight segments between their ends. Unreadable tables (compressed storage, raster fields or unsupported row indexes) are tried through GDAL when installed; otherwise they are named in a notice. | From a731a85ffdf258163cac4a0b8ee8d579b7f275ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 08:20:29 -0500 Subject: [PATCH 02/10] refactor(data): keep a GeoPackage table's row and geometry counts apart, and narrow the kept count's doc (#2849) --- crates/data/src/source/gpkg.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index df6ab6122b..62c6d591c6 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -154,8 +154,7 @@ fn has_table(conn: &Connection, name: &str) -> Result { /// The feature count GDAL keeps for `table` in `gpkg_ogr_contents`, used as the table's count /// when the file also has the two triggers that keep it up to date /// (`trigger_insert_feature_count_
` and `trigger_delete_feature_count_
`, which add or -/// take one per insert and delete, RustGIS's edits included); GDAL answers a table's count with it -/// too. GDAL may drop the triggers while it writes and create them again when it saves the file, +/// take one per insert and delete); GDAL answers a table's count with it too. GDAL may drop the triggers while it writes and create them again when it saves the file, /// so a file without them may hold an out-of-date count. `None` then, when there is no such table /// or row (a file GDAL didn't write), or when the count isn't a whole number from zero up (NULL, /// text, a negative): the table is counted instead. @@ -307,15 +306,18 @@ impl GpkgSource { let mandatory = zm.is_some_and(|(z, m)| z == 1 || m == 1); let counted = if mandatory { format!("COUNT({})", quote(&geom)) } else { "0".into() }; let kept = if mandatory { None } else { kept_count(&conn, &table) }; - // The second value is read only when `mandatory`, which a kept count never is. - let counts = kept.map(|n| (n, 0)).or_else(|| { - conn.query_row(&format!("SELECT COUNT(*), {counted} FROM {}", quote(&table)), [], |r| { - Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)) - }) - .ok() - }); + // The rows, and the geometries when `mandatory`. + let counts: Option<(i64, Option)> = match kept { + Some(n) => Some((n, None)), + None => conn + .query_row(&format!("SELECT COUNT(*), {counted} FROM {}", quote(&table)), [], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)) + }) + .ok() + .map(|(n, g)| (n, mandatory.then_some(g))), + }; let count = counts.and_then(|(n, _)| u64::try_from(n).ok()); - let geometries = counts.filter(|_| mandatory).and_then(|(_, g)| u64::try_from(g).ok()); + let geometries = counts.and_then(|(_, g)| g).and_then(|g| u64::try_from(g).ok()); let geometry_type = match geom_type.to_ascii_uppercase().as_str() { "POINT" | "MULTIPOINT" => GeometryType::Point, "LINESTRING" | "MULTILINESTRING" | "CURVE" | "MULTICURVE" => GeometryType::Polyline, From e0c33abd8f12a55ef10d3685002402978e22f92c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 08:33:38 -0500 Subject: [PATCH 03/10] docs(data): say a GeoPackage's kept count is as right as GDAL's, INSERT OR REPLACE leaving it high (#2849) --- crates/data/src/source/gpkg.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 62c6d591c6..45d98db8d8 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -154,10 +154,13 @@ fn has_table(conn: &Connection, name: &str) -> Result { /// The feature count GDAL keeps for `table` in `gpkg_ogr_contents`, used as the table's count /// when the file also has the two triggers that keep it up to date /// (`trigger_insert_feature_count_
` and `trigger_delete_feature_count_
`, which add or -/// take one per insert and delete); GDAL answers a table's count with it too. GDAL may drop the triggers while it writes and create them again when it saves the file, -/// so a file without them may hold an out-of-date count. `None` then, when there is no such table -/// or row (a file GDAL didn't write), or when the count isn't a whole number from zero up (NULL, -/// text, a negative): the table is counted instead. +/// take one per insert and delete); GDAL answers a table's count with it too, and it is as right +/// as GDAL's: a row an `INSERT OR REPLACE` puts out fires no delete trigger (SQLite's +/// `recursive_triggers` is off by default), so such writes leave it high. GDAL may drop the +/// triggers while it writes and create them again when it saves the file, so a file without them +/// may hold an out-of-date count. `None` then, when there is no such table or row (a file GDAL +/// didn't write), or when the count isn't a whole number from zero up (NULL, text, a negative): +/// the table is counted instead. fn kept_count(conn: &Connection, table: &str) -> Option { conn.query_row( "SELECT feature_count FROM gpkg_ogr_contents From 413cce38da88331dba7cd932f622e29a659b3db9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 08:36:43 -0500 Subject: [PATCH 04/10] docs: say where Add Data takes a GeoPackage table's count, in the copy or link section (#2849) --- docs/user-guide/data-formats.md | 2 +- docs/user-guide/data.md | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 280c4700cf..8fb6e945c8 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -38,7 +38,7 @@ export names its feature. | AutoCAD DXF | `.dxf` (ASCII) | Add Data › DXF…, drop the file, or upload | Points, lines and polygons layers from the drawing's entities: POINT, LINE, LWPOLYLINE and POLYLINE (bulges drawn as arcs; closed ones stay lines; polyface meshes become polygons), CIRCLE, ARC, ELLIPSE, SPLINE, HELIX, LEADER, MLINE (its centre line), TEXT, MTEXT, ATTRIB and constant ATTDEF (points with their text, at the alignment point of justified text), HATCH boundaries (holes found by nesting), SOLID, TRACE and 3DFACE (polygons). Blocks (named in any case) are drawn where INSERTs place them (scaled, rotated, in arrays, nested up to 8 deep), and so are DIMENSIONs' blocks (a linear dimension without one draws its lines and measured text); `"blocks": false` leaves them out, with a notice of how many. Entities in an object's own coordinate system are turned into the drawing's. Fields: `layer`, `entity`, `color` (ACI, BYLAYER and BYBLOCK resolved), `linetype`, `text`, `height`, `rotation`, `block`, `elevation` and `paperspace`. `elevation` keeps the first placed vertex's height; varying heights are dropped with a counted notice. Unreadable POLYLINE XY vertices are left out with a counted notice. In a 3D POLYLINE, a vertex whose supplied Z cannot be read is also left out; an absent Z still means zero. Spline-path vertices without Y, short HATCH rings and coordinates beyond the per-entity limit in LWPOLYLINE/POLYLINE paths and bulged HATCH boundaries are left out with counted notices. The drawing's layouts (paper space: title blocks, viewport frames) are left out, with a notice, unless `"paperSpace": true`. A drawing never says its coordinate system: give `"crs"` (such as `EPSG:2263`) — the import dialog offers the map's — or its coordinates are kept as they are, with a notice. `"layer"` picks one of the drawing's own layers, and `info.fileLayers` lists them. Text is read as UTF-8, and otherwise in the drawing's `$DWGCODEPAGE` (GBK, Big5, Shift_JIS, Windows-1252…), so Chinese layer names and labels come through; an unknown or missing code page is read as Latin-1, with a notice. Up to 2 million features (500,000 in the web app). Not read: binary DXF, MULTILEADER, WIPEOUT, IMAGE and ACIS solids (3DSOLID, REGION), named in a notice. | | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | | LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Converted from the file's WKT or GeoTIFF-key record; without one, coordinates are kept with a notice. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | -| GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. On the desktop, a table's feature count is the one GDAL keeps in `gpkg_ogr_contents`, when the file has one along with the triggers GDAL keeps it up to date by, so a large table isn't scanned to count it; otherwise its rows are counted (a table with Z or M on every geometry is always counted, as that also counts its geometries). Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | +| GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | | GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | | Esri File Geodatabase | `.gdb` folder (desktop) | In Add Data pick a `.gdbtable` file inside it; or double-click the `.gdb` in the Browser, or drop the folder | The native reader loads up to 512 feature classes and tables, up to 2 GiB per table. Feature classes become layers and non-spatial tables standalone tables; dates are text. Coordinates use the EPSG/Esri code, else WKT; the WKT comes first when it gives another datum transformation than an EPSG code's, or another body's system. An Esri-only code still comes first, as ArcGIS keeps transformations apart from the system, with a notice when the WKT gives another one; a grid shift the WKT gives isn't applied, with a notice. `"layer"` picks one; `info.fileLayers` lists them. Multipatches become footprints with `z_min`, `z_max` and `height`; large or wall-only ones may use a convex hull. Curves become straight segments between their ends. Unreadable tables (compressed storage, raster fields or unsupported row indexes) are tried through GDAL when installed; otherwise they are named in a notice. | diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 5b21c575a2..eaae72f796 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1492,7 +1492,11 @@ past 32 MiB starts at Link, and stays linked even when it holds few features). A the file's path (relative to the project's folder when it can, so a folder moved whole keeps it), not its features: to edit it or define its projection, choose **Load All Features** first. A file too large to read whole can only be linked. A GeoPackage of several tables asks once, at the foot -of **Choose Layers**. A linked layer shows "(linked)" after its name in Layers, and Package Project +of **Choose Layers**; one table read in place links them all. A GeoPackage table's size is the +feature count GDAL keeps in `gpkg_ogr_contents`, when the file has one along with the triggers GDAL +keeps it up to date by, so a large table isn't scanned to count it; otherwise its rows are counted +(a table with Z or M on every geometry is always counted, as that also counts its geometries). A +linked layer shows "(linked)" after its name in Layers, and Package Project names the layers it leaves linked to files outside the package. LiDAR is always linked, and a `.json` file (which may be a city model) isn't asked about: it is linked or copied by the size rule above, as before. Files read whole are copied. From 306d7f7755b533159d602d7c8623513952f8f846 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 09:37:51 -0500 Subject: [PATCH 05/10] fix(data): a GeoPackage read doesn't start its sample from the kept count (#2849) --- crates/data/src/source/gpkg.rs | 38 +++++++++++++++++++++++++-------- crates/data/src/source/tests.rs | 4 ++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 45d98db8d8..158f34bc5e 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -36,6 +36,10 @@ pub struct GpkgSource { /// The database file and its identity when opened ([`file_identity`]), for a traversal on a /// connection of its own to check it reads the same file. file: Option<(PathBuf, Option<(u64, u64)>)>, + /// Whether `info.count` is the count GDAL keeps ([`kept_count`]) rather than the rows counted: + /// it may be past them (an `INSERT OR REPLACE` leaves it high, a file may say any number), so + /// a read doesn't start its sample's step from it. + count_kept: bool, } impl Drop for GpkgSource { @@ -156,11 +160,12 @@ fn has_table(conn: &Connection, name: &str) -> Result { /// (`trigger_insert_feature_count_
` and `trigger_delete_feature_count_
`, which add or /// take one per insert and delete); GDAL answers a table's count with it too, and it is as right /// as GDAL's: a row an `INSERT OR REPLACE` puts out fires no delete trigger (SQLite's -/// `recursive_triggers` is off by default), so such writes leave it high. GDAL may drop the -/// triggers while it writes and create them again when it saves the file, so a file without them -/// may hold an out-of-date count. `None` then, when there is no such table or row (a file GDAL -/// didn't write), or when the count isn't a whole number from zero up (NULL, text, a negative): -/// the table is counted instead. +/// `recursive_triggers` is off by default), so such writes leave it high. A read doesn't start +/// its sample's step from it (`GpkgSource::count_kept`), so a preview still gets the rows there +/// are. GDAL may drop the triggers while it writes and create them again when it saves the file, +/// so a file without them may hold an out-of-date count. `None` then, when there is no such table +/// or row (a file GDAL didn't write), or when the count isn't a whole number from zero up (NULL, +/// text, a negative): the table is counted instead. fn kept_count(conn: &Connection, table: &str) -> Option { conn.query_row( "SELECT feature_count FROM gpkg_ogr_contents @@ -342,7 +347,18 @@ impl GpkgSource { zm_dropped: false, }; let file = Some((path.to_path_buf(), id)); - let mut src = GpkgSource { info, conn: Mutex::new(Some(conn)), table, geom, pk, rtree, reproject, temp: None, file }; + let mut src = GpkgSource { + info, + conn: Mutex::new(Some(conn)), + table, + geom, + pk, + rtree, + reproject, + temp: None, + file, + count_kept: kept.is_some(), + }; if src.info.geometry_type == GeometryType::None { src.info.geometry_type = src.peek_kind(); } @@ -536,9 +552,13 @@ impl FeatureSource for GpkgSource { let sql = format!("SELECT {} FROM {}", self.select_list(), quote(&self.table)); let mut st = conn.prepare(&sql).map_err(err)?; let mut rows = st.query([]).map_err(err)?; - // A whole read knows its count; an extent, bounded natively or not, is matched as it goes. - let mut sample = - if req.extent.is_none() { Sampler::with_total(limit, self.info.count.unwrap_or(0)) } else { Sampler::new(limit) }; + // A whole read knows its count, unless the file's own; an extent, bounded natively + // or not, is matched as it goes. + let mut sample = if req.extent.is_none() && !self.count_kept { + Sampler::with_total(limit, self.info.count.unwrap_or(0)) + } else { + Sampler::new(limit) + }; crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); while let Some(r) = rows.next().map_err(err)? { crate::progress::step(1)?; diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 66c555d1ab..f54bfd29b2 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3839,6 +3839,10 @@ fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { rusqlite::Connection::open(&path).unwrap().execute_batch(&sql).unwrap(); let src = open_path(&path, Some("parcels")).unwrap(); assert_eq!(src.info().count, Some(count), "{case}"); + // A preview gets the rows there are, whatever the count says: a count past them (an + // `INSERT OR REPLACE` leaves it high, a file may say any number) doesn't thin it. + let preview = src.read(&Request { extent: None, limit: 100, own: None }).unwrap(); + assert_eq!((preview.features.len(), preview.complete), (3, true), "{case}"); } } From 84c822dc6c48f027d61b53a54ca25114d75dda77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 10:55:47 -0500 Subject: [PATCH 06/10] fix(data): a GeoPackage read with a kept count gives its progress no total; the triggers are the table's own; say when there is no kept count (#2849) --- crates/data/src/source/gpkg.rs | 18 ++++++++++++------ crates/data/src/source/tests.rs | 28 ++++++++++++++++++++++++++-- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 158f34bc5e..6e25efba7e 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -163,14 +163,14 @@ fn has_table(conn: &Connection, name: &str) -> Result { /// `recursive_triggers` is off by default), so such writes leave it high. A read doesn't start /// its sample's step from it (`GpkgSource::count_kept`), so a preview still gets the rows there /// are. GDAL may drop the triggers while it writes and create them again when it saves the file, -/// so a file without them may hold an out-of-date count. `None` then, when there is no such table -/// or row (a file GDAL didn't write), or when the count isn't a whole number from zero up (NULL, -/// text, a negative): the table is counted instead. +/// so a file without them may hold an out-of-date count. `None` then, and when there is no such +/// table or row (a file GDAL didn't write), or when the count isn't a whole number from zero up +/// (NULL, text, a negative): the table is counted instead. fn kept_count(conn: &Connection, table: &str) -> Option { conn.query_row( "SELECT feature_count FROM gpkg_ogr_contents WHERE lower(table_name) = lower(?1) AND typeof(feature_count) = 'integer' AND feature_count >= 0 - AND (SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND lower(name) IN + AND (SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND lower(tbl_name) = lower(?1) AND lower(name) IN (lower('trigger_insert_feature_count_' || ?1), lower('trigger_delete_feature_count_' || ?1))) = 2", [table], |r| r.get(0), @@ -191,6 +191,12 @@ fn feature_tables(conn: &Connection) -> Result> { } impl GpkgSource { + /// The total a scan of the table counts its progress against: none (unknown) for a kept count + /// (`count_kept`), which may be past the rows. + fn progress_total(&self) -> usize { + self.info.count.filter(|_| !self.count_kept).and_then(|n| usize::try_from(n).ok()).unwrap_or(0) + } + pub fn open(path: &Path, layer: Option<&str>) -> Result { // The identity is taken before the database is opened: a file put in its place after // this leaves it describing the file opened, which a traversal then refuses to swap. @@ -559,7 +565,7 @@ impl FeatureSource for GpkgSource { } else { Sampler::new(limit) }; - crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); + crate::progress::begin(self.progress_total()); while let Some(r) = rows.next().map_err(err)? { crate::progress::step(1)?; // With an extent, the envelope in the geometry's header says whether the row @@ -626,7 +632,7 @@ impl FeatureSource for GpkgSource { 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() }; - crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); + crate::progress::begin(self.progress_total()); while let Some(r) = rows.next().map_err(err)? { crate::progress::step(1)?; match self.feature(r, native.as_ref(), &req, &mut out.unread_dates, &mut out.rounded_dates).map_err(err)? { diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index f54bfd29b2..b47a8c9722 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3821,6 +3821,16 @@ fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000); DROP TRIGGER trigger_delete_feature_count_parcels;"), 3, ), + ( + "triggers on another table", + format!( + "{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000); + DROP TRIGGER trigger_insert_feature_count_parcels; DROP TRIGGER trigger_delete_feature_count_parcels; + CREATE TABLE other (v); CREATE TRIGGER trigger_insert_feature_count_parcels AFTER INSERT ON other BEGIN SELECT 1; END; + CREATE TRIGGER trigger_delete_feature_count_parcels AFTER DELETE ON other BEGIN SELECT 1; END;" + ), + 3, + ), ("null", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', NULL);"), 3), ("no table", "DROP TABLE IF EXISTS gpkg_ogr_contents;".to_string(), 3), ("no row", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('roads', 9);"), 3), @@ -3841,8 +3851,22 @@ fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { assert_eq!(src.info().count, Some(count), "{case}"); // A preview gets the rows there are, whatever the count says: a count past them (an // `INSERT OR REPLACE` leaves it high, a file may say any number) doesn't thin it. - let preview = src.read(&Request { extent: None, limit: 100, own: None }).unwrap(); - assert_eq!((preview.features.len(), preview.complete), (3, true), "{case}"); + // Its progress, and a whole read's (Load All), has the rows counted as its total, or none + // (unknown) for a kept count. + // The cases that count the rows get the file's 3; no case keeps a count of 3. + let total = if count == 3 { 3 } else { 0 }; + let watched = |read: &dyn Fn() -> usize| { + let probe = std::sync::Arc::new(crate::progress::tests::Counted::default()); + let _watched = crate::progress::install(Some(probe.clone())); + (read(), probe.total.load(std::sync::atomic::Ordering::Relaxed)) + }; + let preview = || { + let batch = src.read(&Request { extent: None, limit: 100, own: None }).unwrap(); + if batch.complete { batch.features.len() } else { 0 } + }; + assert_eq!(watched(&preview), (3, total), "{case}: preview"); + let whole = || materialize(src.as_ref()).unwrap().0.features.len(); + assert_eq!(watched(&whole), (3, total), "{case}: whole read"); } } From b6d409185a322a19258de8e2f40e32574684e145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 12:50:25 -0500 Subject: [PATCH 07/10] fix(engine): adding a GeoPackage whose kept counts add past the largest total says that total (#2849) --- crates/engine/src/cmd/layer.rs | 3 ++- crates/engine/tests/integration/link_choice.rs | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 89781a808c..97b0cf95d8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -3496,7 +3496,8 @@ fn add_source_read( s.active_layer = Some(id); ids.push(id); streamed = true; - features += info.count.unwrap_or(0); + // A file may keep any count (a GeoPackage's `gpkg_ogr_contents`): past the largest total, that. + features = features.saturating_add(info.count.unwrap_or(0)); s.notify( format!( "{unique}: {} features, read in place a view at a time (Load All Features loads them into memory)", diff --git a/crates/engine/tests/integration/link_choice.rs b/crates/engine/tests/integration/link_choice.rs index 96658b1fcf..346cccc2db 100644 --- a/crates/engine/tests/integration/link_choice.rs +++ b/crates/engine/tests/integration/link_choice.rs @@ -200,3 +200,18 @@ fn a_listing_stopped_between_tables_asks_nothing() { let v = listed(&mut s, &path); assert!(v.get("link").is_none(), "{v}"); } + +#[test] +fn a_geopackage_whose_kept_counts_add_past_the_largest_total_says_the_largest() { + // A file may keep any count: three tables at the largest one add past what a total holds, + // so `layer.addData` says the largest total rather than failing or wrapping (#2849). + let f = Fixture::new("link-gpkg-huge"); + let path = f.file("survey.gpkg"); + gpkg_file(&path, &["a", "b", "c"]); + for table in ["a", "b", "c"] { + keep_count(&path, table, i64::MAX as u64); + } + let mut s = session(); + let r = s.run("layer.addData", &json!({"path": path})).unwrap(); + assert_eq!((r["layers"].as_array().map(Vec::len), r["features"].as_u64()), (Some(3), Some(u64::MAX)), "{r}"); +} From 6d4521b478b1a1a7a7e3487203bffbe0788a1035 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 13:21:47 -0500 Subject: [PATCH 08/10] fix(engine): every sum of added features saturates, and each kept-count test case says whether its count is kept (#2849) --- crates/data/src/source/tests.rs | 31 ++++++++++--------- crates/engine/src/cmd/layer.rs | 10 +++--- .../engine/tests/integration/link_choice.rs | 7 +++-- 3 files changed, 26 insertions(+), 22 deletions(-) diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index b47a8c9722..4441514f34 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3803,23 +3803,25 @@ fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { SET feature_count = feature_count + 1 WHERE lower(table_name) = lower('parcels'); END; CREATE TRIGGER \"trigger_delete_feature_count_parcels\" AFTER DELETE ON \"parcels\" BEGIN UPDATE gpkg_ogr_contents SET feature_count = feature_count - 1 WHERE lower(table_name) = lower('parcels'); END;"; - // The file's three rows, against what the table of counts says. + // The file's three rows, against what the table of counts says, and whether the count is kept. let cases = [ - ("kept", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000);"), 250_000), - ("kept zero", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 0);"), 0), - ("upper-case name", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('PARCELS', 7);"), 7), + ("kept", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000);"), 250_000, true), + ("kept zero", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 0);"), 0, true), + ("upper-case name", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('PARCELS', 7);"), 7, true), // The column's INTEGER affinity stores text digits as a number. - ("digits as text", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', '250000');"), 250_000), + ("digits as text", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', '250000');"), 250_000, true), // Without either trigger nothing kept it up to date (GDAL drops them while it writes). ( "no insert trigger", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000); DROP TRIGGER trigger_insert_feature_count_parcels;"), 3, + false, ), ( "no delete trigger", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000); DROP TRIGGER trigger_delete_feature_count_parcels;"), 3, + false, ), ( "triggers on another table", @@ -3830,20 +3832,22 @@ fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { CREATE TRIGGER trigger_delete_feature_count_parcels AFTER DELETE ON other BEGIN SELECT 1; END;" ), 3, + false, ), - ("null", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', NULL);"), 3), - ("no table", "DROP TABLE IF EXISTS gpkg_ogr_contents;".to_string(), 3), - ("no row", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('roads', 9);"), 3), - ("negative", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', -5);"), 3), - ("text", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 'many');"), 3), - ("fraction", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 2.5);"), 3), + ("null", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', NULL);"), 3, false), + ("no table", "DROP TABLE IF EXISTS gpkg_ogr_contents;".to_string(), 3, false), + ("no row", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('roads', 9);"), 3, false), + ("negative", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', -5);"), 3, false), + ("text", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 'many');"), 3, false), + ("fraction", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 2.5);"), 3, false), ( "z on every geometry", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000); UPDATE gpkg_geometry_columns SET z = 1;"), 3, + false, ), ]; - for (case, sql, count) in cases { + for (case, sql, count, is_kept) in cases { let path = workspace.path().join(format!("{}.gpkg", case.replace(' ', "-"))); crate::io::write_path(&parcels, &path).unwrap(); rusqlite::Connection::open(&path).unwrap().execute_batch(&sql).unwrap(); @@ -3853,8 +3857,7 @@ fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { // `INSERT OR REPLACE` leaves it high, a file may say any number) doesn't thin it. // Its progress, and a whole read's (Load All), has the rows counted as its total, or none // (unknown) for a kept count. - // The cases that count the rows get the file's 3; no case keeps a count of 3. - let total = if count == 3 { 3 } else { 0 }; + let total = if is_kept { 0 } else { 3 }; let watched = |read: &dyn Fn() -> usize| { let probe = std::sync::Arc::new(crate::progress::tests::Counted::default()); let _watched = crate::progress::install(Some(probe.clone())); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 97b0cf95d8..d084881b6a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1997,7 +1997,7 @@ fn add_geodatabase(s: &mut Session, p: &Value, path: &str) -> CmdResult { // One result, as adding a single file gives it: every layer, the first, and the features. let layers: Vec = results.iter().filter_map(|r| r.get("layers").and_then(Value::as_array)).flatten().cloned().collect(); let tables: Vec = results.iter().filter_map(|r| r.get("tables").and_then(Value::as_array)).flatten().cloned().collect(); - let features: u64 = results.iter().filter_map(|r| r.get("features").and_then(Value::as_u64)).sum(); + let features = results.iter().filter_map(|r| r.get("features").and_then(Value::as_u64)).fold(0, u64::saturating_add); let mut out = json!({"layers": layers, "tables": tables, "features": features}); if let (Some(o), Some(first)) = (out.as_object_mut(), layers.first()) { o.insert("layer".into(), first.clone()); @@ -2958,7 +2958,7 @@ fn add_reads( } let layers: Vec = added.iter().filter_map(|r| r.get("layer").cloned()).collect(); let tables: Vec = added.iter().filter_map(|r| r.get("table").cloned()).collect(); - let features: u64 = added.iter().filter_map(|r| r.get("features").and_then(Value::as_u64)).sum(); + let features = added.iter().filter_map(|r| r.get("features").and_then(Value::as_u64)).fold(0, u64::saturating_add); let mut out = json!({"layers": layers, "tables": tables, "features": features}); // The first layer, as the result of adding a single file says it. if let Some(first) = layers.first() { @@ -3509,7 +3509,7 @@ fn add_source_read( let (mut ds, report) = whole.take().unwrap_or_else(|| source::materialize(src.as_ref())).map_err(err)?; ds.name = name; ds.source = Some(label.clone()); - features += ds.features.len() as u64; + features = features.saturating_add(ds.features.len() as u64); let id = add_dataset(s, ds); if let (Some(r), Some(l)) = (style.clone(), s.map_mut().layer_mut(id)) { l.renderer = r; @@ -4358,7 +4358,7 @@ fn add_live(s: &mut Session, p: &Value, db: &rustgis_data::source::duckdb::Datab } }; added = true; - features += r["features"].as_u64().unwrap_or(0); + features = features.saturating_add(r["features"].as_u64().unwrap_or(0)); streamed |= r["streamed"].as_bool().unwrap_or(false); ids.extend(r["layers"].as_array().into_iter().flatten().filter_map(Value::as_u64).filter_map(|i| u32::try_from(i).ok())); } @@ -4552,7 +4552,7 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: & } Err(e) => return Err(e), }; - features += r["features"].as_u64().unwrap_or(0); + features = features.saturating_add(r["features"].as_u64().unwrap_or(0)); streamed |= r["streamed"].as_bool().unwrap_or(false); for id in r["layers"].as_array().into_iter().flatten().filter_map(Value::as_u64).filter_map(|i| u32::try_from(i).ok()) { if let Some(l) = s.map_mut().layer_mut(id) { diff --git a/crates/engine/tests/integration/link_choice.rs b/crates/engine/tests/integration/link_choice.rs index 346cccc2db..93ded159f9 100644 --- a/crates/engine/tests/integration/link_choice.rs +++ b/crates/engine/tests/integration/link_choice.rs @@ -204,14 +204,15 @@ fn a_listing_stopped_between_tables_asks_nothing() { #[test] fn a_geopackage_whose_kept_counts_add_past_the_largest_total_says_the_largest() { // A file may keep any count: three tables at the largest one add past what a total holds, - // so `layer.addData` says the largest total rather than failing or wrapping (#2849). + // so `layer.addData` says the largest total rather than failing or wrapping (#2849), and a + // table read whole after them adds to that total without wrapping it either. let f = Fixture::new("link-gpkg-huge"); let path = f.file("survey.gpkg"); - gpkg_file(&path, &["a", "b", "c"]); + gpkg_file(&path, &["a", "b", "c", "d"]); for table in ["a", "b", "c"] { keep_count(&path, table, i64::MAX as u64); } let mut s = session(); let r = s.run("layer.addData", &json!({"path": path})).unwrap(); - assert_eq!((r["layers"].as_array().map(Vec::len), r["features"].as_u64()), (Some(3), Some(u64::MAX)), "{r}"); + assert_eq!((r["layers"].as_array().map(Vec::len), r["features"].as_u64()), (Some(4), Some(u64::MAX)), "{r}"); } From 5925c075dddfdf60abb667d6bb311ae082d787df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 13:56:31 -0500 Subject: [PATCH 09/10] fix(engine): a Cancel that comes while the last GeoPackage table opens gives no copy or link question, and a kept count is the table's own row's (#2849) --- crates/data/src/source/gpkg.rs | 3 ++- crates/data/src/source/tests.rs | 2 ++ crates/engine/src/cmd/layer.rs | 10 ++++---- .../engine/tests/integration/link_choice.rs | 23 +++++++++++++++++++ 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 6e25efba7e..7817b93769 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -171,7 +171,8 @@ fn kept_count(conn: &Connection, table: &str) -> Option { "SELECT feature_count FROM gpkg_ogr_contents WHERE lower(table_name) = lower(?1) AND typeof(feature_count) = 'integer' AND feature_count >= 0 AND (SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND lower(tbl_name) = lower(?1) AND lower(name) IN - (lower('trigger_insert_feature_count_' || ?1), lower('trigger_delete_feature_count_' || ?1))) = 2", + (lower('trigger_insert_feature_count_' || ?1), lower('trigger_delete_feature_count_' || ?1))) = 2 + ORDER BY table_name = ?1 DESC LIMIT 1", [table], |r| r.get(0), ) diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 4441514f34..232fed2d9d 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3808,6 +3808,8 @@ fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { ("kept", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 250000);"), 250_000, true), ("kept zero", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', 0);"), 0, true), ("upper-case name", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('PARCELS', 7);"), 7, true), + // Names differing in case are two rows (the key is case-sensitive): the table's own is taken. + ("a row for each case", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('PARCELS', 7), ('parcels', 250000);"), 250_000, true), // The column's INTEGER affinity stores text digits as a number. ("digits as text", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', '250000');"), 250_000, true), // Without either trigger nothing kept it up to date (GDAL drops them while it writes). diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index d084881b6a..dd71f7ed19 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2528,10 +2528,10 @@ fn streams_by_count(count: Option) -> bool { /// linked when any table would be: the tables are opened in turn up to the first that would), /// except a `.geojson` file: by its size alone, as reading its count means parsing it, so Add /// Data always sends the answer (`layer.addData` unasked, once it reads such a file in place, -/// also copies one of few features). A Cancel is looked at before each table is opened: the table -/// being opened when it comes finishes, and no question is made. `copy` is whether it can be read -/// whole: a GeoJSON file or a Shapefile (and its `.dbf`) within [`rustgis_data::io::max_bytes`]; -/// a source's whole read is bounded where it is read. +/// also copies one of few features). A Cancel is looked at before each table is opened and after +/// the last: the table being opened when it comes finishes, and no question is made. `copy` is +/// whether it can be read whole: a GeoJSON file or a Shapefile (and its `.dbf`) within +/// [`rustgis_data::io::max_bytes`]; a source's whole read is bounded where it is read. #[cfg(not(target_arch = "wasm32"))] fn link_choice(path: &str, tables: &[String]) -> Option { let lower = path.to_ascii_lowercase(); @@ -2556,6 +2556,8 @@ fn link_choice(path: &str, tables: &[String]) -> Option { break; } } + // And after the last one opened: a Cancel that came while it opened gives no question. + rustgis_data::progress::check().ok()?; (linked, true) } else { return None; diff --git a/crates/engine/tests/integration/link_choice.rs b/crates/engine/tests/integration/link_choice.rs index 93ded159f9..15800d2147 100644 --- a/crates/engine/tests/integration/link_choice.rs +++ b/crates/engine/tests/integration/link_choice.rs @@ -216,3 +216,26 @@ fn a_geopackage_whose_kept_counts_add_past_the_largest_total_says_the_largest() let r = s.run("layer.addData", &json!({"path": path})).unwrap(); assert_eq!((r["layers"].as_array().map(Vec::len), r["features"].as_u64()), (Some(4), Some(u64::MAX)), "{r}"); } + +#[test] +fn a_listing_stopped_while_its_last_table_opens_asks_nothing() { + // Cancel pressed after the last table's open began: that open finishes, and no question is + // made of it, as for a table before it (#2849). + struct AfterFirstLook(std::sync::atomic::AtomicU64); + impl rustgis_engine::data::progress::Probe for AfterFirstLook { + fn cancelled(&self) -> bool { + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed) > 0 + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + let f = Fixture::new("link-stop-last"); + let path = f.file("survey.gpkg"); + gpkg_file(&path, &["roads"]); + let mut s = session(); + let probe = std::sync::Arc::new(AfterFirstLook(std::sync::atomic::AtomicU64::new(0))); + let _stopped = rustgis_engine::data::progress::install(Some(probe.clone())); + let v = listed(&mut s, &path); + assert!(v.get("link").is_none(), "{v}"); + assert_eq!(probe.0.load(std::sync::atomic::Ordering::Relaxed), 2, "looked at before the open and after it"); +} From ea99e0b90b3cc25fa66020960a8c4c38df0c44c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 14:29:50 -0500 Subject: [PATCH 10/10] fix(data): a GeoPackage table's kept count is its own row's, checked after the row is chosen (#2849) --- crates/data/src/source/gpkg.rs | 9 +++++---- crates/data/src/source/tests.rs | 2 ++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 7817b93769..ee2f8c2272 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -168,11 +168,12 @@ fn has_table(conn: &Connection, name: &str) -> Result { /// (NULL, text, a negative): the table is counted instead. fn kept_count(conn: &Connection, table: &str) -> Option { conn.query_row( - "SELECT feature_count FROM gpkg_ogr_contents - WHERE lower(table_name) = lower(?1) AND typeof(feature_count) = 'integer' AND feature_count >= 0 + // The table's row (its own name first, then one differing in case), then whether its count holds. + "SELECT feature_count FROM (SELECT feature_count FROM gpkg_ogr_contents WHERE lower(table_name) = lower(?1) + ORDER BY table_name = ?1 DESC LIMIT 1) + WHERE typeof(feature_count) = 'integer' AND feature_count >= 0 AND (SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND lower(tbl_name) = lower(?1) AND lower(name) IN - (lower('trigger_insert_feature_count_' || ?1), lower('trigger_delete_feature_count_' || ?1))) = 2 - ORDER BY table_name = ?1 DESC LIMIT 1", + (lower('trigger_insert_feature_count_' || ?1), lower('trigger_delete_feature_count_' || ?1))) = 2", [table], |r| r.get(0), ) diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 232fed2d9d..fb6b2451bc 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3810,6 +3810,8 @@ fn geopackage_count_is_the_one_gdal_keeps_when_it_keeps_one() { ("upper-case name", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('PARCELS', 7);"), 7, true), // Names differing in case are two rows (the key is case-sensitive): the table's own is taken. ("a row for each case", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('PARCELS', 7), ('parcels', 250000);"), 250_000, true), + // The table's own row says no count: it is counted, whatever another row says. + ("own row null", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('PARCELS', 250000), ('parcels', NULL);"), 3, false), // The column's INTEGER affinity stores text digits as a number. ("digits as text", format!("{kept} INSERT INTO gpkg_ogr_contents VALUES ('parcels', '250000');"), 250_000, true), // Without either trigger nothing kept it up to date (GDAL drops them while it writes).