use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use arrow_json::ReaderBuilder;
use arrow_schema::{DataType, Field, Fields, Schema};
use commonmeta::RorRelease;
use parquet::arrow::ArrowWriter;
use parquet::basic::{Compression, ZstdLevel};
use parquet::file::metadata::KeyValue;
use parquet::file::properties::WriterProperties;
use serde_json::value::RawValue;
use crate::Error;
use crate::lake::{CSV, Runner, last_count, pairs};
use crate::setup;
use crate::tempdir::TempDir;
pub const VIEW_SCHEMA: &str = "ror";
const RELEASE_PREFIX: &str = "ror_";
const SOURCES: &str = "sources/ror";
const ORGANIZATIONS: &str = "organizations";
const RELEASE: &str = "release";
const BATCH: usize = 16_384;
const CACHE_TTL: u64 = 30 * 24 * 60 * 60;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version(Vec<u32>);
impl Version {
pub fn parse(value: &str) -> Result<Self, Error> {
let invalid = || Error::InvalidSetting {
name: "ROR version",
reason: format!("{value:?} is not like v2.16"),
};
let digits = value.strip_prefix('v').unwrap_or(value);
let parts = digits
.split('.')
.map(|part| {
if part.is_empty() || part.len() > 6 || !part.bytes().all(|b| b.is_ascii_digit()) {
None
} else {
part.parse().ok()
}
})
.collect::<Option<Vec<u32>>>()
.ok_or_else(invalid)?;
Ok(Version(parts))
}
fn from_schema(schema: &str) -> Option<Self> {
let rest = schema.strip_prefix(RELEASE_PREFIX)?.strip_prefix('v')?;
Version::parse(&rest.replace('_', ".")).ok()
}
pub fn schema(&self) -> String {
format!("{RELEASE_PREFIX}v{}", self.joined("_"))
}
fn joined(&self, separator: &str) -> String {
self.0
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(separator)
}
}
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "v{}", self.joined("."))
}
}
#[derive(Debug, Clone)]
pub struct Release {
pub version: Version,
pub date: String,
pub doi: String,
pub filename: String,
pub download_url: String,
}
impl Release {
fn from_zenodo(release: RorRelease) -> Result<Self, Error> {
let invalid = |reason: String| Error::InvalidSetting {
name: "ROR release",
reason,
};
let version = Version::parse(&release.version)?;
if !is_date(&release.date) {
return Err(invalid(format!("bad date {:?}", release.date)));
}
if release.zenodo_id.is_empty() || !release.zenodo_id.bytes().all(|b| b.is_ascii_digit()) {
return Err(invalid(format!("bad Zenodo id {:?}", release.zenodo_id)));
}
let safe = |c: char| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_');
if !release.filename.ends_with(".zip") || !release.filename.chars().all(safe) {
return Err(invalid(format!("unexpected file {:?}", release.filename)));
}
Ok(Release {
version,
date: release.date,
doi: format!("10.5281/zenodo.{}", release.zenodo_id),
filename: release.filename,
download_url: release.download_url,
})
}
pub fn parquet_name(&self) -> String {
format!("{}.parquet", self.filename.trim_end_matches(".zip"))
}
}
fn is_date(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() == 10
&& bytes.iter().enumerate().all(|(i, b)| match i {
4 | 7 => *b == b'-',
_ => b.is_ascii_digit(),
})
}
fn latest_release() -> Result<Release, Error> {
let release = commonmeta::fetch_latest_ror_release()
.map_err(|error| Error::Import(format!("looking up the ROR release on Zenodo: {error}")))?;
Release::from_zenodo(release)
}
fn download(release: &Release) -> Result<PathBuf, Error> {
let (path, cached) = commonmeta::io_utils::ensure_cached_path(
&release.download_url,
"ror",
&release.filename,
std::time::Duration::from_secs(CACHE_TTL),
)
.map_err(|error| Error::Import(format!("downloading {}: {error}", release.filename)))?;
tracing::info!(path = %path.display(), cached, "ROR data dump");
Ok(path)
}
fn records_json(zip: &Path) -> Result<Vec<u8>, Error> {
commonmeta::io_utils::unzip_first_json(&std::fs::read(zip)?)
.map_err(|error| Error::Import(format!("reading the JSON in {}: {error}", zip.display())))
}
pub fn schema() -> Schema {
let text = || Field::new("item", DataType::Utf8, true);
let texts = |name: &str| Field::new(name, DataType::List(Arc::new(text())), true);
let utf8 = |name: &str| Field::new(name, DataType::Utf8, true);
let list_of = |name: &str, fields: Vec<Field>| {
Field::new(
name,
DataType::List(Arc::new(Field::new(
"item",
DataType::Struct(Fields::from(fields)),
true,
))),
true,
)
};
let admin_entry = |name: &str| {
Field::new(
name,
DataType::Struct(Fields::from(vec![
Field::new("date", DataType::Date32, true),
utf8("schema_version"),
])),
true,
)
};
Schema::new(vec![
Field::new("id", DataType::Utf8, false),
list_of("names", vec![utf8("value"), texts("types"), utf8("lang")]),
texts("types"),
utf8("status"),
Field::new("established", DataType::Int32, true),
list_of(
"locations",
vec![
Field::new("geonames_id", DataType::Int64, true),
Field::new(
"geonames_details",
DataType::Struct(Fields::from(vec![
utf8("continent_code"),
utf8("continent_name"),
utf8("country_code"),
utf8("country_name"),
utf8("country_subdivision_code"),
utf8("country_subdivision_name"),
Field::new("lat", DataType::Float64, true),
Field::new("lng", DataType::Float64, true),
utf8("name"),
])),
true,
),
],
),
list_of(
"external_ids",
vec![utf8("type"), texts("all"), utf8("preferred")],
),
list_of("links", vec![utf8("type"), utf8("value")]),
list_of(
"relationships",
vec![utf8("type"), utf8("label"), utf8("id")],
),
texts("domains"),
Field::new(
"admin",
DataType::Struct(Fields::from(vec![
admin_entry("created"),
admin_entry("last_modified"),
])),
true,
),
])
}
pub fn to_parquet(json: &[u8], out: &Path, version: &Version) -> Result<u64, Error> {
let convert = |error: &dyn std::fmt::Display| Error::Import(format!("ROR JSON: {error}"));
let records: Vec<&RawValue> = serde_json::from_slice(json).map_err(|e| convert(&e))?;
let schema = Arc::new(schema());
let mut decoder = ReaderBuilder::new(schema.clone())
.with_batch_size(BATCH)
.with_strict_mode(true)
.build_decoder()
.map_err(|e| convert(&e))?;
let properties = WriterProperties::builder()
.set_compression(Compression::ZSTD(
ZstdLevel::try_new(9).map_err(|e| convert(&e))?,
))
.set_max_row_group_row_count(Some(BATCH))
.set_key_value_metadata(Some(vec![
KeyValue::new("ror_version".into(), version.to_string()),
KeyValue::new(
"created_by_hazine".into(),
env!("CARGO_PKG_VERSION").to_string(),
),
]))
.build();
let file = std::fs::File::create(out)?;
let mut writer =
ArrowWriter::try_new(file, schema, Some(properties)).map_err(|e| convert(&e))?;
let mut rows = 0u64;
for chunk in records.chunks(BATCH) {
for (i, record) in chunk.iter().enumerate() {
let bytes = record.get().as_bytes();
let read = decoder
.decode(bytes)
.map_err(|e| convert(&format!("record {}: {e}", rows as usize + i + 1)))?;
if read != bytes.len() {
return Err(convert(&"a record was not read whole"));
}
}
if let Some(batch) = decoder.flush().map_err(|e| convert(&e))? {
rows += batch.num_rows() as u64;
writer.write(&batch).map_err(|e| convert(&e))?;
}
}
writer.close().map_err(|e| convert(&e))?;
if rows != records.len() as u64 {
return Err(convert(&format!(
"{} records, {rows} rows written",
records.len()
)));
}
Ok(rows)
}
fn archive_dir(data_path: &str, version: &Version) -> Result<String, Error> {
let data_path = setup::render::data_path(data_path)?;
Ok(format!(
"{}/{SOURCES}/{version}/",
setup::render::scope(&data_path)
))
}
fn sql_str(value: &str) -> String {
value.replace('\'', "''")
}
fn import_sql(secret: &str, release: &Release, dir: &Path, archive: &str, records: u64) -> String {
let schema = release.version.schema();
let local = |name: &str| sql_str(&dir.join(name).to_string_lossy());
let zip = release.filename.as_str();
let parquet = release.parquet_name();
let remote = |name: &str| sql_str(&format!("{archive}{name}"));
format!(
"{CSV}SET threads = 4;\n\
SET memory_limit = '4GB';\n\
SET temp_directory = '{home}/tmp';\n\
LOAD httpfs;\n\
{secret}\n\
COPY (SELECT content FROM read_blob('{local_zip}')) TO '{remote_zip}' (FORMAT blob);\n\
COPY (SELECT content FROM read_blob('{local_parquet}')) TO '{remote_parquet}' (FORMAT blob);\n\
CREATE SCHEMA IF NOT EXISTS {schema};\n\
BEGIN;\n\
DROP TABLE IF EXISTS {schema}.{ORGANIZATIONS};\n\
DROP TABLE IF EXISTS {schema}.{RELEASE};\n\
CREATE TABLE {schema}.{ORGANIZATIONS} AS\n \
SELECT id,\n \
(list_filter(names, lambda n: list_contains(n.types, 'ror_display'))[1]).value AS name,\n \
* EXCLUDE (id)\n \
FROM read_parquet('{remote_parquet}');\n\
CREATE TABLE {schema}.{RELEASE} AS SELECT\n \
'{version}' AS version,\n \
DATE '{date}' AS release_date,\n \
'https://doi.org/{doi}' AS doi,\n \
{records}::BIGINT AS records,\n \
'{remote_zip}' AS source_file,\n \
'{remote_parquet}' AS parquet_file,\n \
now() AS imported_at;\n\
COMMIT;\n\
SELECT count(*) FROM {schema}.{ORGANIZATIONS};\n",
home = setup::HOME,
local_zip = local(zip),
local_parquet = local(&parquet),
remote_zip = remote(zip),
remote_parquet = remote(&parquet),
version = release.version,
date = release.date,
doi = release.doi,
)
}
fn catalog_sql() -> String {
format!(
"{CSV}SELECT table_schema, table_name FROM information_schema.tables\n\
WHERE (table_schema LIKE '{RELEASE_PREFIX}v%' AND table_type = 'BASE TABLE')\n \
OR (table_schema = '{VIEW_SCHEMA}' AND table_type = 'VIEW');\n"
)
}
fn parse_catalog(output: &str) -> (Vec<Version>, Vec<String>) {
let mut tables: BTreeMap<Version, Vec<String>> = BTreeMap::new();
let mut views = Vec::new();
for (schema, table) in pairs(output) {
if schema == VIEW_SCHEMA {
views.push(table);
} else if let Some(version) = Version::from_schema(&schema)
&& version.schema() == schema
{
tables.entry(version).or_default().push(table);
}
}
let versions = tables
.into_iter()
.rev()
.filter(|(_, tables)| tables.iter().any(|t| t == RELEASE))
.map(|(version, _)| version)
.collect();
views.sort();
(versions, views)
}
fn views_sql(version: &Version) -> String {
let schema = version.schema();
let mut sql = format!("BEGIN;\nCREATE SCHEMA IF NOT EXISTS {VIEW_SCHEMA};\n");
for table in [ORGANIZATIONS, RELEASE] {
sql.push_str(&format!(
"CREATE OR REPLACE VIEW {VIEW_SCHEMA}.{table} AS FROM {schema}.{table};\n"
));
}
sql.push_str("COMMIT;\n");
sql
}
const LINUX_ONLY: &str = "hazine ror needs Linux (use --output to convert elsewhere)";
#[derive(Debug, Clone, Default)]
pub struct ImportOptions {
pub force: bool,
pub output: Option<PathBuf>,
pub dry_run: bool,
}
pub fn import(options: ImportOptions) -> Result<(), Error> {
let release = latest_release()?;
let schema = release.version.schema();
tracing::info!(
version = %release.version,
date = %release.date,
doi = %release.doi,
file = %release.filename,
%schema,
"ROR release"
);
if let Some(output) = &options.output {
std::fs::create_dir_all(output)?;
let zip = download(&release)?;
let zip_out = output.join(&release.filename);
std::fs::copy(&zip, &zip_out)?;
let parquet_out = output.join(release.parquet_name());
let rows = to_parquet(&records_json(&zip)?, &parquet_out, &release.version)?;
tracing::info!(
zip = %zip_out.display(),
parquet = %parquet_out.display(),
rows,
"wrote the ROR release"
);
return Ok(());
}
if options.dry_run {
println!(
"would download {} ({}), convert its JSON to Parquet, store both in \
<bucket>/{SOURCES}/{}/, and create {schema}.{ORGANIZATIONS} and {schema}.{RELEASE}",
release.filename, release.doi, release.version
);
println!("then: hazine ror setup (views in the {VIEW_SCHEMA} schema)");
return Ok(());
}
let runner = Runner::service(LINUX_ONLY)?;
let (versions, _) = parse_catalog(&runner.run(true, &catalog_sql())?);
if versions.contains(&release.version) && !options.force {
tracing::info!(%schema, "this version is imported already (--force imports it again)");
return Ok(());
}
let data_path = runner
.env("HAZINE_DATA_PATH")
.ok_or_else(|| Error::InvalidSetting {
name: "hazine.env",
reason: "has no HAZINE_DATA_PATH; rerun hazine setup".into(),
})?;
let archive = archive_dir(data_path, &release.version)?;
let secret = crate::lake::installed_data_secret()?;
let account = runner.account().ok_or(Error::Unsupported(LINUX_ONLY))?;
let zip = download(&release)?;
let dir = TempDir::new_in(&Path::new(setup::HOME).join("tmp"))?;
let zip_copy = dir.path().join(&release.filename);
std::fs::copy(&zip, &zip_copy)?;
let parquet = dir.path().join(release.parquet_name());
let records = to_parquet(&records_json(&zip)?, &parquet, &release.version)?;
for path in [dir.path(), &zip_copy, &parquet] {
account.chown(path)?;
}
tracing::info!(
records,
mb = format!("{:.1}", std::fs::metadata(&parquet)?.len() as f64 / 1e6),
"converted to Parquet"
);
tracing::info!(%archive, %schema, "uploading and importing");
let output = runner.run(
true,
&import_sql(&secret, &release, dir.path(), &archive, records),
)?;
let rows = last_count(&output);
if rows != Some(records) {
return Err(Error::Import(format!(
"{schema}.{ORGANIZATIONS} has {} rows, the dump {records}; rerun with --force",
rows.map_or("no".into(), |r| r.to_string()),
)));
}
tracing::info!(
%schema,
rows = records,
source = %format!("{archive}{}", release.filename),
"ROR release imported; point the {VIEW_SCHEMA} views at it with: hazine ror setup"
);
Ok(())
}
#[derive(Debug, Clone, Default)]
pub struct SetupOptions {
pub release: Option<String>,
pub dry_run: bool,
}
pub fn setup(options: SetupOptions) -> Result<(), Error> {
let runner = Runner::service(LINUX_ONLY)?;
let (versions, _) = parse_catalog(&runner.run(true, &catalog_sql())?);
let Some(newest) = versions.first() else {
return Err(Error::InvalidSetting {
name: "ROR",
reason: "no version is imported; run hazine ror import first".into(),
});
};
let version = match &options.release {
Some(wanted) => {
let wanted = Version::parse(wanted)?;
if !versions.contains(&wanted) {
return Err(Error::InvalidSetting {
name: "--release",
reason: format!(
"{wanted} is not imported; imported: {}",
versions
.iter()
.map(Version::to_string)
.collect::<Vec<_>>()
.join(", ")
),
});
}
wanted
}
None => newest.clone(),
};
let sql = views_sql(&version);
if options.dry_run {
print!("{sql}");
return Ok(());
}
runner.run(true, &sql)?;
tracing::info!(
%version,
schema = %version.schema(),
"the {VIEW_SCHEMA} schema now shows this version, e.g. FROM {VIEW_SCHEMA}.{ORGANIZATIONS}"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions_compare_by_number_and_name_schemas() {
let v2_9 = Version::parse("v2.9").unwrap();
let v2_16 = Version::parse("v2.16").unwrap();
assert!(v2_16 > v2_9);
assert_eq!(v2_16.to_string(), "v2.16");
assert_eq!(v2_16.schema(), "ror_v2_16");
assert_eq!(Version::from_schema("ror_v2_16"), Some(v2_16.clone()));
assert_eq!(Version::parse("2.16").unwrap(), v2_16);
for bad in [
"",
"v",
"v2.",
"v2..1",
"2026-11-19",
"v2.16;drop",
"v1234567",
] {
assert!(Version::parse(bad).is_err(), "{bad:?}");
}
assert_eq!(Version::from_schema("ror_scratch"), None);
}
fn zenodo() -> RorRelease {
RorRelease {
version: "v2.16".into(),
date: "2026-11-19".into(),
zenodo_id: "24378467".into(),
filename: "v2.16-2026-11-19-ror-data.zip".into(),
download_url: "https://zenodo.org/api/records/24378467/files/x/content".into(),
}
}
#[test]
fn zenodo_releases_are_checked() {
let release = Release::from_zenodo(zenodo()).unwrap();
assert_eq!(release.doi, "10.5281/zenodo.24378467");
assert_eq!(release.parquet_name(), "v2.16-2026-11-19-ror-data.parquet");
let mut bad = zenodo();
bad.filename = "x'.zip".into();
assert!(Release::from_zenodo(bad).is_err());
let mut bad = zenodo();
bad.date = "19.11.2026".into();
assert!(Release::from_zenodo(bad).is_err());
}
const RECORDS: &str = r#"[
{"locations": [{"geonames_id": 264371, "geonames_details": {"continent_code": "EU",
"continent_name": "Europe", "country_code": "GR", "country_name": "Greece",
"country_subdivision_code": "I", "country_subdivision_name": "Attica",
"lat": 37.98376, "lng": 23.72784, "name": "Athens"}}],
"established": 1989,
"external_ids": [{"type": "grid", "all": ["grid.1088.1"], "preferred": "grid.1088.1"},
{"type": "isni", "all": ["0000 0004 0622 6844"], "preferred": null}],
"id": "https://ror.org/02d439m40", "domains": [],
"links": [{"type": "website", "value": "https://www.epipsi.gr/"}],
"names": [{"value": "UMHRI", "types": ["acronym"], "lang": null},
{"value": "University Mental Health Research Institute",
"types": ["ror_display", "label"], "lang": "en"}],
"relationships": [], "status": "active", "types": ["education"],
"admin": {"created": {"date": "2018-11-14", "schema_version": "1.0"},
"last_modified": {"date": "2024-12-11", "schema_version": "2.1"}}},
{"id": "https://ror.org/00000000x", "established": null, "names": [],
"types": [], "status": "inactive", "locations": [], "external_ids": [],
"links": [], "relationships": [{"type": "successor", "label": "X",
"id": "https://ror.org/02d439m40"}], "domains": ["example.org"],
"admin": {"created": {"date": "2020-01-01", "schema_version": "2.0"},
"last_modified": {"date": "2020-01-01", "schema_version": "2.0"}}}
]"#;
#[test]
fn records_become_nested_parquet() {
use parquet::file::reader::{FileReader, SerializedFileReader};
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("ror.parquet");
let version = Version::parse("v2.16").unwrap();
assert_eq!(to_parquet(RECORDS.as_bytes(), &out, &version).unwrap(), 2);
let reader = SerializedFileReader::new(std::fs::File::open(&out).unwrap()).unwrap();
let metadata = reader.metadata().file_metadata();
assert_eq!(metadata.num_rows(), 2);
let kv = metadata.key_value_metadata().unwrap();
assert!(
kv.iter()
.any(|kv| kv.key == "ror_version" && kv.value.as_deref() == Some("v2.16"))
);
let columns: Vec<String> = metadata
.schema_descr()
.columns()
.iter()
.map(|c| c.path().string())
.collect();
for column in [
"id",
"names.list.item.value",
"locations.list.item.geonames_details.lat",
"admin.last_modified.date",
] {
assert!(
columns.iter().any(|c| c == column),
"{column} in {columns:?}"
);
}
}
#[test]
fn unknown_fields_and_missing_ids_are_refused() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("ror.parquet");
let version = Version::parse("v2.16").unwrap();
let unknown = r#"[{"id": "https://ror.org/1", "new_field": 1}]"#;
assert!(to_parquet(unknown.as_bytes(), &out, &version).is_err());
let no_id = r#"[{"status": "active"}]"#;
assert!(to_parquet(no_id.as_bytes(), &out, &version).is_err());
assert!(to_parquet(b"{}", &out, &version).is_err(), "not an array");
}
#[test]
fn originals_go_next_to_the_lake() {
let v = Version::parse("v2.16").unwrap();
assert_eq!(
archive_dir("s3://hazine/lake/", &v).unwrap(),
"s3://hazine/sources/ror/v2.16/"
);
assert_eq!(
archive_dir("s3://hazine", &v).unwrap(),
"s3://hazine/sources/ror/v2.16/"
);
}
#[test]
fn the_import_uploads_both_files_and_creates_both_tables() {
let release = Release::from_zenodo(zenodo()).unwrap();
let sql = import_sql(
"CREATE SECRET hazine_data (TYPE s3);",
&release,
Path::new("/var/lib/hazine/tmp/hazine-x"),
"s3://hazine/sources/ror/v2.16/",
152297,
);
for part in [
"CREATE SECRET hazine_data (TYPE s3);",
"COPY (SELECT content FROM read_blob('/var/lib/hazine/tmp/hazine-x/v2.16-2026-11-19-ror-data.zip')) \
TO 's3://hazine/sources/ror/v2.16/v2.16-2026-11-19-ror-data.zip' (FORMAT blob);",
"TO 's3://hazine/sources/ror/v2.16/v2.16-2026-11-19-ror-data.parquet' (FORMAT blob);",
"BEGIN;\nDROP TABLE IF EXISTS ror_v2_16.organizations;",
"FROM read_parquet('s3://hazine/sources/ror/v2.16/v2.16-2026-11-19-ror-data.parquet');",
"'v2.16' AS version,",
"DATE '2026-11-19' AS release_date,",
"'https://doi.org/10.5281/zenodo.24378467' AS doi,",
"152297::BIGINT AS records,",
"COMMIT;\nSELECT count(*) FROM ror_v2_16.organizations;",
] {
assert!(sql.contains(part), "{part} missing from\n{sql}");
}
}
#[test]
fn complete_versions_are_found_newest_first() {
let (versions, views) = parse_catalog(
"ror_v2_9,organizations\nror_v2_9,release\n\
ror_v2_16,organizations\nror_v2_16,release\n\
ror_v2_17,organizations\n\
ror,organizations\nror,release\nror_scratch,x\nror_v02_1,release\n",
);
let names: Vec<String> = versions.iter().map(Version::to_string).collect();
assert_eq!(names, ["v2.16", "v2.9"], "v2.17 lacks its release table");
assert_eq!(views, ["organizations", "release"]);
let sql = views_sql(&versions[0]);
assert!(
sql.contains(
"CREATE OR REPLACE VIEW ror.organizations AS FROM ror_v2_16.organizations;"
)
);
assert!(sql.contains("CREATE OR REPLACE VIEW ror.release AS FROM ror_v2_16.release;"));
assert!(sql.starts_with("BEGIN;") && sql.ends_with("COMMIT;\n"));
}
}