use std::collections::BTreeMap;
use std::time::Instant;
use crate::Error;
use crate::lake::{CSV, Runner, last_count, pairs};
use crate::setup;
pub use crate::lake::data_secret;
const MANIFEST: &str = "https://openalex.s3.amazonaws.com/data/parquet/manifest.json";
pub const VIEW_SCHEMA: &str = "openalex";
const RELEASE_PREFIX: &str = "openalex_";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Release {
pub date: String,
pub entities: Vec<Entity>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entity {
pub name: String,
pub records: u64,
pub bytes: u64,
pub files: Vec<String>,
}
impl Release {
pub fn schema(&self) -> String {
format!("{RELEASE_PREFIX}{}", self.date.replace('-', "_"))
}
pub fn totals(&self) -> (u64, u64) {
self.entities
.iter()
.fold((0, 0), |(r, b), e| (r + e.records, b + e.bytes))
}
}
pub fn table_name(entity: &str) -> String {
entity.replace('-', "_")
}
pub fn parse_manifest(output: &str) -> Result<Release, Error> {
let invalid = |reason: String| Error::InvalidSetting {
name: "OpenAlex manifest",
reason,
};
let mut date: Option<String> = None;
let mut entities: BTreeMap<String, Entity> = BTreeMap::new();
for line in output.lines() {
let fields: Vec<&str> = line.trim().split(',').collect();
let [d, name, records, bytes, url] = fields[..] else {
continue;
};
if !is_date(d) || !url.starts_with("s3://openalex/") {
continue;
}
if !is_entity(name) {
return Err(invalid(format!("unexpected entity name {name:?}")));
}
match &date {
None => date = Some(d.to_string()),
Some(seen) if seen != d => {
return Err(invalid(format!("two release dates, {seen} and {d}")));
}
Some(_) => {}
}
let (records, bytes) = match (records.parse(), bytes.parse()) {
(Ok(r), Ok(b)) => (r, b),
_ => return Err(invalid(format!("bad counts in {line:?}"))),
};
entities
.entry(name.to_string())
.or_insert_with(|| Entity {
name: name.to_string(),
records,
bytes,
files: Vec::new(),
})
.files
.push(url.to_string());
}
let date = date.ok_or_else(|| invalid("no files listed".into()))?;
let mut entities: Vec<Entity> = entities.into_values().collect();
for entity in &mut entities {
entity.files.sort();
}
entities.sort_by_key(|e| (e.bytes, e.name.clone()));
Ok(Release { date, entities })
}
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 is_entity(value: &str) -> bool {
!value.is_empty() && value.chars().all(|c| c.is_ascii_lowercase() || c == '-')
}
fn manifest_sql() -> String {
format!(
"{CSV}LOAD httpfs;\n\
SELECT m.date, e.entity, e.record_count, e.content_length, f.url\n\
FROM read_json('{MANIFEST}') AS m,\n \
unnest(m.entities) AS t(e), unnest(e.files) AS u(f);\n"
)
}
#[derive(Debug, Clone)]
pub struct Limits {
pub threads: usize,
pub memory_limit: String,
}
fn import_sql(limits: &Limits, secret: &str, schema: &str, entity: &Entity) -> String {
let table = table_name(&entity.name);
let files = entity
.files
.iter()
.map(|url| format!("'{}'", url.replace('\'', "''")))
.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 SECRET openalex (TYPE s3, SCOPE 's3://openalex', REGION 'us-east-1');\n\
CREATE SCHEMA IF NOT EXISTS {schema};\n\
BEGIN;\n\
DROP TABLE IF EXISTS {schema}.{table};\n\
CREATE TABLE {schema}.{table} AS FROM read_parquet([\n {files}\n ], \
union_by_name = true, hive_partitioning = false);\n\
COMMIT;\n\
SELECT count(*) FROM {schema}.{table};\n",
threads = limits.threads,
memory = limits.memory_limit.replace('\'', "''"),
home = setup::HOME,
)
}
fn counts_sql(schema: &str, tables: &[String]) -> String {
if tables.is_empty() {
return String::new();
}
let selects = tables
.iter()
.map(|table| format!("SELECT '{table}' AS t, count(*) AS n FROM {schema}.{table}"))
.collect::<Vec<_>>()
.join("\n UNION ALL ");
format!("{CSV}{selects};\n")
}
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<(String, Vec<String>)>, Vec<String>) {
let mut releases: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut views = Vec::new();
for (schema, table) in pairs(output) {
if schema == VIEW_SCHEMA {
views.push(table);
} else if schema
.strip_prefix(RELEASE_PREFIX)
.is_some_and(|date| is_date(&date.replace('_', "-")))
{
releases.entry(schema).or_default().push(table);
}
}
let mut releases: Vec<_> = releases.into_iter().collect();
releases.reverse();
for (_, tables) in &mut releases {
tables.sort();
}
views.sort();
(releases, views)
}
fn views_sql(schema: &str, date: &str, tables: &[String], old_views: &[String]) -> String {
let mut sql = format!("BEGIN;\nCREATE SCHEMA IF NOT EXISTS {VIEW_SCHEMA};\n");
for view in old_views {
if !tables.contains(view) && view != "release" {
sql.push_str(&format!("DROP VIEW {VIEW_SCHEMA}.{view};\n"));
}
}
for table in tables {
sql.push_str(&format!(
"CREATE OR REPLACE VIEW {VIEW_SCHEMA}.{table} AS FROM {schema}.{table};\n"
));
}
sql.push_str(&format!(
"CREATE OR REPLACE VIEW {VIEW_SCHEMA}.release AS SELECT DATE '{date}' AS release_date, \
'{schema}' AS schema_name;\nCOMMIT;\n"
));
sql
}
fn current_release(runner: &Runner) -> Result<Release, Error> {
parse_manifest(&runner.run(false, &manifest_sql())?)
}
#[derive(Debug, Clone, Default)]
pub struct ImportOptions {
pub entities: Vec<String>,
pub threads: Option<usize>,
pub memory_limit: Option<String>,
pub dry_run: bool,
}
pub fn import(options: ImportOptions) -> Result<(), Error> {
let runner = if options.dry_run {
Runner::Local
} else {
Runner::service("hazine openalex needs Linux")?
};
let mut release = current_release(&runner)?;
if !options.entities.is_empty() {
for name in &options.entities {
if !release.entities.iter().any(|e| &e.name == name) {
return Err(Error::InvalidSetting {
name: "--entities",
reason: format!(
"{name:?} is not in release {}; it has: {}",
release.date,
release
.entities
.iter()
.map(|e| e.name.as_str())
.collect::<Vec<_>>()
.join(", ")
),
});
}
}
release
.entities
.retain(|e| options.entities.contains(&e.name));
}
let schema = release.schema();
let (records, bytes) = release.totals();
tracing::info!(
release = %release.date,
%schema,
entities = release.entities.len(),
records,
gb = format!("{:.1}", gb(bytes)),
"OpenAlex release"
);
if options.dry_run {
for entity in &release.entities {
println!(
"{schema}.{:<18} {:>12} rows {:>9.2} GB {:>5} files",
table_name(&entity.name),
entity.records,
gb(entity.bytes),
entity.files.len()
);
}
println!("then: hazine openalex setup (views in the {VIEW_SCHEMA} schema)");
return Ok(());
}
let limits = limits(&options)?;
let secret = crate::lake::installed_data_secret()?;
tracing::info!(threads = limits.threads, memory_limit = %limits.memory_limit, "import limits");
let (catalog, _) = parse_catalog(&runner.run(true, &catalog_sql())?);
let existing = catalog
.into_iter()
.find(|(name, _)| *name == schema)
.map(|(_, tables)| tables)
.unwrap_or_default();
let counts: BTreeMap<String, u64> = pairs(&runner.run(true, &counts_sql(&schema, &existing))?)
.into_iter()
.filter_map(|(table, n)| Some((table, n.parse().ok()?)))
.collect();
let started = Instant::now();
for (n, entity) in release.entities.iter().enumerate() {
let table = table_name(&entity.name);
let step = format!("{}/{}", n + 1, release.entities.len());
if counts.get(&table) == Some(&entity.records) {
tracing::info!(%step, table = %format!("{schema}.{table}"), rows = entity.records, "already imported");
continue;
}
let current = current_release(&runner)?.date;
if current != release.date {
return Err(Error::InvalidSetting {
name: "OpenAlex release",
reason: format!(
"OpenAlex published {current} during the import of {}; rerun to import {current}",
release.date
),
});
}
tracing::info!(
%step,
table = %format!("{schema}.{table}"),
rows = entity.records,
gb = format!("{:.2}", gb(entity.bytes)),
files = entity.files.len(),
"importing"
);
let begun = Instant::now();
let output = runner.run(true, &import_sql(&limits, &secret, &schema, entity))?;
let rows = last_count(&output);
if rows != Some(entity.records) {
return Err(Error::InvalidSetting {
name: "import",
reason: format!(
"{schema}.{table} has {} rows, the manifest says {}; rerun to retry it",
rows.map_or("no".into(), |r| r.to_string()),
entity.records
),
});
}
let seconds = begun.elapsed().as_secs_f64().max(0.001);
tracing::info!(
%step,
table = %format!("{schema}.{table}"),
rows = entity.records,
seconds = format!("{seconds:.0}"),
mb_per_s = format!("{:.0}", entity.bytes as f64 / 1e6 / seconds),
"imported"
);
}
tracing::info!(
%schema,
minutes = format!("{:.0}", started.elapsed().as_secs_f64() / 60.0),
"OpenAlex release imported; point the {VIEW_SCHEMA} views at it with: hazine openalex setup"
);
Ok(())
}
fn limits(options: &ImportOptions) -> Result<Limits, Error> {
let threads = match options.threads {
Some(threads) => threads.max(1),
None => (std::thread::available_parallelism()?.get() / 2).max(1),
};
let memory_limit = match &options.memory_limit {
Some(limit) => limit.clone(),
None => format!("{}GB", (setup::memory_gb()? / 5).max(1)),
};
Ok(Limits {
threads,
memory_limit,
})
}
fn gb(bytes: u64) -> f64 {
bytes as f64 / 1e9
}
#[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("hazine openalex needs Linux")?;
let (releases, views) = parse_catalog(&runner.run(true, &catalog_sql())?);
if releases.is_empty() {
return Err(Error::InvalidSetting {
name: "OpenAlex",
reason: "no release is imported; run hazine openalex import first".into(),
});
}
let (schema, tables) = match &options.release {
Some(date) => {
let schema = format!("{RELEASE_PREFIX}{}", date.replace('-', "_"));
releases
.iter()
.find(|(name, _)| *name == schema)
.cloned()
.ok_or_else(|| Error::InvalidSetting {
name: "--release",
reason: format!(
"{date} is not imported; imported: {}",
releases
.iter()
.map(|(name, _)| release_date(name))
.collect::<Vec<_>>()
.join(", ")
),
})?
}
None => releases[0].clone(),
};
let date = release_date(&schema);
if !tables.iter().any(|t| t == "works") {
tracing::warn!(%schema, "this release has no works table; is its import finished?");
}
let sql = views_sql(&schema, &date, &tables, &views);
if options.dry_run {
print!("{sql}");
return Ok(());
}
runner.run(true, &sql)?;
tracing::info!(
release = %date,
%schema,
views = tables.len(),
"the {VIEW_SCHEMA} schema now shows this release, e.g. FROM {VIEW_SCHEMA}.works"
);
Ok(())
}
fn release_date(schema: &str) -> String {
schema
.strip_prefix(RELEASE_PREFIX)
.unwrap_or(schema)
.replace('_', "-")
}
#[cfg(test)]
mod tests {
use super::*;
const MANIFEST_OUTPUT: &str = "\
┌─────────┐
│ Success │
└─────────┘
2026-10-14,works,464765485,744042462611,s3://openalex/data/parquet/works/updated_date=2026-10-14/part_0001.parquet
2026-10-14,institution-types,8,1000,s3://openalex/data/parquet/institution-types/updated_date=2026-10-14/part_0000.parquet
2026-10-14,works,464765485,744042462611,s3://openalex/data/parquet/works/updated_date=2016-06-24/part_0000.parquet
";
#[test]
fn the_manifest_becomes_a_release_smallest_first() {
let release = parse_manifest(MANIFEST_OUTPUT).unwrap();
assert_eq!(release.date, "2026-10-14");
assert_eq!(release.schema(), "openalex_2026_10_14");
let names: Vec<_> = release.entities.iter().map(|e| e.name.as_str()).collect();
assert_eq!(names, ["institution-types", "works"]);
let works = &release.entities[1];
assert_eq!(works.records, 464_765_485);
assert_eq!(works.files.len(), 2);
assert!(works.files[0].contains("2016-06-24"), "files are sorted");
assert_eq!(release.totals(), (464_765_493, 744_042_463_611));
}
#[test]
fn mixed_releases_and_bad_names_are_refused() {
let mixed = "2026-10-14,works,1,1,s3://openalex/a.parquet\n\
2027-01-13,works,1,1,s3://openalex/b.parquet\n";
assert!(parse_manifest(mixed).is_err());
let bad = "2026-10-14,Works;drop,1,1,s3://openalex/a.parquet\n";
assert!(parse_manifest(bad).is_err());
assert!(parse_manifest("nothing here\n").is_err());
}
#[test]
fn entity_names_become_table_names() {
assert_eq!(table_name("institution-types"), "institution_types");
assert_eq!(table_name("works"), "works");
}
#[test]
fn the_import_reads_exactly_the_listed_files() {
let release = parse_manifest(MANIFEST_OUTPUT).unwrap();
let limits = Limits {
threads: 8,
memory_limit: "30GB".into(),
};
let sql = import_sql(
&limits,
"CREATE SECRET hazine_data (TYPE s3);",
"openalex_2026_10_14",
&release.entities[1],
);
for part in [
"SET threads = 8;",
"SET memory_limit = '30GB';",
"SET preserve_insertion_order = false;",
"CREATE SECRET hazine_data (TYPE s3);",
"CREATE SECRET openalex (TYPE s3, SCOPE 's3://openalex', REGION 'us-east-1');",
"CREATE SCHEMA IF NOT EXISTS openalex_2026_10_14;",
"DROP TABLE IF EXISTS openalex_2026_10_14.works;",
"CREATE TABLE openalex_2026_10_14.works AS FROM read_parquet([",
"'s3://openalex/data/parquet/works/updated_date=2016-06-24/part_0000.parquet',",
"union_by_name = true, hive_partitioning = false);",
"SELECT count(*) FROM openalex_2026_10_14.works;",
] {
assert!(sql.contains(part), "{part} missing from\n{sql}");
}
assert!(!sql.contains("*.parquet"), "no globs");
}
#[test]
fn catalogs_are_parsed_from_output() {
let (releases, views) = parse_catalog(
"openalex_2026_10_14,works\nopenalex_2026_10_14,authors\n\
openalex_2027_01_13,works\nopenalex,works\nopenalex,release\n\
openalex_scratch,x\n│ junk │\n",
);
assert_eq!(releases[0].0, "openalex_2027_01_13", "newest first");
assert_eq!(releases[1].1, ["authors", "works"]);
assert_eq!(releases.len(), 2, "openalex_scratch is not a release");
assert_eq!(views, ["release", "works"]);
assert_eq!(counts_sql("s", &[]), "");
let counts = counts_sql("s", &["works".into()]);
assert!(counts.starts_with(".mode csv\n"));
assert!(counts.contains("SELECT 'works' AS t, count(*) AS n FROM s.works;"));
}
#[test]
fn views_follow_the_release() {
let sql = views_sql(
"openalex_2027_01_13",
"2027-01-13",
&["authors".into(), "works".into()],
&["concepts".into(), "release".into(), "works".into()],
);
assert!(sql.starts_with("BEGIN;\nCREATE SCHEMA IF NOT EXISTS openalex;\n"));
assert!(sql.contains("DROP VIEW openalex.concepts;"));
assert!(!sql.contains("DROP VIEW openalex.release;"));
assert!(
sql.contains(
"CREATE OR REPLACE VIEW openalex.works AS FROM openalex_2027_01_13.works;"
)
);
assert!(sql.contains("SELECT DATE '2027-01-13' AS release_date"));
assert!(sql.ends_with("COMMIT;\n"));
assert_eq!(release_date("openalex_2027_01_13"), "2027-01-13");
}
}