hazine 0.2.9

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! `hazine openalex`: import the OpenAlex snapshot into the lake, and point
//! a stable `openalex` schema at the newest import.
//!
//! OpenAlex publishes its snapshot as Parquet in the public bucket
//! `s3://openalex/data/parquet/`, once a quarter, replacing the previous
//! release. `import` copies the current release, exactly the files its
//! manifest lists, into a schema named after the release date
//! (`openalex_2026_10_14`), one table per entity. `setup` creates views in
//! the `openalex` schema on the tables of the newest (or a chosen) release.
//!
//! Both run on the server as root, like `hazine setup`, and run DuckDB as
//! the service account on the lake, with the settings `hazine setup` wrote.

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::{Limits, data_secret};

/// The manifest of the current Parquet release.
const MANIFEST: &str = "https://openalex.s3.amazonaws.com/data/parquet/manifest.json";

/// The schema with views on the tables of the release in use.
pub const VIEW_SCHEMA: &str = "openalex";

/// The prefix of the schemas holding one release each.
const RELEASE_PREFIX: &str = "openalex_";

/// One OpenAlex release, as its manifest describes it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Release {
    /// `2026-10-14`
    pub date: String,
    /// Smallest first.
    pub entities: Vec<Entity>,
}

/// One entity of a release: a table's worth of Parquet files.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entity {
    /// As OpenAlex names it, e.g. `institution-types`.
    pub name: String,
    pub records: u64,
    pub bytes: u64,
    pub files: Vec<String>,
}

impl Release {
    /// The schema this release is imported into, e.g. `openalex_2026_10_14`.
    pub fn schema(&self) -> String {
        format!("{RELEASE_PREFIX}{}", self.date.replace('-', "_"))
    }

    /// Records and bytes over all entities.
    pub fn totals(&self) -> (u64, u64) {
        self.entities
            .iter()
            .fold((0, 0), |(r, b), e| (r + e.records, b + e.bytes))
    }
}

/// The table an entity becomes: `institution-types` is `institution_types`.
pub fn table_name(entity: &str) -> String {
    entity.replace('-', "_")
}

/// The release in the manifest, from the lines of [`manifest_sql`]'s output:
/// `date,entity,records,bytes,url`. Other output lines are ignored.
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 })
}

/// `YYYY-MM-DD`.
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(),
        })
}

/// Lowercase letters and `-`, like `institution-types`.
fn is_entity(value: &str) -> bool {
    !value.is_empty() && value.chars().all(|c| c.is_ascii_lowercase() || c == '-')
}

/// SQL that prints the manifest as `date,entity,records,bytes,url` lines.
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"
    )
}

/// SQL that (re)creates one entity's table from exactly its files, and
/// prints its row count.
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,
    )
}

/// SQL that prints `table,rows` for each table in `schema`.
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")
}

/// SQL that prints `schema,table` for every table in a release schema, and
/// `openalex,view` for every view in [`VIEW_SCHEMA`].
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"
    )
}

/// The release schemas in the catalog, newest first, with their tables; and
/// the views in [`VIEW_SCHEMA`].
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)
}

/// SQL that points the views in [`VIEW_SCHEMA`] at `tables` in `schema`, in
/// one transaction: views for tables the release lacks are dropped.
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
}

/// The release the manifest lists now.
fn current_release(runner: &Runner) -> Result<Release, Error> {
    parse_manifest(&runner.run(false, &manifest_sql())?)
}

/// What `hazine openalex import` was asked to do.
#[derive(Debug, Clone, Default)]
pub struct ImportOptions {
    /// Only these entities (OpenAlex names, e.g. `works`); all without.
    pub entities: Vec<String>,
    pub threads: Option<usize>,
    pub memory_limit: Option<String>,
    pub dry_run: bool,
}

/// Import the current OpenAlex release into the lake.
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::new(options.threads, options.memory_limit.clone())?;
    let secret = crate::lake::installed_data_secret()?;
    tracing::info!(threads = limits.threads, memory_limit = %limits.memory_limit, "import limits");

    // Tables already complete are kept, so an interrupted import resumes.
    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;
        }
        // The bucket holds one release; a new one replaces its files.
        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 gb(bytes: u64) -> f64 {
    bytes as f64 / 1e9
}

/// What `hazine openalex setup` was asked to do.
#[derive(Debug, Clone, Default)]
pub struct SetupOptions {
    /// The release to use, e.g. `2026-10-14`; the newest imported without.
    pub release: Option<String>,
    pub dry_run: bool,
}

/// Point the views in the `openalex` schema at an imported release.
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(())
}

/// `2026-10-14` from `openalex_2026_10_14`.
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");
    }
}