parquet-cli 0.2.0

A Parquet CLI for AI agents: inspect, measure and convert Parquet files.
Documentation
//! Luau: the way in for scripts.
//!
//! Everything the command line can do is here too, and more: a script can
//! read a file, measure it, write it again with a plan, and compare two plans
//! — all in the DuckDB-style vocabulary, because that is the vocabulary the
//! translation understands.

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

use anyhow::{anyhow, Context, Result};
use mlua::{Lua, LuaSerdeExt};
use serde_json::Value as Json;

use crate::bench;
use crate::compare;
use crate::meta;
use crate::plan::Plan;

/// A Lua state with the tool's API in it.
pub fn lua() -> Result<Lua> {
    let lua = Lua::new();
    crate::stdlib::register(&lua).map_err(lua_error)?;
    register(&lua).map_err(lua_error)?;
    Ok(lua)
}

/// Run a script, with arguments for it.
pub fn run_file(path: &Path, args: &[String]) -> Result<()> {
    let lua = lua()?;
    let source =
        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    // The arguments of the script, the way a shell script sees them: `arg[0]`
    // is the script itself.
    let table = lua.create_table().map_err(lua_error)?;
    table
        .set(0, path.display().to_string())
        .map_err(lua_error)?;
    for (index, argument) in args.iter().enumerate() {
        table.set(index + 1, argument.clone()).map_err(lua_error)?;
    }
    lua.globals().set("arg", table).map_err(lua_error)?;
    lua.load(&source)
        .set_name(path.display().to_string())
        .exec()
        .map_err(lua_error)
}

/// Run every script in a directory, and say which ones passed.
///
/// Each script is a test: it fails by raising an error.
/// What the test run found: how many passed, how many failed, and why.
pub type TestRun = (usize, usize, Vec<(String, String)>);

pub fn run_tests(directory: &Path) -> Result<TestRun> {
    let mut scripts: Vec<PathBuf> = std::fs::read_dir(directory)
        .with_context(|| format!("read {}", directory.display()))?
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.path())
        .filter(|path| {
            path.extension()
                .and_then(|extension| extension.to_str())
                .map(|extension| extension.eq_ignore_ascii_case("luau"))
                .unwrap_or(false)
        })
        .collect();
    scripts.sort();

    let mut passed = 0;
    let mut failed = 0;
    let mut failures = Vec::new();
    for script in &scripts {
        let name = script
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or_default();
        match run_file(script, &[]) {
            Ok(()) => passed += 1,
            Err(error) => {
                failed += 1;
                failures.push((name, error.to_string()));
            }
        }
    }
    Ok((passed, failed, failures))
}

/// Run a piece of code.
pub fn run_string(code: &str) -> Result<()> {
    let lua = lua()?;
    lua.load(code).exec().map_err(lua_error)
}

/// A Lua error, as an error we can pass on.
fn lua_error(error: mlua::Error) -> anyhow::Error {
    anyhow!("{error}")
}

/// Put the tool's API into the Lua state.
fn register(lua: &Lua) -> mlua::Result<()> {
    let api = lua.create_table()?;

    api.set(
        "info",
        lua.create_function(|lua, (path,): (String,)| {
            let value = meta::facts(Path::new(&path)).map_err(runtime_error)?;
            lua.to_value(&value)
        })?,
    )?;

    api.set(
        "schema",
        lua.create_function(|lua, (path,): (String,)| {
            let value = meta::schema(Path::new(&path)).map_err(runtime_error)?;
            lua.to_value(&value)
        })?,
    )?;

    api.set(
        "columns",
        lua.create_function(|lua, (path, scan): (String, Option<bool>)| {
            let value =
                meta::columns(Path::new(&path), scan.unwrap_or(false)).map_err(runtime_error)?;
            lua.to_value(&value)
        })?,
    )?;

    api.set(
        "advise",
        lua.create_function(
            |lua, (path, scan, contrast): (String, Option<bool>, Option<usize>)| {
                let value =
                    crate::advise::advise(Path::new(&path), scan.unwrap_or(false), contrast)
                        .map_err(runtime_error)?;
                lua.to_value(&value.to_json())
            },
        )?,
    )?;

    api.set(
        "compare",
        lua.create_function(|lua, (paths,): (Vec<String>,)| {
            let paths: Vec<PathBuf> = paths.into_iter().map(PathBuf::from).collect();
            let value = compare::compare(&paths).map_err(runtime_error)?;
            lua.to_value(&value.to_json())
        })?,
    )?;

    api.set(
        "bench",
        lua.create_function(
            |lua, (path, plan, sweep): (String, Option<mlua::Table>, Option<bool>)| {
                let mut settings = Plan::new();
                if let Some(options) = plan {
                    for pair in options.pairs::<String, mlua::Value>() {
                        let (name, value) =
                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
                        settings
                            .set(&name, &value_to_string(&value))
                            .map_err(runtime_error)?;
                    }
                }
                let result =
                    bench::bench(Path::new(&path), &settings, sweep.unwrap_or(false), None)
                        .map_err(runtime_error)?;
                lua.to_value(&result.to_json())
            },
        )?,
    )?;

    api.set(
        "sort",
        lua.create_function(
            |lua,
             (path, by, out, descending, plan): (
                String,
                String,
                String,
                Option<bool>,
                Option<mlua::Table>,
            )| {
                let mut settings = Plan::new();
                if let Some(options) = plan {
                    for pair in options.pairs::<String, mlua::Value>() {
                        let (name, value) =
                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
                        settings
                            .set(&name, &value_to_string(&value))
                            .map_err(runtime_error)?;
                    }
                }
                let bytes = crate::sort::sort_file(
                    Path::new(&path),
                    &by,
                    descending.unwrap_or(false),
                    Path::new(&out),
                    &settings,
                )
                .map_err(runtime_error)?;
                lua.to_value(&serde_json::json!({
                    "file": path,
                    "out": out,
                    "bytes": bytes,
                }))
            },
        )?,
    )?;

    api.set(
        "prune",
        lua.create_function(|lua, (path, condition): (String, mlua::Table)| {
            let json = crate::stdlib::to_json(&mlua::Value::Table(condition))?;
            let condition = crate::prune::parse(&json).map_err(runtime_error)?;
            let result =
                crate::prune::prune(Path::new(&path), &condition).map_err(runtime_error)?;
            lua.to_value(&result.to_json())
        })?,
    )?;

    api.set(
        "rows",
        lua.create_function(|lua, (path, size): (String, Option<usize>)| {
            let size = size.unwrap_or(1024).max(1);
            let reader = crate::rows::reader(Path::new(&path), size).map_err(runtime_error)?;
            let state = std::rc::Rc::new(std::cell::RefCell::new(Some(reader)));
            let next = state.clone();
            lua.create_function(move |lua, ()| {
                let mut state = next.borrow_mut();
                let reader = match state.as_mut() {
                    Some(reader) => reader,
                    None => return Ok(mlua::Value::Nil),
                };
                match reader.next_batch() {
                    Some(batch) => {
                        let rows = batch_to_lua(lua, &batch)?;
                        Ok(mlua::Value::Table(rows))
                    }
                    None => {
                        *state = None;
                        Ok(mlua::Value::Nil)
                    }
                }
            })
        })?,
    )?;

    api.set(
        "write",
        lua.create_function(
            |lua, (path, rows, plan): (String, mlua::Table, Option<mlua::Table>)| {
                let mut settings = Plan::new();
                if let Some(options) = plan {
                    for pair in options.pairs::<String, mlua::Value>() {
                        let (name, value) =
                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
                        settings
                            .set(&name, &value_to_string(&value))
                            .map_err(runtime_error)?;
                    }
                }
                let records = crate::stdlib::to_json(&mlua::Value::Table(rows))?;
                let batch = crate::rows::batch_from_json(&records).map_err(runtime_error)?;
                let bytes = crate::rows::write_batch(Path::new(&path), batch, &settings)
                    .map_err(runtime_error)?;
                lua.to_value(&serde_json::json!({ "out": path, "bytes": bytes }))
            },
        )?,
    )?;

    api.set(
        "list",
        lua.create_function(|lua, (directory,): (String,)| {
            let mut names: Vec<String> = std::fs::read_dir(&directory)
                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
                .filter_map(|entry| entry.ok())
                .map(|entry| entry.file_name().to_string_lossy().to_string())
                .collect();
            names.sort();
            lua.to_value(&names)
        })?,
    )?;

    api.set(
        "project",
        lua.create_function(|lua, (path, out, columns): (String, String, Vec<String>)| {
            crate::rows::convert(
                Path::new(&path),
                Path::new(&out),
                crate::rows::ConvertFormat::Parquet,
                Some(&columns),
            )
            .map_err(runtime_error)?;
            let bytes = std::fs::metadata(&out).map(|meta| meta.len()).unwrap_or(0);
            lua.to_value(&serde_json::json!({
                "file": path,
                "out": out,
                "bytes": bytes,
                "columns": columns,
            }))
        })?,
    )?;

    api.set(
        "lookup_cost",
        lua.create_function(|lua, (path,): (String,)| {
            let facts = meta::file_facts(Path::new(&path)).map_err(runtime_error)?;
            let value = serde_json::json!({
                "file": facts.path,
                "size_bytes": facts.size_bytes,
                "rows": facts.rows,
                "row_groups": facts.row_groups,
                "footer_bytes": facts.footer_bytes,
                "metadata_bytes": facts.metadata_bytes,
                "column_bytes": facts.column_bytes,
                "row_group_bytes": facts.row_group_bytes,
                "lookup_reads_typical": facts.lookup_reads_typical,
                "lookup_reads_worst": facts.lookup_reads_worst,
                "rows_per_group": facts.row_group_rows,
            });
            lua.to_value(&value)
        })?,
    )?;

    api.set(
        "options",
        lua.create_function(|lua, ()| {
            let value: Vec<Json> = crate::plan::known_options()
                .into_iter()
                .map(
                    |(name, supported)| serde_json::json!({ "name": name, "supported": supported }),
                )
                .collect();
            lua.to_value(&value)
        })?,
    )?;

    lua.globals().set("pqt", api)?;
    Ok(())
}

/// Our error, as a Lua one.
fn runtime_error(error: anyhow::Error) -> mlua::Error {
    mlua::Error::RuntimeError(error.to_string())
}

/// A batch of rows, as a Luau table of row tables.
fn batch_to_lua(lua: &Lua, batch: &arrow_array::RecordBatch) -> Result<mlua::Table, mlua::Error> {
    let schema = batch.schema();
    let names: Vec<String> = schema
        .fields()
        .iter()
        .map(|field| field.name().clone())
        .collect();
    let rows = lua.create_table()?;
    for row in 0..batch.num_rows() {
        let record = lua.create_table()?;
        for (index, name) in names.iter().enumerate() {
            let value = crate::value::cell(batch.column(index), row);
            record.set(name.clone(), lua.to_value(&value)?)?;
        }
        rows.set(row + 1, record)?;
    }
    Ok(rows)
}

/// A plan's value, as the text the plan takes.
fn value_to_string(value: &mlua::Value) -> String {
    match value {
        mlua::Value::String(text) => match text.to_str() {
            Ok(text) => text.to_string(),
            Err(_) => String::new(),
        },
        mlua::Value::Boolean(on) => on.to_string(),
        mlua::Value::Integer(number) => number.to_string(),
        mlua::Value::Number(number) => number.to_string(),
        other => format!("{other:?}"),
    }
}