use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use arrow::array::{
ArrayRef, BinaryArray, BooleanArray, Float64Array, RecordBatch, StringArray, UInt32Array,
};
use arrow::datatypes::{DataType, Field, Schema};
use geo::BoundingRect as _;
use geozero::{CoordDimensions, ToWkb as _};
use parquet::arrow::ArrowWriter;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::basic::{Compression, ZstdLevel};
use parquet::file::metadata::KeyValue;
use parquet::file::properties::WriterProperties;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::areas::BOUNDARIES_ATTRIBUTION;
use crate::cli::{DownloadsAction, DownloadsArgs};
use crate::country::CountryConfig;
use crate::normals::parse_csv;
pub const GEOPARQUET_VERSION: &str = "1.1.0";
pub const BOUNDARIES_LICENSE: &str = "ODbL-1.0";
pub const LICENSE_TEXT: &str = "\
Boundary files: areas.parquet and areas.pmtiles
These boundary files are made available under the Open Database License
(ODbL) 1.0: https://opendatacommons.org/licenses/odbl/1-0/
© OpenStreetMap contributors.
Boundaries from Overture Maps Foundation (divisions, derived from
OpenStreetMap).
India boundaries by DataMeet India community (CC BY 4.0).
The values files of a build (numbers.csv, numbers.parquet, index.json and
areas/<area-id>.json) are separate works, not part of this database; each
carries its own attribution and licence.
";
const FLOAT_COLUMNS: [&str; 5] = [
"value",
"normal",
"anomaly_pct",
"anomaly_abs",
"coverage_pct",
];
const INDEX_KEYS: [&str; 3] = ["attribution", "licence", "dataset"];
const AREA_COLUMNS: [&str; 6] = ["id", "name", "country", "level", "parent_id", "region_code"];
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CheckReport {
pub rows: i64,
pub columns: Vec<CheckColumn>,
pub metadata_keys: Vec<String>,
pub attribution: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CheckColumn {
pub name: String,
#[serde(rename = "type")]
pub data_type: String,
}
#[derive(Debug, Serialize)]
struct GeoMetadata {
version: &'static str,
primary_column: &'static str,
columns: GeoColumns,
}
#[derive(Debug, Serialize)]
struct GeoColumns {
geometry: GeoColumn,
}
#[derive(Debug, Serialize)]
struct GeoColumn {
encoding: &'static str,
geometry_types: [&'static str; 1],
bbox: [f64; 4],
}
pub fn run(args: &DownloadsArgs) -> Result<()> {
match &args.action {
DownloadsAction::Numbers(a) => {
write_numbers_parquet(&a.csv, &a.index, &a.source_url, &a.out)
}
DownloadsAction::Areas(a) => {
let config = a
.country_config
.as_deref()
.map(CountryConfig::load)
.transpose()?;
write_areas_downloads(&a.areas, &a.release, &a.out, config.as_ref())
}
DownloadsAction::Check(a) => {
let report = check_parquet(&a.file)?;
println!("{}", serde_json::to_string(&report)?);
Ok(())
}
}
}
fn numbers_type(name: &str) -> DataType {
match name {
_ if FLOAT_COLUMNS.contains(&name) => DataType::Float64,
"cells" => DataType::UInt32,
"sparse" => DataType::Boolean,
_ => DataType::Utf8,
}
}
pub fn write_numbers_parquet(csv: &Path, index: &Path, source_url: &str, out: &Path) -> Result<()> {
if source_url.trim().is_empty() {
bail!("{}: numbers.parquet needs --source-url", out.display());
}
let text =
std::fs::read_to_string(csv).with_context(|| format!("reading {}", csv.display()))?;
let mut records = parse_csv(&text)
.with_context(|| format!("parsing {}", csv.display()))?
.into_iter();
let header = records
.next()
.with_context(|| format!("{} is empty", csv.display()))?;
let rows: Vec<Vec<String>> = records.collect();
for (index, row) in rows.iter().enumerate() {
if row.len() != header.len() {
bail!(
"{} row {}: {} fields, expected {}",
csv.display(),
index + 2,
row.len(),
header.len()
);
}
}
let mut fields = Vec::with_capacity(header.len());
let mut columns: Vec<ArrayRef> = Vec::with_capacity(header.len());
for (column, name) in header.iter().enumerate() {
let data_type = numbers_type(name);
let cells = rows.iter().map(|row| row[column].as_str());
let field_error = |row: usize, value: &str| {
format!("{} row {} column {name}: {value:?}", csv.display(), row + 2)
};
let (array, nullable): (ArrayRef, bool) = match data_type {
DataType::Float64 => {
let mut values = Vec::with_capacity(rows.len());
for (row, cell) in cells.enumerate() {
values.push(if cell.is_empty() {
None
} else {
Some(
cell.parse::<f64>()
.with_context(|| field_error(row, cell))?,
)
});
}
(Arc::new(Float64Array::from(values)), true)
}
DataType::UInt32 => {
let mut values = Vec::with_capacity(rows.len());
for (row, cell) in cells.enumerate() {
values.push(
cell.parse::<u32>()
.with_context(|| field_error(row, cell))?,
);
}
(Arc::new(UInt32Array::from(values)), false)
}
DataType::Boolean => {
let mut values = Vec::with_capacity(rows.len());
for (row, cell) in cells.enumerate() {
values.push(match cell {
"true" => true,
"false" => false,
_ => bail!("{}: not true or false", field_error(row, cell)),
});
}
(Arc::new(BooleanArray::from(values)), false)
}
_ => {
let values: Vec<Option<&str>> = cells
.map(|cell| (!cell.is_empty()).then_some(cell))
.collect();
(Arc::new(StringArray::from(values)), true)
}
};
fields.push(Field::new(name, data_type, nullable));
columns.push(array);
}
let mut metadata = index_metadata(index)?;
metadata.push(KeyValue::new(
"source_url".to_owned(),
source_url.to_owned(),
));
let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)
.with_context(|| format!("columns of {}", csv.display()))?;
write_parquet(out, &batch, metadata)
}
fn index_metadata(path: &Path) -> Result<Vec<KeyValue>> {
let file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
let index: serde_json::Map<String, Value> =
serde_json::from_reader(std::io::BufReader::new(file))
.with_context(|| format!("parsing {}", path.display()))?;
let mut metadata = Vec::with_capacity(INDEX_KEYS.len() + 1);
for key in INDEX_KEYS {
if let Some(Value::String(value)) = index.get(key) {
metadata.push(KeyValue::new(key.to_owned(), value.clone()));
}
}
if !metadata.iter().any(|kv| kv.key == "attribution") {
bail!("{} has no attribution", path.display());
}
if let Some(comparison) = index.get("comparison").filter(|c| !c.is_null()) {
metadata.push(KeyValue::new(
"comparison".to_owned(),
comparison.to_string(),
));
}
Ok(metadata)
}
fn partial_of(path: &Path) -> PathBuf {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
path.with_file_name(format!(".{name}.partial"))
}
fn write_parquet(out: &Path, batch: &RecordBatch, metadata: Vec<KeyValue>) -> Result<()> {
let props = WriterProperties::builder()
.set_compression(Compression::ZSTD(ZstdLevel::default()))
.set_max_row_group_row_count(Some(batch.num_rows().max(1)))
.set_max_row_group_bytes(None)
.set_key_value_metadata(Some(metadata))
.build();
let partial = partial_of(out);
let file = File::create(&partial).with_context(|| format!("creating {}", partial.display()))?;
let mut writer = ArrowWriter::try_new(file, batch.schema(), Some(props))
.with_context(|| format!("writing {}", partial.display()))?;
writer
.write(batch)
.with_context(|| format!("writing {}", partial.display()))?;
writer
.close()
.with_context(|| format!("writing {}", partial.display()))?;
std::fs::rename(&partial, out).with_context(|| format!("renaming to {}", out.display()))
}
pub fn write_areas_downloads(
areas: &Path,
release: &str,
out: &Path,
country: Option<&CountryConfig>,
) -> Result<()> {
let bytes = std::fs::read(areas).with_context(|| format!("opening {}", areas.display()))?;
let collection = super::exact_json::parse_feature_collection(&bytes)
.with_context(|| format!("parsing {}", areas.display()))?;
if let Some(theirs) = collection
.foreign_members
.as_ref()
.and_then(|m| m.get("boundary_release"))
.and_then(Value::as_str)
.filter(|theirs| *theirs != release)
{
bail!(
"{} holds boundary release {theirs}, not {release}",
areas.display()
);
}
if collection.features.is_empty() {
bail!("{} holds no area", areas.display());
}
let count = collection.features.len();
let mut props: Vec<Vec<Option<String>>> = (0..AREA_COLUMNS.len())
.map(|_| Vec::with_capacity(count))
.collect();
let mut wkb: Vec<Vec<u8>> = Vec::with_capacity(count);
let mut bbox = [
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
];
for (n, feature) in collection.features.iter().enumerate() {
for (column, key) in AREA_COLUMNS.iter().enumerate() {
let value = feature
.properties
.as_ref()
.and_then(|p| p.get(*key))
.and_then(Value::as_str)
.map(str::to_owned);
props[column].push(value);
}
let geometry = feature
.geometry
.clone()
.with_context(|| format!("feature {} of {} has no geometry", n + 1, areas.display()))?;
let shape = match geo::Geometry::<f64>::try_from(geometry)
.with_context(|| format!("bad geometry of feature {} in {}", n + 1, areas.display()))?
{
geo::Geometry::Polygon(p) => geo::MultiPolygon(vec![p]),
geo::Geometry::MultiPolygon(m) => m,
_ => bail!("feature {} of {} is not a polygon", n + 1, areas.display()),
};
if let Some(rect) = shape.bounding_rect() {
bbox = [
bbox[0].min(rect.min().x),
bbox[1].min(rect.min().y),
bbox[2].max(rect.max().x),
bbox[3].max(rect.max().y),
];
}
wkb.push(
geo::Geometry::MultiPolygon(shape)
.to_wkb(CoordDimensions::xy())
.with_context(|| format!("WKB of feature {} in {}", n + 1, areas.display()))?,
);
}
if !bbox.iter().all(|v| v.is_finite()) {
bail!("{} holds no coordinate", areas.display());
}
let mut fields: Vec<Field> = AREA_COLUMNS
.iter()
.map(|name| Field::new(*name, DataType::Utf8, true))
.collect();
fields.push(Field::new("geometry", DataType::Binary, false));
let mut columns: Vec<ArrayRef> = props
.into_iter()
.map(|values| Arc::new(StringArray::from(values)) as ArrayRef)
.collect();
columns.push(Arc::new(BinaryArray::from_iter_values(wkb)));
let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)
.with_context(|| format!("columns of {}", areas.display()))?;
let geo = GeoMetadata {
version: GEOPARQUET_VERSION,
primary_column: "geometry",
columns: GeoColumns {
geometry: GeoColumn {
encoding: "WKB",
geometry_types: ["MultiPolygon"],
bbox,
},
},
};
let attribution = country.map_or(BOUNDARIES_ATTRIBUTION, |c| {
c.boundaries.attribution.as_str()
});
let licence_id = country.map_or(BOUNDARIES_LICENSE, |c| c.boundaries.licence_id.as_str());
let licence_text = match country.and_then(|c| c.boundaries.licence_file.as_deref()) {
Some(path) => std::fs::read(path).with_context(|| format!("reading {path}"))?,
None => LICENSE_TEXT.as_bytes().to_vec(),
};
let metadata = vec![
KeyValue::new("geo".to_owned(), serde_json::to_string(&geo)?),
KeyValue::new("attribution".to_owned(), attribution.to_owned()),
KeyValue::new("license".to_owned(), licence_id.to_owned()),
KeyValue::new("boundary_release".to_owned(), release.to_owned()),
];
std::fs::create_dir_all(out).with_context(|| format!("creating {}", out.display()))?;
write_parquet(&out.join("areas.parquet"), &batch, metadata)?;
let license = out.join("LICENSE.txt");
let partial = partial_of(&license);
std::fs::write(&partial, &licence_text)
.with_context(|| format!("writing {}", partial.display()))?;
std::fs::rename(&partial, &license)
.with_context(|| format!("renaming to {}", license.display()))
}
pub fn check_parquet(path: &Path) -> Result<CheckReport> {
let file = File::open(path).with_context(|| format!("opening {}", path.display()))?;
let builder = ParquetRecordBatchReaderBuilder::try_new(file)
.with_context(|| format!("reading {}", path.display()))?;
let meta = builder.metadata().file_metadata();
let kv = meta.key_value_metadata().cloned().unwrap_or_default();
let mut metadata_keys: Vec<String> = kv.iter().map(|kv| kv.key.clone()).collect();
metadata_keys.sort();
Ok(CheckReport {
rows: meta.num_rows(),
columns: builder
.schema()
.fields()
.iter()
.map(|field| CheckColumn {
name: field.name().clone(),
data_type: field.data_type().to_string(),
})
.collect(),
metadata_keys,
attribution: kv
.into_iter()
.find(|kv| kv.key == "attribution")
.and_then(|kv| kv.value),
})
}
#[cfg(test)]
mod tests {
use super::*;
use arrow::array::{Array, AsArray};
use arrow::datatypes::{Float64Type, UInt32Type};
use geozero::ToGeo as _;
use geozero::wkb::Wkb;
const NDVI: &str = "Contains modified Copernicus Land Monitoring Service information 2026";
const SOURCE: &str = "https://land.copernicus.eu/en/products/vegetation/ndvi";
fn numbers_fixture(dir: &Path) -> (PathBuf, PathBuf) {
let csv = dir.join("numbers.csv");
std::fs::write(
&csv,
format!(
"area_id,name,state,country,period_start,period_end,status,value,normal,\
anomaly_pct,anomaly_abs,coverage_pct,cells,sparse,attribution\n\
a1,\"Name, with a comma\",State A,IN,2026-11-01,2026-11-10,final,0.42,0.5,,\
-0.08,100,135,false,\"{NDVI}\"\n\
a2,Two,,IN,2026-11-01,2026-11-10,prelim,,,,,0,0,true,\"{NDVI}\"\n"
),
)
.unwrap();
let index = dir.join("index.json");
std::fs::write(
&index,
format!(
r#"{{"dataset":"ndvi","attribution":"{NDVI}","licence":"Copernicus free licence",
"comparison":{{"kind":"average","baseline":"2014-2025","label":"vs 2014–2025 average"}},
"areas":[]}}"#
),
)
.unwrap();
(csv, index)
}
fn read_batch(path: &Path) -> (RecordBatch, Vec<KeyValue>, usize, Compression) {
let builder = ParquetRecordBatchReaderBuilder::try_new(File::open(path).unwrap()).unwrap();
let meta = builder.metadata().clone();
let kv = meta
.file_metadata()
.key_value_metadata()
.cloned()
.unwrap_or_default();
let batches: Vec<RecordBatch> = builder.build().unwrap().map(Result::unwrap).collect();
let batch = arrow::compute::concat_batches(&batches[0].schema(), &batches).unwrap();
let compression = meta.row_group(0).column(0).compression();
(batch, kv, meta.num_row_groups(), compression)
}
fn kv_value<'a>(kv: &'a [KeyValue], key: &str) -> Option<&'a str> {
kv.iter()
.find(|kv| kv.key == key)
.and_then(|kv| kv.value.as_deref())
}
fn row_of(batch: &RecordBatch, column: &str, value: &str) -> usize {
let ids = batch.column_by_name(column).unwrap().as_string::<i32>();
(0..ids.len())
.find(|&i| ids.is_valid(i) && ids.value(i) == value)
.unwrap_or_else(|| panic!("no row with {column} = {value}"))
}
#[test]
fn numbers_parquet_round_trips_the_csv() {
let dir = tempfile::tempdir().unwrap();
let (csv, index) = numbers_fixture(dir.path());
let out = dir.path().join("numbers.parquet");
write_numbers_parquet(&csv, &index, SOURCE, &out).unwrap();
let (batch, kv, row_groups, compression) = read_batch(&out);
assert_eq!(batch.num_rows(), 2);
assert_eq!(row_groups, 1);
assert!(
matches!(compression, Compression::ZSTD(_)),
"{compression:?}"
);
let schema = batch.schema();
let type_of = |name: &str| schema.field_with_name(name).unwrap().data_type().clone();
assert_eq!(type_of("value"), DataType::Float64);
assert_eq!(type_of("anomaly_abs"), DataType::Float64);
assert_eq!(type_of("cells"), DataType::UInt32);
assert_eq!(type_of("sparse"), DataType::Boolean);
assert_eq!(type_of("period_end"), DataType::Utf8);
assert_eq!(type_of("attribution"), DataType::Utf8);
let float = |name: &str| {
batch
.column_by_name(name)
.unwrap()
.as_primitive::<Float64Type>()
};
let text = |name: &str| batch.column_by_name(name).unwrap().as_string::<i32>();
let a1 = row_of(&batch, "area_id", "a1");
assert_eq!(text("name").value(a1), "Name, with a comma");
assert_eq!(text("state").value(a1), "State A");
assert_eq!(text("status").value(a1), "final");
assert_eq!(float("value").value(a1), 0.42);
assert_eq!(float("normal").value(a1), 0.5);
assert!(float("anomaly_pct").is_null(a1));
assert_eq!(float("anomaly_abs").value(a1), -0.08);
assert_eq!(float("coverage_pct").value(a1), 100.0);
let cells = batch
.column_by_name("cells")
.unwrap()
.as_primitive::<UInt32Type>();
assert_eq!(cells.value(a1), 135);
let sparse = batch.column_by_name("sparse").unwrap().as_boolean();
assert!(!sparse.value(a1));
assert_eq!(text("attribution").value(a1), NDVI);
let a2 = row_of(&batch, "area_id", "a2");
assert_eq!(text("status").value(a2), "prelim");
assert!(text("state").is_null(a2));
for name in ["value", "normal", "anomaly_pct", "anomaly_abs"] {
assert!(float(name).is_null(a2), "{name}");
}
assert_eq!(float("coverage_pct").value(a2), 0.0);
assert_eq!(cells.value(a2), 0);
assert!(sparse.value(a2));
assert_eq!(kv_value(&kv, "attribution"), Some(NDVI));
assert_eq!(kv_value(&kv, "licence"), Some("Copernicus free licence"));
assert_eq!(kv_value(&kv, "dataset"), Some("ndvi"));
assert_eq!(kv_value(&kv, "source_url"), Some(SOURCE));
let comparison: Value = serde_json::from_str(kv_value(&kv, "comparison").unwrap()).unwrap();
assert_eq!(comparison["label"], "vs 2014–2025 average");
assert_eq!(comparison["baseline"], "2014-2025");
}
#[test]
fn numbers_without_an_index_attribution_are_refused() {
let dir = tempfile::tempdir().unwrap();
let (csv, index) = numbers_fixture(dir.path());
std::fs::write(&index, r#"{"dataset":"ndvi"}"#).unwrap();
let err =
write_numbers_parquet(&csv, &index, SOURCE, &dir.path().join("n.parquet")).unwrap_err();
assert!(format!("{err:#}").contains("has no attribution"), "{err:#}");
}
#[test]
fn numbers_without_a_source_url_are_refused() {
let dir = tempfile::tempdir().unwrap();
let (csv, index) = numbers_fixture(dir.path());
let out = dir.path().join("n.parquet");
let err = write_numbers_parquet(&csv, &index, " ", &out).unwrap_err();
assert!(
format!("{err:#}").contains("numbers.parquet needs --source-url"),
"{err:#}"
);
assert!(!out.exists());
}
fn areas_fixture(dir: &Path) -> PathBuf {
let path = dir.join("areas.geojson");
std::fs::write(
&path,
r#"{"type":"FeatureCollection","boundary_release":"2026-10-21.0","attribution":"x",
"features":[
{"type":"Feature","properties":{"id":"b","name":"Bee","country":"IN","level":"county",
"parent_id":"r1","parent_name":"Region","region_code":"IN-XX"},
"geometry":{"type":"Polygon","coordinates":[
[[0,0],[2,0],[2,1],[0,1],[0,0]],
[[0.5,0.25],[0.5,0.75],[1,0.75],[1,0.25],[0.5,0.25]]]}},
{"type":"Feature","properties":{"id":"a","name":"Ay","country":"IN","level":"county",
"parent_id":null,"parent_name":null,"region_code":null},
"geometry":{"type":"MultiPolygon","coordinates":[
[[[10,5],[11,5],[11,6],[10,6],[10,5]]],
[[[-3,-4],[-2,-4],[-2,-3],[-3,-3],[-3,-4]]]]}}]}"#,
)
.unwrap();
path
}
#[test]
fn a_country_licence_file_replaces_the_odbl_text() {
let dir = tempfile::tempdir().unwrap();
let areas = areas_fixture(dir.path());
let licence_text = "Fixture CC0 notice\n";
let licence_path = dir.path().join("fixture-licence.txt");
std::fs::write(&licence_path, licence_text).unwrap();
let json = format!(
r#"{{
"code": "us", "name": "Fixture",
"unit": {{"one": "county", "many": "counties"}},
"parent": {{"one": "state", "many": "states"}},
"bounds": [-170.0, 18.0, -66.0, 72.0],
"boundaries": {{
"source": "overture", "release": "2026-10-21.0", "level": "county",
"attribution": "Boundaries: fixture", "licence_id": "CC0-1.0",
"licence_file": "{}"
}}
}}"#,
licence_path.display()
);
let config = crate::country::CountryConfig::from_json_str(&json).unwrap();
write_areas_downloads(&areas, "2026-10-21.0", dir.path(), Some(&config)).unwrap();
let licence = std::fs::read(dir.path().join("LICENSE.txt")).unwrap();
assert_eq!(licence, licence_text.as_bytes());
let (_, kv, _, _) = read_batch(&dir.path().join("areas.parquet"));
assert_eq!(kv_value(&kv, "license"), Some("CC0-1.0"));
assert_eq!(kv_value(&kv, "attribution"), Some("Boundaries: fixture"));
}
#[test]
fn areas_geoparquet_has_spec_metadata() {
let dir = tempfile::tempdir().unwrap();
let areas = areas_fixture(dir.path());
write_areas_downloads(&areas, "2026-10-21.0", dir.path(), None).unwrap();
let (batch, kv, row_groups, _) = read_batch(&dir.path().join("areas.parquet"));
assert_eq!(batch.num_rows(), 2);
assert_eq!(row_groups, 1);
let geo: Value = serde_json::from_str(kv_value(&kv, "geo").unwrap()).unwrap();
assert_eq!(geo["version"], "1.1.0");
assert_eq!(geo["primary_column"], "geometry");
let column = &geo["columns"]["geometry"];
assert_eq!(column["encoding"], "WKB");
assert_eq!(
column["geometry_types"],
serde_json::json!(["MultiPolygon"])
);
assert_eq!(column["bbox"], serde_json::json!([-3.0, -4.0, 11.0, 6.0]));
assert!(column.get("crs").is_none(), "{column}");
assert!(geo.get("crs").is_none(), "{geo}");
assert_eq!(kv_value(&kv, "attribution"), Some(BOUNDARIES_ATTRIBUTION));
assert_eq!(kv_value(&kv, "license"), Some("ODbL-1.0"));
assert_eq!(kv_value(&kv, "boundary_release"), Some("2026-10-21.0"));
let schema = batch.schema();
for name in ["id", "name", "country", "level", "parent_id", "region_code"] {
let field = schema.field_with_name(name).unwrap();
assert_eq!(field.data_type(), &DataType::Utf8, "{name}");
assert!(field.is_nullable(), "{name}");
}
assert_eq!(
schema.field_with_name("geometry").unwrap().data_type(),
&DataType::Binary
);
let text = |name: &str| batch.column_by_name(name).unwrap().as_string::<i32>();
let a = row_of(&batch, "id", "a");
assert!(text("parent_id").is_null(a));
assert!(text("region_code").is_null(a));
let b = row_of(&batch, "id", "b");
assert_eq!(text("region_code").value(b), "IN-XX");
assert_eq!(text("name").value(b), "Bee");
let ids: Vec<&str> = (0..2).map(|i| text("id").value(i)).collect();
assert_eq!(ids, ["b", "a"]);
}
#[test]
fn areas_geometries_are_the_correctly_rounded_geojson_text() {
let text = "21.546982095478498";
let exact: f64 = text.parse().unwrap();
let dir = tempfile::tempdir().unwrap();
let areas = dir.path().join("areas.geojson");
std::fs::write(
&areas,
format!(
r#"{{"type":"FeatureCollection","boundary_release":"2026-10-21.0","attribution":"x",
"features":[{{"type":"Feature","properties":{{"id":"d"}},"geometry":{{"type":"Polygon",
"coordinates":[[[{text},1],[22,1],[22,2],[{text},2],[{text},1]]]}}}}]}}"#
),
)
.unwrap();
write_areas_downloads(&areas, "2026-10-21.0", dir.path(), None).unwrap();
let (batch, _, _, _) = read_batch(&dir.path().join("areas.parquet"));
let wkb = batch.column_by_name("geometry").unwrap().as_binary::<i32>();
let geo::Geometry::MultiPolygon(shape) = Wkb(wkb.value(0).to_vec()).to_geo().unwrap()
else {
panic!("not a multipolygon");
};
let ring = &shape.0[0].exterior().0;
assert_eq!(ring[0].x.to_bits(), exact.to_bits());
assert_eq!(ring[3].x.to_bits(), exact.to_bits());
}
#[test]
fn areas_geometries_round_trip() {
let dir = tempfile::tempdir().unwrap();
let areas = areas_fixture(dir.path());
write_areas_downloads(&areas, "2026-10-21.0", dir.path(), None).unwrap();
let (batch, _, _, _) = read_batch(&dir.path().join("areas.parquet"));
let wkb = batch.column_by_name("geometry").unwrap().as_binary::<i32>();
let decode = |row: usize| Wkb(wkb.value(row).to_vec()).to_geo().unwrap();
let b = geo::MultiPolygon(vec![geo::Polygon::new(
geo::LineString::from(vec![
(0.0, 0.0),
(2.0, 0.0),
(2.0, 1.0),
(0.0, 1.0),
(0.0, 0.0),
]),
vec![geo::LineString::from(vec![
(0.5, 0.25),
(0.5, 0.75),
(1.0, 0.75),
(1.0, 0.25),
(0.5, 0.25),
])],
)]);
let a = geo::MultiPolygon(vec![
geo::Polygon::new(
geo::LineString::from(vec![
(10.0, 5.0),
(11.0, 5.0),
(11.0, 6.0),
(10.0, 6.0),
(10.0, 5.0),
]),
vec![],
),
geo::Polygon::new(
geo::LineString::from(vec![
(-3.0, -4.0),
(-2.0, -4.0),
(-2.0, -3.0),
(-3.0, -3.0),
(-3.0, -4.0),
]),
vec![],
),
]);
assert_eq!(
decode(row_of(&batch, "id", "b")),
geo::Geometry::MultiPolygon(b)
);
assert_eq!(
decode(row_of(&batch, "id", "a")),
geo::Geometry::MultiPolygon(a)
);
}
#[test]
fn the_licence_file_names_odbl_and_osm() {
let dir = tempfile::tempdir().unwrap();
let areas = areas_fixture(dir.path());
write_areas_downloads(&areas, "2026-10-21.0", dir.path(), None).unwrap();
let text = std::fs::read_to_string(dir.path().join("LICENSE.txt")).unwrap();
for needle in [
"Open Database License",
"ODbL",
"https://opendatacommons.org/licenses/odbl/1-0/",
"© OpenStreetMap contributors",
"Overture Maps Foundation",
"India boundaries by DataMeet India community (CC BY 4.0)",
"are separate works",
] {
assert!(text.contains(needle), "{needle} missing from:\n{text}");
}
assert!(!dir.path().join(".LICENSE.txt.partial").exists());
assert!(!dir.path().join(".areas.parquet.partial").exists());
}
#[test]
fn areas_of_another_release_are_refused() {
let dir = tempfile::tempdir().unwrap();
let areas = areas_fixture(dir.path());
let out = dir.path().join("out");
let err = write_areas_downloads(&areas, "2026-12-16.0", &out, None).unwrap_err();
assert!(
format!("{err:#}").contains("holds boundary release 2026-10-21.0, not 2026-12-16.0"),
"{err:#}"
);
assert!(!out.join("areas.parquet").exists());
}
#[test]
fn check_reads_rows_columns_and_attribution() {
let dir = tempfile::tempdir().unwrap();
let (csv, index) = numbers_fixture(dir.path());
let out = dir.path().join("numbers.parquet");
write_numbers_parquet(&csv, &index, SOURCE, &out).unwrap();
let report = check_parquet(&out).unwrap();
assert_eq!(report.rows, 2);
assert_eq!(report.attribution.as_deref(), Some(NDVI));
let value = report.columns.iter().find(|c| c.name == "value").unwrap();
assert_eq!(value.data_type, "Float64");
let cells = report.columns.iter().find(|c| c.name == "cells").unwrap();
assert_eq!(cells.data_type, "UInt32");
for key in [
"attribution",
"comparison",
"dataset",
"licence",
"source_url",
] {
assert!(report.metadata_keys.iter().any(|k| k == key), "{key}");
}
let json: Value = serde_json::from_str(&serde_json::to_string(&report).unwrap()).unwrap();
let columns = json["columns"].as_array().unwrap();
assert!(
columns.contains(&serde_json::json!({"name": "area_id", "type": "Utf8"})),
"{json}"
);
}
}