parquet-cli 0.1.7

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();
    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 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(
        "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 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:?}"),
    }
}