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        "sort",
132        lua.create_function(
133            |lua,
134             (path, by, out, descending, plan): (
135                String,
136                String,
137                String,
138                Option<bool>,
139                Option<mlua::Table>,
140            )| {
141                let mut settings = Plan::new();
142                if let Some(options) = plan {
143                    for pair in options.pairs::<String, mlua::Value>() {
144                        let (name, value) =
145                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
146                        settings
147                            .set(&name, &value_to_string(&value))
148                            .map_err(runtime_error)?;
149                    }
150                }
151                let bytes = crate::sort::sort_file(
152                    Path::new(&path),
153                    &by,
154                    descending.unwrap_or(false),
155                    Path::new(&out),
156                    &settings,
157                )
158                .map_err(runtime_error)?;
159                lua.to_value(&serde_json::json!({
160                    "file": path,
161                    "out": out,
162                    "bytes": bytes,
163                }))
164            },
165        )?,
166    )?;
167
168    api.set(
169        "list",
170        lua.create_function(|lua, (directory,): (String,)| {
171            let mut names: Vec<String> = std::fs::read_dir(&directory)
172                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
173                .filter_map(|entry| entry.ok())
174                .map(|entry| entry.file_name().to_string_lossy().to_string())
175                .collect();
176            names.sort();
177            lua.to_value(&names)
178        })?,
179    )?;
180
181    api.set(
182        "project",
183        lua.create_function(|lua, (path, out, columns): (String, String, Vec<String>)| {
184            crate::rows::convert(
185                Path::new(&path),
186                Path::new(&out),
187                crate::rows::ConvertFormat::Parquet,
188                Some(&columns),
189            )
190            .map_err(runtime_error)?;
191            let bytes = std::fs::metadata(&out).map(|meta| meta.len()).unwrap_or(0);
192            lua.to_value(&serde_json::json!({
193                "file": path,
194                "out": out,
195                "bytes": bytes,
196                "columns": columns,
197            }))
198        })?,
199    )?;
200
201    api.set(
202        "lookup_cost",
203        lua.create_function(|lua, (path,): (String,)| {
204            let facts = meta::file_facts(Path::new(&path)).map_err(runtime_error)?;
205            let value = serde_json::json!({
206                "file": facts.path,
207                "size_bytes": facts.size_bytes,
208                "rows": facts.rows,
209                "row_groups": facts.row_groups,
210                "footer_bytes": facts.footer_bytes,
211                "metadata_bytes": facts.metadata_bytes,
212                "column_bytes": facts.column_bytes,
213                "row_group_bytes": facts.row_group_bytes,
214                "lookup_reads_typical": facts.lookup_reads_typical,
215                "lookup_reads_worst": facts.lookup_reads_worst,
216                "rows_per_group": facts.row_group_rows,
217            });
218            lua.to_value(&value)
219        })?,
220    )?;
221
222    api.set(
223        "options",
224        lua.create_function(|lua, ()| {
225            let value: Vec<Json> = crate::plan::known_options()
226                .into_iter()
227                .map(
228                    |(name, supported)| serde_json::json!({ "name": name, "supported": supported }),
229                )
230                .collect();
231            lua.to_value(&value)
232        })?,
233    )?;
234
235    lua.globals().set("pqt", api)?;
236    Ok(())
237}
238
239/// Our error, as a Lua one.
240fn runtime_error(error: anyhow::Error) -> mlua::Error {
241    mlua::Error::RuntimeError(error.to_string())
242}
243
244/// A plan's value, as the text the plan takes.
245fn value_to_string(value: &mlua::Value) -> String {
246    match value {
247        mlua::Value::String(text) => match text.to_str() {
248            Ok(text) => text.to_string(),
249            Err(_) => String::new(),
250        },
251        mlua::Value::Boolean(on) => on.to_string(),
252        mlua::Value::Integer(number) => number.to_string(),
253        mlua::Value::Number(number) => number.to_string(),
254        other => format!("{other:?}"),
255    }
256}