use std::collections::BTreeMap;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use arrow_schema::{DataType, Field, Fields, Schema};
use commonmeta::{Entity, Person};
use rayon::prelude::*;
use serde::Serialize;
use crate::Error;
use crate::cache;
use crate::lake::{CSV, Limits, Runner, last_count, pairs};
use crate::parts::{Layout, Part, Parts};
use crate::s3::Bucket;
use crate::setup;
use crate::tempdir::TempDir;
pub const VIEW_SCHEMA: &str = "orcid";
const RELEASE_PREFIX: &str = "orcid_";
const SOURCES: &str = "sources/orcid";
const PEOPLE: &str = "people";
const RELEASE: &str = "release";
const BATCH: usize = 10_000;
const PART_RECORDS: u64 = 1_000_000;
const CACHE_TTL: u64 = 400 * 24 * 60 * 60;
const LINUX_ONLY: &str = "hazine orcid needs Linux (use --output to convert elsewhere)";
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Version {
pub year: u16,
pub batch: u8,
}
impl Version {
pub fn parse(value: &str) -> Result<Self, Error> {
let invalid = || Error::InvalidSetting {
name: "ORCID version",
reason: format!("{value:?} is not like 2026_10"),
};
let (year, batch) = value.split_once(['_', '-']).ok_or_else(invalid)?;
let digits = |s: &str, n: usize| s.len() == n && s.bytes().all(|b| b.is_ascii_digit());
if !digits(year, 4) || !digits(batch, 2) {
return Err(invalid());
}
Ok(Version {
year: year.parse().map_err(|_| invalid())?,
batch: batch.parse().map_err(|_| invalid())?,
})
}
pub fn from_filename(name: &str) -> Result<Self, Error> {
name.strip_prefix("ORCID_")
.and_then(|rest| rest.strip_suffix("_summaries.tar.gz"))
.ok_or_else(|| Error::InvalidSetting {
name: "ORCID file",
reason: format!("{name:?} is not like ORCID_2026_10_summaries.tar.gz"),
})
.and_then(Version::parse)
}
fn from_schema(schema: &str) -> Option<Self> {
Version::parse(schema.strip_prefix(RELEASE_PREFIX)?).ok()
}
pub fn schema(&self) -> String {
format!("{RELEASE_PREFIX}{self}")
}
pub fn filename(&self) -> String {
format!("ORCID_{self}_summaries.tar.gz")
}
fn stem(&self) -> String {
format!("ORCID_{self}_summaries")
}
}
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}_{:02}", self.year, self.batch)
}
}
#[derive(Debug, Clone)]
struct Source {
version: Version,
path: PathBuf,
size: u64,
}
fn latest_release() -> Result<(Version, String, u64), Error> {
crate::tls::init();
let release = commonmeta::fetch_latest_orcid_release().map_err(|error| {
Error::Import(format!("looking up the ORCID release on figshare: {error}"))
})?;
let version = Version::from_filename(&release.filename)?;
Ok((version, release.download_url, release.size_bytes))
}
fn newest_archive(dirs: &[PathBuf]) -> Option<(Version, PathBuf)> {
dirs.iter()
.filter_map(|dir| std::fs::read_dir(dir).ok())
.flatten()
.filter_map(|entry| {
let entry = entry.ok()?;
let version = Version::from_filename(entry.file_name().to_str()?).ok()?;
entry
.file_type()
.ok()?
.is_file()
.then(|| (version, entry.path()))
})
.max_by_key(|(version, _)| *version)
}
fn find_source(file: Option<&Path>, download: bool) -> Result<Option<Source>, Error> {
let source = |version: Version, path: PathBuf| -> Result<Source, Error> {
let size = std::fs::metadata(&path)?.len();
Ok(Source {
version,
path,
size,
})
};
if let Some(file) = file {
let name = file
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default();
return Ok(Some(source(
Version::from_filename(name)?,
file.to_path_buf(),
)?));
}
if let Some((version, path)) = newest_archive(&cache::dirs("orcid")) {
let found = source(version, path)?;
match latest_release() {
Ok((latest, _, expected)) if latest == version => check_size(&found, expected)?,
Ok(_) => {}
Err(error) => {
tracing::warn!(%error, "cannot check the archive's size against figshare")
}
}
return Ok(Some(found));
}
if !download {
return Ok(None);
}
let (version, url, expected) = latest_release()?;
let filename = version.filename();
tracing::info!(%filename, gb = format!("{:.0}", expected as f64 / 1e9), "downloading from figshare");
let (path, _) = commonmeta::io_utils::ensure_cached_path(
&url,
"orcid",
&filename,
std::time::Duration::from_secs(CACHE_TTL),
)
.map_err(|error| Error::Import(format!("downloading {filename}: {error}")))?;
let found = source(version, path)?;
check_size(&found, expected)?;
Ok(Some(found))
}
fn check_size(source: &Source, expected: u64) -> Result<(), Error> {
if expected > 0 && source.size != expected {
return Err(Error::Import(format!(
"{} has {} bytes, figshare lists {expected}: an incomplete download? \
Remove it to download it again, or give another with --file",
source.path.display(),
source.size
)));
}
Ok(())
}
fn orcid_of(path: &Path) -> Option<String> {
if path.extension()? != "xml" {
return None;
}
let id = path.file_stem()?.to_str()?;
let bytes = id.as_bytes();
let valid = bytes.len() == 19
&& bytes.iter().enumerate().all(|(i, b)| match i {
4 | 9 | 14 => *b == b'-',
18 => b.is_ascii_digit() || *b == b'X',
_ => b.is_ascii_digit(),
});
valid.then(|| id.to_string())
}
fn error_code(xml: &str) -> Option<i32> {
let head = &xml[..xml.len().min(400)];
if !head.contains("<error:error") {
return None;
}
let code = xml
.split_once("<error:response-code>")
.and_then(|(_, rest)| rest.split_once("</error:response-code>"))
.and_then(|(code, _)| code.trim().parse().ok());
Some(code.unwrap_or(0))
}
#[derive(Serialize)]
struct Row<'a> {
orcid: &'a str,
error_code: Option<i32>,
#[serde(flatten)]
person: Option<Person>,
xml: &'a str,
}
fn row<'a>(orcid: &'a str, xml: &'a str) -> Row<'a> {
let error_code = error_code(xml);
let person = match error_code {
Some(_) => None,
None => match commonmeta::read("orcid_xml", xml) {
Ok(Entity::Person(person)) => Some(person),
_ => None,
},
};
Row {
orcid,
error_code,
person,
xml,
}
}
pub fn schema() -> Schema {
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,
)
};
Schema::new(vec![
Field::new("orcid", DataType::Utf8, false),
Field::new("error_code", DataType::Int32, true),
utf8("id"),
utf8("given_name"),
utf8("family_name"),
utf8("name"),
Field::new(
"additional_names",
DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
true,
),
utf8("description"),
list_of(
"affiliations",
vec![
utf8("identifier"),
utf8("identifier_type"),
utf8("name"),
utf8("role"),
utf8("start_date"),
utf8("end_date"),
utf8("asserted_by"),
],
),
list_of(
"identifiers",
vec![
utf8("identifier"),
utf8("identifier_type"),
utf8("scheme"),
utf8("asserted_by"),
],
),
list_of("urls", vec![utf8("name"), utf8("url")]),
utf8("country"),
utf8("date_updated"),
utf8("asserted_by"),
Field::new("xml", DataType::Utf8, false),
])
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
pub records: u64,
pub people: u64,
pub errors: u64,
pub unparsed: u64,
pub skipped: u64,
}
fn convert_error(error: impl std::fmt::Display) -> Error {
Error::Import(format!("converting the ORCID archive: {error}"))
}
pub fn convert(
tar_gz: &Path,
dir: &Path,
version: Version,
threads: usize,
on_part: impl FnMut(Part) -> Result<(), Error>,
) -> Result<Counts, Error> {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(threads.max(1))
.build()
.map_err(convert_error)?;
let mut parts = Parts::new(
dir,
schema(),
Layout {
batch: BATCH,
part_rows: PART_RECORDS,
metadata: vec![("orcid_version".into(), version.to_string())],
},
"converting the ORCID archive",
on_part,
)?;
let file = std::fs::File::open(tar_gz)?;
let gz = flate2::read::GzDecoder::new(BufReader::with_capacity(1 << 20, file));
let mut archive = tar::Archive::new(gz);
let mut counts = Counts::default();
let mut chunk: Vec<(String, String)> = Vec::with_capacity(BATCH);
let started = Instant::now();
let flush = |chunk: &mut Vec<(String, String)>,
counts: &mut Counts,
parts: &mut Parts<'_, _>|
-> Result<(), Error> {
let rows: Vec<Row<'_>> =
pool.install(|| chunk.par_iter().map(|(id, xml)| row(id, xml)).collect());
for row in &rows {
counts.records += 1;
match (&row.error_code, &row.person) {
(Some(_), _) => counts.errors += 1,
(None, Some(_)) => counts.people += 1,
(None, None) => counts.unparsed += 1,
}
}
parts.write(&rows)?;
chunk.clear();
if counts.records % (10 * BATCH as u64) == 0 {
tracing::info!(
records = counts.records,
per_s = format!(
"{:.0}",
counts.records as f64 / started.elapsed().as_secs_f64()
),
"converting"
);
}
Ok(())
};
for entry in archive.entries().map_err(convert_error)? {
let mut entry = entry.map_err(convert_error)?;
if entry.header().entry_type().is_dir() {
continue;
}
let path = entry.path().map_err(convert_error)?.into_owned();
let Some(orcid) = orcid_of(&path) else {
std::io::copy(&mut entry, &mut std::io::sink()).map_err(convert_error)?;
counts.skipped += 1;
tracing::debug!(path = %path.display(), "not an ORCID record; skipped");
continue;
};
let mut bytes = Vec::with_capacity(entry.size() as usize);
entry.read_to_end(&mut bytes).map_err(convert_error)?;
let xml = String::from_utf8(bytes)
.unwrap_or_else(|error| String::from_utf8_lossy(error.as_bytes()).into_owned());
chunk.push((orcid, xml));
if chunk.len() == BATCH {
flush(&mut chunk, &mut counts, &mut parts)?;
}
}
if !chunk.is_empty() {
flush(&mut chunk, &mut counts, &mut parts)?;
}
std::io::copy(&mut archive.into_inner(), &mut std::io::sink()).map_err(convert_error)?;
parts.finish()?;
Ok(counts)
}
fn sql_str(value: &str) -> String {
value.replace('\'', "''")
}
fn import_sql(
limits: &Limits,
secret: &str,
version: Version,
source_file: &str,
part_files: &[String],
counts: &Counts,
) -> String {
let schema = version.schema();
let files = part_files
.iter()
.map(|url| format!("'{}'", sql_str(url)))
.collect::<Vec<_>>()
.join(",\n ");
format!(
"{CSV}SET threads = {threads};\n\
SET memory_limit = '{memory}';\n\
SET preserve_insertion_order = false;\n\
SET temp_directory = '{home}/tmp';\n\
LOAD httpfs;\n\
{secret}\n\
CREATE SCHEMA IF NOT EXISTS {schema};\n\
BEGIN;\n\
DROP TABLE IF EXISTS {schema}.{PEOPLE};\n\
DROP TABLE IF EXISTS {schema}.{RELEASE};\n\
CREATE TABLE {schema}.{PEOPLE} AS\n \
SELECT * EXCLUDE (error_code, xml)\n \
FROM read_parquet([\n {files}\n ])\n \
WHERE error_code IS NULL AND id IS NOT NULL;\n\
CREATE TABLE {schema}.{RELEASE} AS SELECT\n \
'{version}' AS version,\n \
{year} AS year,\n \
{batch} AS batch,\n \
{records}::BIGINT AS records,\n \
{people}::BIGINT AS people,\n \
{errors}::BIGINT AS errors,\n \
{unparsed}::BIGINT AS unparsed,\n \
'{source}' AS source_file,\n \
[\n {files}\n ] AS parquet_files,\n \
now() AS imported_at;\n\
COMMIT;\n\
SELECT count(*) FROM {schema}.{PEOPLE};\n",
threads = limits.threads,
memory = sql_str(&limits.memory_limit),
home = setup::HOME,
year = version.year,
batch = version.batch,
records = counts.records,
people = counts.people,
errors = counts.errors,
unparsed = counts.unparsed,
source = sql_str(source_file),
)
}
fn catalog_sql() -> String {
format!(
"{CSV}SELECT table_schema, table_name FROM information_schema.tables\n\
WHERE (table_schema LIKE '{RELEASE_PREFIX}%' AND table_type = 'BASE TABLE')\n \
OR (table_schema = '{VIEW_SCHEMA}' AND table_type = 'VIEW');\n"
)
}
fn parse_catalog(output: &str) -> Vec<Version> {
let mut tables: BTreeMap<Version, Vec<String>> = BTreeMap::new();
for (schema, table) in pairs(output) {
if let Some(version) = Version::from_schema(&schema)
&& version.schema() == schema
{
tables.entry(version).or_default().push(table);
}
}
tables
.into_iter()
.rev()
.filter(|(_, tables)| tables.iter().any(|t| t == RELEASE))
.map(|(version, _)| version)
.collect()
}
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 [PEOPLE, RELEASE] {
sql.push_str(&format!(
"CREATE OR REPLACE VIEW {VIEW_SCHEMA}.{table} AS FROM {schema}.{table};\n"
));
}
sql.push_str("COMMIT;\n");
sql
}
#[derive(Debug, Clone, Default)]
pub struct ImportOptions {
pub file: Option<PathBuf>,
pub force: bool,
pub threads: Option<usize>,
pub memory_limit: Option<String>,
pub output: Option<PathBuf>,
pub dry_run: bool,
}
fn log_counts(counts: &Counts, started: Instant) {
tracing::info!(
records = counts.records,
people = counts.people,
errors = counts.errors,
unparsed = counts.unparsed,
skipped = counts.skipped,
minutes = format!("{:.1}", started.elapsed().as_secs_f64() / 60.0),
"converted"
);
}
pub fn import(options: ImportOptions) -> Result<(), Error> {
let threads = Limits::threads(options.threads)?;
if let Some(output) = &options.output {
let source = find_source(options.file.as_deref(), true)?
.expect("find_source downloads when asked to");
std::fs::create_dir_all(output)?;
let dir = output.join(source.version.stem());
std::fs::create_dir_all(&dir)?;
tracing::info!(file = %source.path.display(), version = %source.version, threads = threads, "converting");
let started = Instant::now();
let counts = convert(&source.path, &dir, source.version, threads, |part| {
tracing::info!(part = %part.path.display(), rows = part.rows, "wrote");
Ok(())
})?;
log_counts(&counts, started);
return Ok(());
}
if options.dry_run {
let (version, gb) = match find_source(options.file.as_deref(), false)? {
Some(source) => {
println!(
"archive: {} ({:.1} GB)",
source.path.display(),
source.size as f64 / 1e9
);
(source.version, source.size as f64 / 1e9)
}
None => {
let (version, url, size) = latest_release()?;
println!(
"archive: not on this host; would download {} from {url}",
version.filename()
);
(version, size as f64 / 1e9)
}
};
println!(
"would store it ({gb:.1} GB) and its Parquet parts in <bucket>/{SOURCES}/{version}/, \
and create {schema}.{PEOPLE} and {schema}.{RELEASE}",
schema = version.schema()
);
println!("then: hazine orcid setup (views in the {VIEW_SCHEMA} schema)");
return Ok(());
}
let runner = Runner::service(LINUX_ONLY)?;
let limits = Limits::new(options.threads, options.memory_limit.clone())?;
let source =
find_source(options.file.as_deref(), true)?.expect("find_source downloads when asked to");
let version = source.version;
let schema = version.schema();
if parse_catalog(&runner.run(true, &catalog_sql())?).contains(&version) && !options.force {
tracing::info!(%schema, "this version is imported already (--force imports it again)");
return Ok(());
}
let secret = crate::lake::installed_data_secret()?;
let bucket = Bucket::from_env(
|name| runner.env(name).map(str::to_string),
crate::lake::installed_use_ssl()?,
)?;
let prefix = format!("{SOURCES}/{version}");
let dir = TempDir::new_in(&Path::new(setup::HOME).join("tmp"))?;
let mut part_urls = Vec::new();
tracing::info!(file = %source.path.display(), %version, threads = limits.threads, "converting");
let started = Instant::now();
let counts = convert(&source.path, dir.path(), version, limits.threads, |part| {
let key = format!(
"{prefix}/{}/{}",
version.stem(),
part.path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default()
);
let size = bucket.upload(&part.path, &key)?;
verify_size(&bucket, &key, size)?;
std::fs::remove_file(&part.path)?;
tracing::info!(part = part.index, rows = part.rows, to = %bucket.url(&key), "uploaded");
part_urls.push(bucket.url(&key));
Ok(())
})?;
log_counts(&counts, started);
if counts.records == 0 {
return Err(Error::Import(format!(
"{} holds no ORCID records",
source.path.display()
)));
}
let source_key = format!("{prefix}/{}", version.filename());
let source_url = bucket.url(&source_key);
if bucket.size(&source_key)? == Some(source.size) {
tracing::info!(file = %source_url, "the archive is stored already");
} else {
tracing::info!(
file = %source.path.display(),
to = %source_url,
gb = format!("{:.1}", source.size as f64 / 1e9),
"uploading the archive"
);
let begun = Instant::now();
bucket.upload(&source.path, &source_key)?;
verify_size(&bucket, &source_key, source.size)?;
tracing::info!(
mb_per_s = format!(
"{:.0}",
source.size as f64 / 1e6 / begun.elapsed().as_secs_f64().max(0.001)
),
"uploaded the archive"
);
}
tracing::info!(%schema, parts = part_urls.len(), "creating the tables");
let output = runner.run(
true,
&import_sql(&limits, &secret, version, &source_url, &part_urls, &counts),
)?;
let rows = last_count(&output);
if rows != Some(counts.people) {
return Err(Error::Import(format!(
"{schema}.{PEOPLE} has {} rows, the archive {} people; rerun with --force",
rows.map_or("no".into(), |r| r.to_string()),
counts.people
)));
}
tracing::info!(
%schema,
people = counts.people,
"ORCID release imported; point the {VIEW_SCHEMA} views at it with: hazine orcid setup"
);
Ok(())
}
fn verify_size(bucket: &Bucket, key: &str, size: u64) -> Result<(), Error> {
match bucket.size(key)? {
Some(stored) if stored == size => Ok(()),
stored => Err(Error::Import(format!(
"{} has {} bytes after the upload, the file {size}",
bucket.url(key),
stored.map_or("no".into(), |s| s.to_string())
))),
}
}
#[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: "ORCID",
reason: "no version is imported; run hazine orcid 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,
};
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}.{PEOPLE}"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions_come_from_file_names_and_sort_by_date() {
let v = Version::from_filename("ORCID_2026_10_summaries.tar.gz").unwrap();
assert_eq!(
v,
Version {
year: 2026,
batch: 10
}
);
assert_eq!(v.to_string(), "2026_10");
assert_eq!(v.schema(), "orcid_2026_10");
assert_eq!(v.filename(), "ORCID_2026_10_summaries.tar.gz");
assert_eq!(Version::parse("2026-10").unwrap(), v);
assert!(Version::parse("2027_01").unwrap() > v);
assert_eq!(Version::from_schema("orcid_2026_10"), Some(v));
for bad in [
"ORCID_2026_10.tar.gz",
"orcid_summaries.tar.gz",
"ORCID_26_10_summaries.tar.gz",
] {
assert!(Version::from_filename(bad).is_err(), "{bad}");
}
assert_eq!(Version::from_schema("orcid_scratch"), None);
}
#[test]
fn entries_are_named_by_their_id() {
let id = |p: &str| orcid_of(Path::new(p));
assert_eq!(
id("ORCID_2026_10_summaries/097/0000-0002-1825-0097.xml").as_deref(),
Some("0000-0002-1825-0097")
);
assert_eq!(
id("x/0000-0002-1694-233X.xml").as_deref(),
Some("0000-0002-1694-233X")
);
assert_eq!(id("x/README.txt"), None);
assert_eq!(id("x/0000-0002-1825.xml"), None);
assert_eq!(id("x/0000-0002-1825-0097.json"), None);
}
#[test]
fn the_newest_cached_archive_is_found() {
let a = tempfile::tempdir().unwrap();
let b = tempfile::tempdir().unwrap();
for name in [
"ORCID_2025_10_summaries.tar.gz",
"ORCID_2027_10_summaries.tar.gz.part",
"orcid_summaries.tar.gz",
] {
std::fs::write(a.path().join(name), "").unwrap();
}
std::fs::write(b.path().join("ORCID_2026_10_summaries.tar.gz"), "").unwrap();
let dirs = [
a.path().to_path_buf(),
b.path().join("missing"),
b.path().to_path_buf(),
];
let (version, path) = newest_archive(&dirs).unwrap();
assert_eq!(version.to_string(), "2026_10");
assert_eq!(path, b.path().join("ORCID_2026_10_summaries.tar.gz"));
assert_eq!(newest_archive(&[b.path().join("missing")]), None);
}
const RECORD: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<record:record xmlns:record="http://www.orcid.org/ns/record" xmlns:common="http://www.orcid.org/ns/common" xmlns:person="http://www.orcid.org/ns/person" xmlns:personal-details="http://www.orcid.org/ns/personal-details" xmlns:activities="http://www.orcid.org/ns/activities" xmlns:employment="http://www.orcid.org/ns/employment" path="/0000-0002-1825-0097">
<common:orcid-identifier>
<common:uri>https://orcid.org/0000-0002-1825-0097</common:uri>
<common:path>0000-0002-1825-0097</common:path>
<common:host>orcid.org</common:host>
</common:orcid-identifier>
<person:person path="/0000-0002-1825-0097/person">
<person:name visibility="public" path="0000-0002-1825-0097">
<personal-details:given-names>Josiah</personal-details:given-names>
<personal-details:family-name>Carberry</personal-details:family-name>
</person:name>
</person:person>
<activities:activities-summary path="/0000-0002-1825-0097/activities">
<activities:employments path="/0000-0002-1825-0097/employments">
<activities:affiliation-group>
<employment:employment-summary put-code="1" visibility="public">
<common:start-date><common:year>1992</common:year></common:start-date>
<common:organization>
<common:name>Brown University</common:name>
<common:disambiguated-organization>
<common:disambiguated-organization-identifier>https://ror.org/05gq02987</common:disambiguated-organization-identifier>
<common:disambiguation-source>ROR</common:disambiguation-source>
</common:disambiguated-organization>
</common:organization>
</employment:employment-summary>
</activities:affiliation-group>
</activities:employments>
</activities:activities-summary>
</record:record>
"#;
const LOCKED: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<error:error xmlns:error="http://www.orcid.org/ns/error">
<error:response-code>409</error:response-code>
<error:developer-message>409 Conflict: The ORCID record is locked and cannot be edited. ORCID 0009-0009-8592-7000</error:developer-message>
</error:error>
"#;
#[test]
fn records_are_read_and_stubs_recognized() {
let person = row("0000-0002-1825-0097", RECORD);
assert_eq!(person.error_code, None);
let p = person.person.expect("a person");
assert_eq!(p.id, "https://orcid.org/0000-0002-1825-0097");
assert_eq!(p.family_name, "Carberry");
let locked = row("0009-0009-8592-7000", LOCKED);
assert_eq!(locked.error_code, Some(409));
assert!(locked.person.is_none());
let broken = row("0000-0000-0000-0000", "<record:record");
assert_eq!((broken.error_code, broken.person.is_none()), (None, true));
}
fn archive(entries: &[(&str, &str)], truncate: bool) -> Vec<u8> {
let mut builder = tar::Builder::new(flate2::write::GzEncoder::new(
Vec::new(),
flate2::Compression::fast(),
));
for (path, content) in entries {
let mut header = tar::Header::new_gnu();
header.set_size(content.len() as u64);
header.set_mode(0o644);
header.set_cksum();
builder
.append_data(&mut header, path, content.as_bytes())
.unwrap();
}
let mut bytes = builder.into_inner().unwrap().finish().unwrap();
if truncate {
bytes.truncate(bytes.len() * 2 / 3);
}
bytes
}
#[test]
fn archives_become_parquet_parts() {
use parquet::file::reader::{FileReader, SerializedFileReader};
let dir = tempfile::tempdir().unwrap();
let tar_gz = dir.path().join("ORCID_2026_10_summaries.tar.gz");
let s = "ORCID_2026_10_summaries";
std::fs::write(
&tar_gz,
archive(
&[
(&format!("{s}/097/0000-0002-1825-0097.xml"), RECORD),
(&format!("{s}/000/0009-0009-8592-7000.xml"), LOCKED),
(
&format!("{s}/000/0000-0000-0000-0000.xml"),
"<record:record",
),
(&format!("{s}/README.txt"), "not a record"),
],
false,
),
)
.unwrap();
let out = dir.path().join("out");
std::fs::create_dir(&out).unwrap();
let mut parts = Vec::new();
let version = Version::parse("2026_10").unwrap();
let counts = convert(&tar_gz, &out, version, 2, |part| {
parts.push((part.index, part.rows));
Ok(())
})
.unwrap();
assert_eq!(
counts,
Counts {
records: 3,
people: 1,
errors: 1,
unparsed: 1,
skipped: 1
}
);
assert_eq!(parts, [(0, 3)]);
let reader =
SerializedFileReader::new(std::fs::File::open(out.join("part-00000.parquet")).unwrap())
.unwrap();
let metadata = reader.metadata().file_metadata();
assert_eq!(metadata.num_rows(), 3);
let columns: Vec<String> = metadata
.schema_descr()
.columns()
.iter()
.map(|c| c.path().string())
.collect();
for column in [
"orcid",
"error_code",
"family_name",
"affiliations.list.item.identifier",
"xml",
] {
assert!(
columns.iter().any(|c| c == column),
"{column} in {columns:?}"
);
}
}
#[test]
fn truncated_archives_are_refused() {
let dir = tempfile::tempdir().unwrap();
let tar_gz = dir.path().join("ORCID_2026_10_summaries.tar.gz");
let big = RECORD.repeat(50);
let entries: Vec<(String, &str)> = (0..20)
.map(|i| (format!("x/0000-0002-1825-{i:04}.xml"), big.as_str()))
.collect();
let refs: Vec<(&str, &str)> = entries.iter().map(|(p, c)| (p.as_str(), *c)).collect();
std::fs::write(&tar_gz, archive(&refs, true)).unwrap();
let version = Version::parse("2026_10").unwrap();
let result = convert(&tar_gz, dir.path(), version, 1, |_| Ok(()));
assert!(result.is_err(), "{result:?}");
}
#[test]
fn the_import_creates_people_and_release_from_the_parts() {
let limits = Limits {
threads: 8,
memory_limit: "30GB".into(),
};
let counts = Counts {
records: 3,
people: 1,
errors: 1,
unparsed: 1,
skipped: 0,
};
let version = Version::parse("2026_10").unwrap();
let sql = import_sql(
&limits,
"CREATE SECRET hazine_data (TYPE s3);",
version,
"s3://lake/sources/orcid/2026_10/ORCID_2026_10_summaries.tar.gz",
&["s3://lake/sources/orcid/2026_10/ORCID_2026_10_summaries/part-00000.parquet".into()],
&counts,
);
for part in [
"SET threads = 8;",
"CREATE SECRET hazine_data (TYPE s3);",
"BEGIN;\nDROP TABLE IF EXISTS orcid_2026_10.people;",
"SELECT * EXCLUDE (error_code, xml)",
"'s3://lake/sources/orcid/2026_10/ORCID_2026_10_summaries/part-00000.parquet'",
"WHERE error_code IS NULL AND id IS NOT NULL;",
"'2026_10' AS version,",
"1::BIGINT AS people,",
"COMMIT;\nSELECT count(*) FROM orcid_2026_10.people;",
] {
assert!(sql.contains(part), "{part} missing from\n{sql}");
}
}
#[test]
fn complete_versions_are_found_newest_first() {
let versions = parse_catalog(
"orcid_2025_10,people\norcid_2025_10,release\norcid_2026_10,people\n\
orcid_2026_10,release\norcid_2027_10,people\norcid,people\norcid_scratch,x\n",
);
let names: Vec<String> = versions.iter().map(Version::to_string).collect();
assert_eq!(
names,
["2026_10", "2025_10"],
"2027_10 lacks its release table"
);
let sql = views_sql(versions[0]);
assert!(sql.contains("CREATE OR REPLACE VIEW orcid.people AS FROM orcid_2026_10.people;"));
assert!(
sql.contains("CREATE OR REPLACE VIEW orcid.release AS FROM orcid_2026_10.release;")
);
}
}