hazine 0.2.7

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
//! Parquet written in parts: rows serialized through Arrow into files of a
//! bounded number of rows, each handed on (to be uploaded and removed) as
//! soon as it is complete, so a conversion's disk use stays small.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use arrow_json::ReaderBuilder;
use arrow_json::reader::Decoder;
use arrow_schema::Schema;
use parquet::arrow::ArrowWriter;
use parquet::basic::{Compression, ZstdLevel};
use parquet::file::metadata::KeyValue;
use parquet::file::properties::WriterProperties;
use serde::Serialize;

use crate::Error;

/// A finished Parquet part.
pub struct Part {
    pub index: usize,
    pub path: PathBuf,
    pub rows: u64,
}

/// How parts are cut.
pub(crate) struct Layout {
    /// Rows per row group, and the most passed to one [`Parts::write`].
    pub batch: usize,
    /// Rows per part (a multiple of `batch` keeps parts exact).
    pub part_rows: u64,
    /// `key=value` metadata in each file, besides `created_by_hazine`.
    pub metadata: Vec<(String, String)>,
}

/// The part being written.
struct Open {
    index: usize,
    path: PathBuf,
    writer: ArrowWriter<std::fs::File>,
    rows: u64,
}

/// Writes rows into `dir/part-00000.parquet`, `part-00001.parquet`, …,
/// handing each finished part to `on_part`. Rows must match `schema`
/// exactly: a field the schema lacks is an error (strict mode), so that new
/// fields in a source are noticed rather than lost.
pub(crate) struct Parts<'a, F> {
    dir: &'a Path,
    schema: Arc<Schema>,
    layout: Layout,
    decoder: Decoder,
    current: Option<Open>,
    next: usize,
    on_part: F,
    /// Prefixes errors, e.g. "converting the ORCID archive".
    what: &'static str,
}

impl<'a, F: FnMut(Part) -> Result<(), Error>> Parts<'a, F> {
    pub(crate) fn new(
        dir: &'a Path,
        schema: Schema,
        layout: Layout,
        what: &'static str,
        on_part: F,
    ) -> Result<Self, Error> {
        let schema = Arc::new(schema);
        let decoder = ReaderBuilder::new(schema.clone())
            .with_batch_size(layout.batch)
            .with_strict_mode(true)
            .build_decoder()
            .map_err(|e| failed(what, e))?;
        Ok(Parts {
            dir,
            schema,
            layout,
            decoder,
            current: None,
            next: 0,
            on_part,
            what,
        })
    }

    fn properties(&self) -> Result<WriterProperties, Error> {
        let mut metadata: Vec<KeyValue> = self
            .layout
            .metadata
            .iter()
            .map(|(key, value)| KeyValue::new(key.clone(), value.clone()))
            .collect();
        metadata.push(KeyValue::new(
            "created_by_hazine".into(),
            env!("CARGO_PKG_VERSION").to_string(),
        ));
        Ok(WriterProperties::builder()
            .set_compression(Compression::ZSTD(
                ZstdLevel::try_new(3).map_err(|e| failed(self.what, e))?,
            ))
            .set_max_row_group_row_count(Some(self.layout.batch))
            .set_key_value_metadata(Some(metadata))
            .build())
    }

    /// Write at most `batch` rows.
    pub(crate) fn write<R: Serialize>(&mut self, rows: &[R]) -> Result<(), Error> {
        let what = self.what;
        self.decoder.serialize(rows).map_err(|e| failed(what, e))?;
        let Some(batch) = self.decoder.flush().map_err(|e| failed(what, e))? else {
            return Ok(());
        };
        if self.current.is_none() {
            let index = self.next;
            self.next += 1;
            let path = self.dir.join(format!("part-{index:05}.parquet"));
            let writer = ArrowWriter::try_new(
                std::fs::File::create(&path)?,
                self.schema.clone(),
                Some(self.properties()?),
            )
            .map_err(|e| failed(what, e))?;
            self.current = Some(Open {
                index,
                path,
                writer,
                rows: 0,
            });
        }
        let part = self.current.as_mut().expect("a part is open");
        part.writer.write(&batch).map_err(|e| failed(what, e))?;
        part.rows += batch.num_rows() as u64;
        if part.rows >= self.layout.part_rows {
            self.finish()?;
        }
        Ok(())
    }

    /// Close the open part, if any, and hand it on.
    pub(crate) fn finish(&mut self) -> Result<(), Error> {
        if let Some(part) = self.current.take() {
            part.writer.close().map_err(|e| failed(self.what, e))?;
            (self.on_part)(Part {
                index: part.index,
                path: part.path,
                rows: part.rows,
            })?;
        }
        Ok(())
    }
}

fn failed(what: &str, error: impl std::fmt::Display) -> Error {
    Error::Import(format!("{what}: {error}"))
}