Skip to content
Merged
60 changes: 60 additions & 0 deletions crates/data/src/source/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,46 @@ pub fn layers(path: &Path) -> Result<Vec<String>> {
feature_tables(&conn)
}

/// Unsupported contents omitted when the GeoPackage is added as feature layers, by type.
pub fn unsupported_table_counts(path: &Path) -> Result<Vec<(String, u64)>> {
Comment thread
giswqs marked this conversation as resolved.
Resolved
let conn = open_db(path)?;
let invalid: i64 = conn
.query_row("SELECT count(*) FROM gpkg_contents WHERE typeof(table_name) <> 'text' OR typeof(data_type) <> 'text'", [], |row| {
Comment thread
giswqs marked this conversation as resolved.
Resolved
row.get(0)
})
.map_err(not_gpkg)?;
if invalid > 0 {
return Err(DataError::Format(format!(
"GeoPackage: {invalid} invalid gpkg_contents entry/entries: table_name and data_type must be text"
)));
}
let registered_filter = if has_geometry_columns(&conn)? {
"WHERE lower(table_name) NOT IN (SELECT lower(table_name) FROM gpkg_geometry_columns WHERE table_name IS NOT NULL)"
} else {
""
};
let query = format!(
"SELECT CASE WHEN data_type COLLATE NOCASE IN ('attributes','features','tiles','2d-gridded-coverage') THEN lower(data_type) ELSE 'other' END AS kind, count(*) FROM gpkg_contents {registered_filter} GROUP BY 1 ORDER BY 1"
);
let mut st = conn.prepare(&query).map_err(not_gpkg)?;
st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
.map_err(err)?
.map(|r| {
let (kind, count) = r.map_err(err)?;
Ok((kind, u64::try_from(count).map_err(|_| DataError::Format("GeoPackage: invalid table count".into()))?))
})
.collect()
}

/// Count a desktop upload with SQLite, matching the reader used to open its feature table.
pub fn unsupported_table_counts_bytes(bytes: &[u8]) -> Result<Vec<(String, u64)>> {
use std::io::Write;
let mut copy = tempfile::NamedTempFile::new()?;
copy.write_all(bytes)?;
copy.flush()?;
unsupported_table_counts(copy.path())
}

fn open_db(path: &Path) -> Result<Connection> {
let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX).map_err(err)?;
// A cap on SQLite's page cache, so a huge database can't take all the memory; and the file is
Expand All @@ -67,7 +107,27 @@ fn open_db(path: &Path) -> Result<Connection> {
Ok(conn)
}

/// Attribute-only and tile-only packages need not declare any geometry columns.
fn has_geometry_columns(conn: &Connection) -> Result<bool> {
has_table(conn, "gpkg_geometry_columns")
}

fn has_table(conn: &Connection, name: &str) -> Result<bool> {
conn.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name = ?1 COLLATE NOCASE AND type IN ('table','view'))",
[name],
|row| row.get(0),
)
.map_err(err)
}

fn feature_tables(conn: &Connection) -> Result<Vec<String>> {
if !has_geometry_columns(conn)? {
Comment thread
giswqs marked this conversation as resolved.
Resolved
if !has_table(conn, "gpkg_contents")? {
return Err(DataError::Format("not a GeoPackage: no gpkg_contents table".into()));
}
return Ok(Vec::new());
}
let mut st = conn.prepare("SELECT table_name FROM gpkg_geometry_columns ORDER BY table_name").map_err(not_gpkg)?;
let rows = st.query_map([], |r| r.get::<_, String>(0)).map_err(err)?;
Ok(rows.filter_map(std::result::Result::ok).collect())
Expand Down
66 changes: 62 additions & 4 deletions crates/data/src/source/gpkg_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,16 @@ fn err(e: String) -> DataError {

/// The rows of a small metadata table, as (column name → value) lookups.
fn meta_rows(db: &Db<Shared>, tables: &[Table], name: &str) -> Result<Vec<Vec<(String, Val)>>> {
let t = tables
.iter()
.find(|t| t.name.eq_ignore_ascii_case(name))
.ok_or_else(|| DataError::Format(format!("not a GeoPackage: no {name} table")))?;
let Some(t) = tables.iter().find(|t| t.name.eq_ignore_ascii_case(name)) else {
// Attribute-only and tile-only packages can omit the geometry registration table.
if name.eq_ignore_ascii_case("gpkg_geometry_columns") {
if !tables.iter().any(|table| table.name.eq_ignore_ascii_case("gpkg_contents")) {
return Err(DataError::Format("not a GeoPackage: no gpkg_contents table".into()));
}
return Ok(Vec::new());
}
return Err(DataError::Format(format!("not a GeoPackage: no {name} table")));
};
let mut out = Vec::new();
let mut too_many = false;
db.rows(t, |_, r| {
Expand Down Expand Up @@ -83,6 +89,58 @@ pub fn layers(bytes: Shared) -> Result<Vec<String>> {
Ok(names)
}

/// Unsupported contents omitted when an uploaded GeoPackage is added as feature layers, by type.
pub fn unsupported_table_counts(bytes: Shared) -> Result<Vec<(String, u64)>> {
let db = Db::open(bytes).map_err(err)?;
let schema = db.tables().map_err(err)?;
let registered: std::collections::HashSet<String> = meta_rows(&db, &schema, "gpkg_geometry_columns")?
.iter()
.filter_map(|row| text(get(row, "table_name")))
.map(|name| name.to_ascii_lowercase())
.collect();
let table = schema
.iter()
.find(|t| t.name.eq_ignore_ascii_case("gpkg_contents"))
.ok_or_else(|| DataError::Format("not a GeoPackage: no gpkg_contents table".into()))?;
let kind_col = table
.columns
.iter()
.position(|c| c.name.eq_ignore_ascii_case("data_type"))
.ok_or_else(|| DataError::Format("GeoPackage: gpkg_contents has no data_type column".into()))?;
let name_col = table
.columns
.iter()
.position(|c| c.name.eq_ignore_ascii_case("table_name"))
.ok_or_else(|| DataError::Format("GeoPackage: gpkg_contents has no table_name column".into()))?;
if [kind_col, name_col].iter().any(|&index| table.columns.get(index).is_some_and(|column| column.generated)) {
Comment thread
giswqs marked this conversation as resolved.
Resolved
Comment thread
giswqs marked this conversation as resolved.
Resolved
return Err(DataError::Format("GeoPackage: uploaded catalogs with virtual generated table_name or data_type columns are not supported; materialize these columns or select a feature table explicitly".into()));
}
let mut counts = std::collections::BTreeMap::<String, u64>::new();
let mut invalid = 0u64;
// Count in place: the contents catalog can be large without materializing its rows.
db.rows(table, |_, row| {
let (Some(Val::Text(kind)), Some(Val::Text(name))) = (row.get(kind_col), row.get(name_col)) else {
invalid = invalid.saturating_add(1);
return ControlFlow::Continue(());
};
Comment thread
giswqs marked this conversation as resolved.
Resolved
if !registered.contains(&name.to_ascii_lowercase()) {
let kind = ["attributes", "features", "tiles", "2d-gridded-coverage"]
.into_iter()
.find(|known| kind.eq_ignore_ascii_case(known))
.unwrap_or("other");
*counts.entry(kind.to_string()).or_default() += 1;
}
ControlFlow::Continue(())
})
.map_err(err)?;
if invalid > 0 {
return Err(DataError::Format(format!(
"GeoPackage: {invalid} invalid gpkg_contents entry/entries: table_name and data_type must be text"
)));
}
Ok(counts.into_iter().collect())
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

impl GpkgMemSource {
/// Opens a feature table (default: the first) of the GeoPackage in `bytes`.
pub fn open_shared(bytes: Shared, layer: Option<&str>) -> Result<Self> {
Expand Down
45 changes: 42 additions & 3 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2033,7 +2033,37 @@ fn add_source_with(
// and the AI Assistant know the file holds more than was added.
let mut skipped: Vec<String> = Vec::new();
let mut total = None;
let tables: Vec<Option<String>> = match (ps(p, "layer").map(str::trim).filter(|t| !t.is_empty()), &origin) {
let selected = ps(p, "layer").map(str::trim).filter(|t| !t.is_empty());
// Report unsupported contents for a whole-file add, not a deliberate table selection.
let contents = match (&origin, selected.is_none()) {
#[cfg(not(target_arch = "wasm32"))]
(Origin::Path(path), true) if path.to_ascii_lowercase().ends_with(".gpkg") => {
source::gpkg::unsupported_table_counts(Path::new(path)).map_err(err)?
}
#[cfg(not(target_arch = "wasm32"))]
(Origin::Bytes(name, bytes), true) if name.to_ascii_lowercase().ends_with(".gpkg") => {
source::gpkg::unsupported_table_counts_bytes(bytes.as_slice()).map_err(err)?
Comment thread
giswqs marked this conversation as resolved.
Resolved
}
#[cfg(target_arch = "wasm32")]
(Origin::Bytes(name, bytes), true) if name.to_ascii_lowercase().ends_with(".gpkg") => {
source::gpkg_mem::unsupported_table_counts(source::Shared(bytes.clone())).map_err(err)?
Comment thread
giswqs marked this conversation as resolved.
Resolved
}
_ => Vec::new(),
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let omitted: Vec<String> = contents
.into_iter()
.map(|(kind, count)| {
if kind == "attributes" {
format!("{count} attribute-only tables not added: GeoPackage attribute tables are not supported")
} else if kind == "features" {
format!("{count} feature table(s) not added: no geometry column is registered")
Comment thread
giswqs marked this conversation as resolved.
Resolved
} else {
format!("{count} {kind} table(s) not added: only GeoPackage feature tables are supported")
Comment thread
giswqs marked this conversation as resolved.
Resolved
Comment thread
giswqs marked this conversation as resolved.
Resolved
}
})
.collect();
let attribute_note = (!omitted.is_empty()).then(|| omitted.join("; "));
Comment thread
giswqs marked this conversation as resolved.
Resolved
Comment thread
giswqs marked this conversation as resolved.
Resolved
let tables: Vec<Option<String>> = match (selected, &origin) {
(Some(t), _) => vec![Some(t.to_string())],
(None, Origin::Path(path)) if path.to_ascii_lowercase().ends_with(".gpkg") => {
let mut all = source::layers(Path::new(path)).map_err(err)?;
Expand All @@ -2058,7 +2088,10 @@ fn add_source_with(
_ => vec![None],
Comment thread
giswqs marked this conversation as resolved.
Resolved
};
if tables.is_empty() {
return Err(format!("{label}: no feature tables"));
return Err(match &attribute_note {
Some(note) => format!("{label}: no feature tables; {note}"),
None => format!("{label}: no feature tables"),
});
}
let empty_before = super::map_is_empty(s);
let mut ids = Vec::new();
Expand All @@ -2074,7 +2107,10 @@ fn add_source_with(
Err(rustgis_data::DataError::Format("the table isn't open".into()))
}
}
.map_err(err)?,
.map_err(|e| match &attribute_note {
Some(note) => format!("{}; {note}", err(e)),
None => err(e),
})?,
};
let info = src.info().clone();
// A point cloud is always read in place, so a project keeps its file's path, not millions
Expand Down Expand Up @@ -2146,6 +2182,9 @@ fn add_source_with(
s.zoom_to(&e);
}
}
if let Some(note) = attribute_note {
Comment thread
giswqs marked this conversation as resolved.
Resolved
s.notify(format!("{label}: {note}"), false);
}
let first = ids.first().copied();
let mut out = json!({"layer": first, "layers": ids, "features": features, "streamed": streamed});
// Said once the tables are in: a failure above is the error instead.
Expand Down
Loading
Loading