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    crate::stdlib::register(&lua).map_err(lua_error)?;
23    register(&lua).map_err(lua_error)?;
24    Ok(lua)
25}
26
27/// Run a script, with arguments for it.
28pub fn run_file(path: &Path, args: &[String]) -> Result<()> {
29    let lua = lua()?;
30    let source =
31        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
32    // The arguments of the script, the way a shell script sees them: `arg[0]`
33    // is the script itself.
34    let table = lua.create_table().map_err(lua_error)?;
35    table
36        .set(0, path.display().to_string())
37        .map_err(lua_error)?;
38    for (index, argument) in args.iter().enumerate() {
39        table.set(index + 1, argument.clone()).map_err(lua_error)?;
40    }
41    lua.globals().set("arg", table).map_err(lua_error)?;
42    lua.load(&source)
43        .set_name(path.display().to_string())
44        .exec()
45        .map_err(lua_error)
46}
47
48/// Run every script in a directory, and say which ones passed.
49///
50/// Each script is a test: it fails by raising an error.
51/// What the test run found: how many passed, how many failed, and why.
52pub type TestRun = (usize, usize, Vec<(String, String)>);
53
54pub fn run_tests(directory: &Path) -> Result<TestRun> {
55    let mut scripts: Vec<PathBuf> = std::fs::read_dir(directory)
56        .with_context(|| format!("read {}", directory.display()))?
57        .filter_map(|entry| entry.ok())
58        .map(|entry| entry.path())
59        .filter(|path| {
60            path.extension()
61                .and_then(|extension| extension.to_str())
62                .map(|extension| extension.eq_ignore_ascii_case("luau"))
63                .unwrap_or(false)
64        })
65        .collect();
66    scripts.sort();
67
68    let mut passed = 0;
69    let mut failed = 0;
70    let mut failures = Vec::new();
71    for script in &scripts {
72        let name = script
73            .file_name()
74            .map(|name| name.to_string_lossy().to_string())
75            .unwrap_or_default();
76        match run_file(script, &[]) {
77            Ok(()) => passed += 1,
78            Err(error) => {
79                failed += 1;
80                failures.push((name, error.to_string()));
81            }
82        }
83    }
84    Ok((passed, failed, failures))
85}
86
87/// Run a piece of code.
88pub fn run_string(code: &str) -> Result<()> {
89    let lua = lua()?;
90    lua.load(code).exec().map_err(lua_error)
91}
92
93/// A Lua error, as an error we can pass on.
94fn lua_error(error: mlua::Error) -> anyhow::Error {
95    anyhow!("{error}")
96}
97
98/// Put the tool's API into the Lua state.
99fn register(lua: &Lua) -> mlua::Result<()> {
100    let api = lua.create_table()?;
101
102    api.set(
103        "info",
104        lua.create_function(|lua, (path,): (String,)| {
105            let value = meta::facts(Path::new(&path)).map_err(runtime_error)?;
106            lua.to_value(&value)
107        })?,
108    )?;
109
110    api.set(
111        "schema",
112        lua.create_function(|lua, (path,): (String,)| {
113            let value = meta::schema(Path::new(&path)).map_err(runtime_error)?;
114            lua.to_value(&value)
115        })?,
116    )?;
117
118    api.set(
119        "columns",
120        lua.create_function(|lua, (path, scan): (String, Option<bool>)| {
121            let value =
122                meta::columns(Path::new(&path), scan.unwrap_or(false)).map_err(runtime_error)?;
123            lua.to_value(&value)
124        })?,
125    )?;
126
127    api.set(
128        "advise",
129        lua.create_function(
130            |lua, (path, scan, contrast): (String, Option<bool>, Option<usize>)| {
131                let value =
132                    crate::advise::advise(Path::new(&path), scan.unwrap_or(false), contrast)
133                        .map_err(runtime_error)?;
134                lua.to_value(&value.to_json())
135            },
136        )?,
137    )?;
138
139    api.set(
140        "compare",
141        lua.create_function(|lua, (paths,): (Vec<String>,)| {
142            let paths: Vec<PathBuf> = paths.into_iter().map(PathBuf::from).collect();
143            let value = compare::compare(&paths).map_err(runtime_error)?;
144            lua.to_value(&value.to_json())
145        })?,
146    )?;
147
148    api.set(
149        "bench",
150        lua.create_function(
151            |lua, (path, plan, sweep): (String, Option<mlua::Table>, Option<bool>)| {
152                let mut settings = Plan::new();
153                if let Some(options) = plan {
154                    for pair in options.pairs::<String, mlua::Value>() {
155                        let (name, value) =
156                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
157                        settings
158                            .set(&name, &value_to_string(&value))
159                            .map_err(runtime_error)?;
160                    }
161                }
162                let result =
163                    bench::bench(Path::new(&path), &settings, sweep.unwrap_or(false), None)
164                        .map_err(runtime_error)?;
165                lua.to_value(&result.to_json())
166            },
167        )?,
168    )?;
169
170    api.set(
171        "sort",
172        lua.create_function(
173            |lua,
174             (path, by, out, descending, plan): (
175                String,
176                String,
177                String,
178                Option<bool>,
179                Option<mlua::Table>,
180            )| {
181                let mut settings = Plan::new();
182                if let Some(options) = plan {
183                    for pair in options.pairs::<String, mlua::Value>() {
184                        let (name, value) =
185                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
186                        settings
187                            .set(&name, &value_to_string(&value))
188                            .map_err(runtime_error)?;
189                    }
190                }
191                let bytes = crate::sort::sort_file(
192                    Path::new(&path),
193                    &by,
194                    descending.unwrap_or(false),
195                    Path::new(&out),
196                    &settings,
197                )
198                .map_err(runtime_error)?;
199                lua.to_value(&serde_json::json!({
200                    "file": path,
201                    "out": out,
202                    "bytes": bytes,
203                }))
204            },
205        )?,
206    )?;
207
208    api.set(
209        "prune",
210        lua.create_function(|lua, (path, condition): (String, mlua::Table)| {
211            let json = crate::stdlib::to_json(&mlua::Value::Table(condition))?;
212            let condition = crate::prune::parse(&json).map_err(runtime_error)?;
213            let result =
214                crate::prune::prune(Path::new(&path), &condition).map_err(runtime_error)?;
215            lua.to_value(&result.to_json())
216        })?,
217    )?;
218
219    api.set(
220        "rows",
221        lua.create_function(|lua, (path, size): (String, Option<usize>)| {
222            let size = size.unwrap_or(1024).max(1);
223            let reader = crate::rows::reader(Path::new(&path), size).map_err(runtime_error)?;
224            let state = std::rc::Rc::new(std::cell::RefCell::new(Some(reader)));
225            let next = state.clone();
226            lua.create_function(move |lua, ()| {
227                let mut state = next.borrow_mut();
228                let reader = match state.as_mut() {
229                    Some(reader) => reader,
230                    None => return Ok(mlua::Value::Nil),
231                };
232                match reader.next_batch() {
233                    Some(batch) => {
234                        let rows = batch_to_lua(lua, &batch)?;
235                        Ok(mlua::Value::Table(rows))
236                    }
237                    None => {
238                        *state = None;
239                        Ok(mlua::Value::Nil)
240                    }
241                }
242            })
243        })?,
244    )?;
245
246    api.set(
247        "write",
248        lua.create_function(
249            |lua, (path, rows, plan): (String, mlua::Table, Option<mlua::Table>)| {
250                let mut settings = Plan::new();
251                if let Some(options) = plan {
252                    for pair in options.pairs::<String, mlua::Value>() {
253                        let (name, value) =
254                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
255                        settings
256                            .set(&name, &value_to_string(&value))
257                            .map_err(runtime_error)?;
258                    }
259                }
260                let records = crate::stdlib::to_json(&mlua::Value::Table(rows))?;
261                let batch = crate::rows::batch_from_json(&records).map_err(runtime_error)?;
262                let bytes = crate::rows::write_batch(Path::new(&path), batch, &settings)
263                    .map_err(runtime_error)?;
264                lua.to_value(&serde_json::json!({ "out": path, "bytes": bytes }))
265            },
266        )?,
267    )?;
268
269    api.set(
270        "list",
271        lua.create_function(|lua, (directory,): (String,)| {
272            let mut names: Vec<String> = std::fs::read_dir(&directory)
273                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
274                .filter_map(|entry| entry.ok())
275                .map(|entry| entry.file_name().to_string_lossy().to_string())
276                .collect();
277            names.sort();
278            lua.to_value(&names)
279        })?,
280    )?;
281
282    api.set(
283        "project",
284        lua.create_function(|lua, (path, out, columns): (String, String, Vec<String>)| {
285            crate::rows::convert(
286                Path::new(&path),
287                Path::new(&out),
288                crate::rows::ConvertFormat::Parquet,
289                Some(&columns),
290            )
291            .map_err(runtime_error)?;
292            let bytes = std::fs::metadata(&out).map(|meta| meta.len()).unwrap_or(0);
293            lua.to_value(&serde_json::json!({
294                "file": path,
295                "out": out,
296                "bytes": bytes,
297                "columns": columns,
298            }))
299        })?,
300    )?;
301
302    api.set(
303        "lookup_cost",
304        lua.create_function(|lua, (path,): (String,)| {
305            let facts = meta::file_facts(Path::new(&path)).map_err(runtime_error)?;
306            let value = serde_json::json!({
307                "file": facts.path,
308                "size_bytes": facts.size_bytes,
309                "rows": facts.rows,
310                "row_groups": facts.row_groups,
311                "footer_bytes": facts.footer_bytes,
312                "metadata_bytes": facts.metadata_bytes,
313                "column_bytes": facts.column_bytes,
314                "row_group_bytes": facts.row_group_bytes,
315                "lookup_reads_typical": facts.lookup_reads_typical,
316                "lookup_reads_worst": facts.lookup_reads_worst,
317                "rows_per_group": facts.row_group_rows,
318            });
319            lua.to_value(&value)
320        })?,
321    )?;
322
323    api.set(
324        "options",
325        lua.create_function(|lua, ()| {
326            let value: Vec<Json> = crate::plan::known_options()
327                .into_iter()
328                .map(
329                    |(name, supported)| serde_json::json!({ "name": name, "supported": supported }),
330                )
331                .collect();
332            lua.to_value(&value)
333        })?,
334    )?;
335
336    lua.globals().set("pqt", api)?;
337    Ok(())
338}
339
340/// Our error, as a Lua one.
341fn runtime_error(error: anyhow::Error) -> mlua::Error {
342    mlua::Error::RuntimeError(error.to_string())
343}
344
345/// A batch of rows, as a Luau table of row tables.
346fn batch_to_lua(lua: &Lua, batch: &arrow_array::RecordBatch) -> Result<mlua::Table, mlua::Error> {
347    let schema = batch.schema();
348    let names: Vec<String> = schema
349        .fields()
350        .iter()
351        .map(|field| field.name().clone())
352        .collect();
353    let rows = lua.create_table()?;
354    for row in 0..batch.num_rows() {
355        let record = lua.create_table()?;
356        for (index, name) in names.iter().enumerate() {
357            let value = crate::value::cell(batch.column(index), row);
358            record.set(name.clone(), lua.to_value(&value)?)?;
359        }
360        rows.set(row + 1, record)?;
361    }
362    Ok(rows)
363}
364
365/// A plan's value, as the text the plan takes.
366fn value_to_string(value: &mlua::Value) -> String {
367    match value {
368        mlua::Value::String(text) => match text.to_str() {
369            Ok(text) => text.to_string(),
370            Err(_) => String::new(),
371        },
372        mlua::Value::Boolean(on) => on.to_string(),
373        mlua::Value::Integer(number) => number.to_string(),
374        mlua::Value::Number(number) => number.to_string(),
375        other => format!("{other:?}"),
376    }
377}