Skip to main content

parquet_cli/
lua.rs

1//! Luau: the way in for scripts.
2//!
3//! Everything the command line can do is here too, and more: a script can
4//! read a file, measure it, write it again with a plan, and compare two plans
5//! — all in the DuckDB-style vocabulary, because that is the vocabulary the
6//! translation understands.
7
8use std::path::{Path, PathBuf};
9
10use anyhow::{anyhow, Context, Result};
11use mlua::{Lua, LuaSerdeExt};
12use serde_json::Value as Json;
13
14use crate::bench;
15use crate::compare;
16use crate::meta;
17use crate::plan::Plan;
18
19/// A Lua state with the tool's API in it.
20pub fn lua() -> Result<Lua> {
21    let lua = Lua::new();
22    register(&lua).map_err(lua_error)?;
23    Ok(lua)
24}
25
26/// Run a script, with arguments for it.
27pub fn run_file(path: &Path, args: &[String]) -> Result<()> {
28    let lua = lua()?;
29    let source =
30        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
31    // The arguments of the script, the way a shell script sees them: `arg[0]`
32    // is the script itself.
33    let table = lua.create_table().map_err(lua_error)?;
34    table
35        .set(0, path.display().to_string())
36        .map_err(lua_error)?;
37    for (index, argument) in args.iter().enumerate() {
38        table.set(index + 1, argument.clone()).map_err(lua_error)?;
39    }
40    lua.globals().set("arg", table).map_err(lua_error)?;
41    lua.load(&source)
42        .set_name(path.display().to_string())
43        .exec()
44        .map_err(lua_error)
45}
46
47/// Run a piece of code.
48pub fn run_string(code: &str) -> Result<()> {
49    let lua = lua()?;
50    lua.load(code).exec().map_err(lua_error)
51}
52
53/// A Lua error, as an error we can pass on.
54fn lua_error(error: mlua::Error) -> anyhow::Error {
55    anyhow!("{error}")
56}
57
58/// Put the tool's API into the Lua state.
59fn register(lua: &Lua) -> mlua::Result<()> {
60    let api = lua.create_table()?;
61
62    api.set(
63        "info",
64        lua.create_function(|lua, (path,): (String,)| {
65            let value = meta::facts(Path::new(&path)).map_err(runtime_error)?;
66            lua.to_value(&value)
67        })?,
68    )?;
69
70    api.set(
71        "schema",
72        lua.create_function(|lua, (path,): (String,)| {
73            let value = meta::schema(Path::new(&path)).map_err(runtime_error)?;
74            lua.to_value(&value)
75        })?,
76    )?;
77
78    api.set(
79        "columns",
80        lua.create_function(|lua, (path, scan): (String, Option<bool>)| {
81            let value =
82                meta::columns(Path::new(&path), scan.unwrap_or(false)).map_err(runtime_error)?;
83            lua.to_value(&value)
84        })?,
85    )?;
86
87    api.set(
88        "advise",
89        lua.create_function(
90            |lua, (path, scan, contrast): (String, Option<bool>, Option<usize>)| {
91                let value =
92                    crate::advise::advise(Path::new(&path), scan.unwrap_or(false), contrast)
93                        .map_err(runtime_error)?;
94                lua.to_value(&value.to_json())
95            },
96        )?,
97    )?;
98
99    api.set(
100        "compare",
101        lua.create_function(|lua, (paths,): (Vec<String>,)| {
102            let paths: Vec<PathBuf> = paths.into_iter().map(PathBuf::from).collect();
103            let value = compare::compare(&paths).map_err(runtime_error)?;
104            lua.to_value(&value.to_json())
105        })?,
106    )?;
107
108    api.set(
109        "bench",
110        lua.create_function(
111            |lua, (path, plan, sweep): (String, Option<mlua::Table>, Option<bool>)| {
112                let mut settings = Plan::new();
113                if let Some(options) = plan {
114                    for pair in options.pairs::<String, mlua::Value>() {
115                        let (name, value) =
116                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
117                        settings
118                            .set(&name, &value_to_string(&value))
119                            .map_err(runtime_error)?;
120                    }
121                }
122                let result =
123                    bench::bench(Path::new(&path), &settings, sweep.unwrap_or(false), None)
124                        .map_err(runtime_error)?;
125                lua.to_value(&result.to_json())
126            },
127        )?,
128    )?;
129
130    api.set(
131        "lookup_cost",
132        lua.create_function(|lua, (path,): (String,)| {
133            let facts = meta::file_facts(Path::new(&path)).map_err(runtime_error)?;
134            let value = serde_json::json!({
135                "file": facts.path,
136                "size_bytes": facts.size_bytes,
137                "rows": facts.rows,
138                "row_groups": facts.row_groups,
139                "footer_bytes": facts.footer_bytes,
140                "metadata_bytes": facts.metadata_bytes,
141                "column_bytes": facts.column_bytes,
142                "row_group_bytes": facts.row_group_bytes,
143                "lookup_reads_typical": facts.lookup_reads_typical,
144                "lookup_reads_worst": facts.lookup_reads_worst,
145                "rows_per_group": facts.row_group_rows,
146            });
147            lua.to_value(&value)
148        })?,
149    )?;
150
151    api.set(
152        "options",
153        lua.create_function(|lua, ()| {
154            let value: Vec<Json> = crate::plan::known_options()
155                .into_iter()
156                .map(
157                    |(name, supported)| serde_json::json!({ "name": name, "supported": supported }),
158                )
159                .collect();
160            lua.to_value(&value)
161        })?,
162    )?;
163
164    lua.globals().set("pqt", api)?;
165    Ok(())
166}
167
168/// Our error, as a Lua one.
169fn runtime_error(error: anyhow::Error) -> mlua::Error {
170    mlua::Error::RuntimeError(error.to_string())
171}
172
173/// A plan's value, as the text the plan takes.
174fn value_to_string(value: &mlua::Value) -> String {
175    match value {
176        mlua::Value::String(text) => match text.to_str() {
177            Ok(text) => text.to_string(),
178            Err(_) => String::new(),
179        },
180        mlua::Value::Boolean(on) => on.to_string(),
181        mlua::Value::Integer(number) => number.to_string(),
182        mlua::Value::Number(number) => number.to_string(),
183        other => format!("{other:?}"),
184    }
185}