hazine 0.2.7

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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
//! `hazine orcid`: import the ORCID Public Data File summaries into the lake,
//! and point a stable `orcid` schema at the newest import.
//!
//! ORCID publishes the summaries once a year on figshare, as a tar.gz of one
//! XML record per iD (`ORCID_2026_10_summaries.tar.gz`, about 50 GB; locked
//! records are `<error:error>` stubs). `import` converts the archive to
//! Parquet, one row per entry: the iD, the error code of a stub, the person
//! as commonmeta reads it, and the record's XML unchanged. It stores the
//! original archive and the Parquet parts in the lake's bucket under
//! `sources/orcid/<version>/`, then creates a schema named after the version
//! (`orcid_2026_10`) with the tables `people` (the persons, without the XML)
//! and `release`. `setup` creates views in the `orcid` schema on the tables of
//! the newest (or a chosen) version.
//!
//! Without `--file`, the newest archive in commonmeta's cache is used (root's,
//! and the sudo user's), else the latest on figshare is downloaded into it.
//! The figshare lookup, the download and the XML reader are commonmeta's.

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;

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

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

/// Where in the lake's bucket the original archive and the Parquet parts
/// go, one directory per version.
const SOURCES: &str = "sources/orcid";

/// The tables of a version.
const PEOPLE: &str = "people";
const RELEASE: &str = "release";

/// Records parsed at once, and per Parquet row group.
const BATCH: usize = 10_000;

/// Records per Parquet part: about 1–2 GB with the XML.
const PART_RECORDS: u64 = 1_000_000;

/// Seconds a downloaded archive stays in commonmeta's cache. Long: it is
/// big, and a new one comes once a year.
const CACHE_TTL: u64 = 400 * 24 * 60 * 60;

const LINUX_ONLY: &str = "hazine orcid needs Linux (use --output to convert elsewhere)";

/// An ORCID release, by year and batch: `ORCID_2026_10_summaries.tar.gz` is
/// 2026_10.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Version {
    pub year: u16,
    pub batch: u8,
}

impl Version {
    /// `2026_10` or `2026-10`.
    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())?,
        })
    }

    /// The version of a summaries archive, from its file name.
    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()
    }

    /// `orcid_2026_10`.
    pub fn schema(&self) -> String {
        format!("{RELEASE_PREFIX}{self}")
    }

    /// `ORCID_2026_10_summaries.tar.gz`.
    pub fn filename(&self) -> String {
        format!("ORCID_{self}_summaries.tar.gz")
    }

    /// The directory of the Parquet parts: `ORCID_2026_10_summaries`.
    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)
    }
}

/// A summaries archive on this host.
#[derive(Debug, Clone)]
struct Source {
    version: Version,
    path: PathBuf,
    size: u64,
}

/// The latest release on figshare: its version, download URL and size.
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))
}

/// The newest summaries archive in `dirs`, by version. In-progress
/// downloads (`.part`) don't count.
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)
}

/// The archive to import: `file`; or the newest in a cache; or (with
/// `download`) the latest release on figshare, downloaded into commonmeta's
/// cache.
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)?;
        // A copy of the listed release must be complete. (A truncated one
        // also fails the conversion, at its end.)
        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))
}

/// `source` has the size figshare lists (when it lists one).
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(())
}

/// The bare iD of an entry: `.../000/0000-0002-1825-0097.xml` is
/// `0000-0002-1825-0097`. None for anything else.
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())
}

/// The response code of an `<error:error>` stub; none for a record.
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))
}

/// One Parquet row: an archive entry.
#[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,
    }
}

/// The Arrow schema of a row: commonmeta's person fields between the iD and
/// the 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),
    ])
}

/// What the archive held.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
    /// XML entries: every row.
    pub records: u64,
    /// Records commonmeta read as a person.
    pub people: u64,
    /// `<error:error>` stubs (locked records).
    pub errors: u64,
    /// Records commonmeta could not read (kept, with their XML).
    pub unparsed: u64,
    /// Entries that are not an iD's XML, not converted.
    pub skipped: u64,
}

fn convert_error(error: impl std::fmt::Display) -> Error {
    Error::Import(format!("converting the ORCID archive: {error}"))
}

/// Convert the summaries archive at `tar_gz` to Parquet parts in `dir`,
/// parsing on `threads` threads, and hand each finished part to `on_part`
/// (which may move or delete it). A damaged or truncated archive is an
/// error, not a shorter import.
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 {
            // Read through it: the next entry starts after it.
            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)?;
    }
    // Read to the end of the gzip stream, past tar's end marker, so that its
    // checksum and length are checked.
    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('\'', "''")
}

/// SQL that (re)creates the version's tables from the uploaded parts in one
/// transaction, and prints the row count of `people`.
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),
    )
}

/// SQL that prints `schema,table` for every table in a version schema, and
/// `orcid,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 complete versions in the catalog, newest first: those with their
/// `release` table, which the import creates with the data.
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()
}

/// SQL that points the views in [`VIEW_SCHEMA`] at `version`'s tables.
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
}

/// What `hazine orcid import` was asked to do.
#[derive(Debug, Clone, Default)]
pub struct ImportOptions {
    /// The summaries archive; without, the latest release from the cache,
    /// or downloaded.
    pub file: Option<PathBuf>,
    /// Import again, though this version is imported.
    pub force: bool,
    pub threads: Option<usize>,
    pub memory_limit: Option<String>,
    /// Only write the Parquet parts here; no lake.
    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"
    );
}

/// Import an ORCID summaries archive into the lake. Blocking: call it in
/// `spawn_blocking` (the S3 client needs the Tokio runtime around it).
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}");

    // The Parquet parts, each uploaded and removed as soon as it is done.
    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()
        )));
    }

    // The original archive, once the conversion has read all of it intact;
    // unless it is stored already.
    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(())
}

/// The object at `key` has `size` bytes.
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())
        ))),
    }
}

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

/// Point the views in the `orcid` schema at an imported version.
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));
    }

    /// A tar.gz of `entries` (path, content), as ORCID packs them.
    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;")
        );
    }
}