Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-iceberg/src/write.rs

//! Writing Iceberg tables into an embedded warehouse: for tests and benches only (the reader
//! never writes). One snapshot per batch appended, per delete, per rewrite.

use std::path::Path;

use arrow_array::RecordBatch;

use crate::{Error, Result};

/// Append each batch of `batches` to table `table` (`ns.name`, made with the first batch's
/// schema if it is not there) in the warehouse at `dir`, one snapshot each; the snapshot ids
/// made, oldest first. The warehouse is opened and closed inside the call.
pub async fn append(dir: &Path, table: &str, batches: &[RecordBatch]) -> Result<Vec<i64>> {
    let first = batches
        .first()
        .ok_or_else(|| Error::Table(format!("nothing to append to `{table}`")))?;
    let err = |e: skade::SkadeError| Error::Table(format!("writing `{table}`: {e}"));
    let wh = skade::open(dir).await.map_err(err)?;
    let mut t = wh
        .table_or_create(table, &first.schema())
        .await
        .map_err(err)?;
    let mut ids = Vec::with_capacity(batches.len());
    for b in batches {
        t.append(std::slice::from_ref(b)).await.map_err(err)?;
        ids.push(
            t.inner().metadata().current_snapshot_id().ok_or_else(|| {
                Error::Table(format!("`{table}` has no snapshot after an append"))
            })?,
        );
    }
    Ok(ids)
}

/// The table `table` of the warehouse at `dir`, opened for a write (`err` names it).
async fn opened(dir: &Path, table: &str) -> Result<skade::Table> {
    let err = |e: skade::SkadeError| Error::Table(format!("writing `{table}`: {e}"));
    let wh = skade::open(dir).await.map_err(err)?;
    wh.table(table).await.map_err(err)
}

/// The current snapshot id of `t` after a write to `table`.
fn current(t: &skade::Table, table: &str) -> Result<i64> {
    t.inner()
        .metadata()
        .current_snapshot_id()
        .ok_or_else(|| Error::Table(format!("`{table}` has no snapshot after a write")))
}

/// Remove from table `table` every row whose `columns` equal one row of `keys` (an Iceberg
/// equality delete, one snapshot); the snapshot id made.
pub async fn delete_equal(
    dir: &Path,
    table: &str,
    keys: &RecordBatch,
    columns: &[&str],
) -> Result<i64> {
    let err = |e: skade::SkadeError| Error::Table(format!("deleting from `{table}`: {e}"));
    let mut t = opened(dir, table).await?;
    t.delete_equality(keys, columns).await.map_err(err)?;
    current(&t, table)
}

/// Remove rows `positions` of data file `file` of table `table` by their positions (an
/// Iceberg position delete; a deletion vector on skade's v3 tables), one snapshot; the
/// snapshot id made.
pub async fn delete_at(dir: &Path, table: &str, file: &str, positions: &[i64]) -> Result<i64> {
    let err = |e: skade::SkadeError| Error::Table(format!("deleting from `{table}`: {e}"));
    let mut t = opened(dir, table).await?;
    t.delete_positions(file, positions).await.map_err(err)?;
    current(&t, table)
}

/// Replace data files `files` of table `table` by `batches` (a copy-on-write rewrite, one
/// snapshot); the snapshot id made.
pub async fn rewrite(
    dir: &Path,
    table: &str,
    files: &[String],
    batches: &[RecordBatch],
) -> Result<i64> {
    let err = |e: skade::SkadeError| Error::Table(format!("rewriting `{table}`: {e}"));
    let mut t = opened(dir, table).await?;
    t.overwrite(files, batches).await.map_err(err)?;
    current(&t, table)
}

/// The live data files of table `table` now, sorted.
pub async fn data_files(dir: &Path, table: &str) -> Result<Vec<String>> {
    let err = |e: skade::SkadeError| Error::Table(format!("reading `{table}`: {e}"));
    let t = opened(dir, table).await?;
    let mut files = t.live_data_files().await.map_err(err)?;
    files.sort();
    Ok(files)
}