diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index a6f86f2dbc..ee2f8c2272 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 { @@ -151,6 +155,31 @@ 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); 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. 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, 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( + // 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", + [table], + |r| r.get(0), + ) + .ok() +} + fn feature_tables(conn: &Connection) -> Result> { if !has_geometry_columns(conn)? { if !has_table(conn, "gpkg_contents")? { @@ -164,6 +193,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. @@ -280,17 +315,25 @@ 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| { - Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)) - }) - .ok(); + let kept = if mandatory { None } else { kept_count(&conn, &table) }; + // 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, @@ -312,7 +355,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(); } @@ -506,10 +560,14 @@ 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) }; - crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); + // 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.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 @@ -576,7 +634,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 665e7d1807..fb6b2451bc 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3785,6 +3785,98 @@ 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, and whether the count is kept. + let cases = [ + ("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 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). + ( + "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", + 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, + false, + ), + ("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, 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(); + 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. + // Its progress, and a whole read's (Load All), has the rows counted as its total, or none + // (unknown) for a kept count. + 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())); + (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"); + } +} + /// 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..dd71f7ed19 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"}"#, ), @@ -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()); @@ -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 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(); @@ -2546,11 +2547,17 @@ 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; + } } + // 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; @@ -2953,7 +2960,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() { @@ -3119,8 +3126,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)?; @@ -3491,7 +3498,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)", @@ -3503,7 +3511,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; @@ -4352,7 +4360,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())); } @@ -4546,7 +4554,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 14657f4630..15800d2147 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. @@ -136,3 +200,42 @@ 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), 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", "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(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"); +} 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.