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, (path, by, out, plan): (String, Vec<String>, String, Option<mlua::Table>)| {
174                let mut settings = Plan::new();
175                if let Some(options) = plan {
176                    for pair in options.pairs::<String, mlua::Value>() {
177                        let (name, value) =
178                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
179                        settings
180                            .set(&name, &value_to_string(&value))
181                            .map_err(runtime_error)?;
182                    }
183                }
184                let keys: Vec<(String, bool)> = by
185                    .iter()
186                    .map(|key| match key.strip_prefix('-') {
187                        Some(name) => (name.to_string(), true),
188                        None => (key.clone(), false),
189                    })
190                    .collect();
191                let bytes =
192                    crate::sort::sort_file(Path::new(&path), &keys, Path::new(&out), &settings)
193                        .map_err(runtime_error)?;
194                lua.to_value(&serde_json::json!({
195                    "file": path,
196                    "out": out,
197                    "bytes": bytes,
198                }))
199            },
200        )?,
201    )?;
202
203    api.set(
204        "prune",
205        lua.create_function(|lua, (path, condition): (String, mlua::Table)| {
206            let json = crate::stdlib::to_json(&mlua::Value::Table(condition))?;
207            let condition = crate::prune::parse(&json).map_err(runtime_error)?;
208            let result =
209                crate::prune::prune(Path::new(&path), &condition).map_err(runtime_error)?;
210            lua.to_value(&result.to_json())
211        })?,
212    )?;
213
214    api.set(
215        "rows",
216        lua.create_function(|lua, (path, size): (String, Option<usize>)| {
217            let size = size.unwrap_or(1024).max(1);
218            let reader = crate::rows::reader(Path::new(&path), size).map_err(runtime_error)?;
219            let state = std::rc::Rc::new(std::cell::RefCell::new(Some(reader)));
220            let next = state.clone();
221            lua.create_function(move |lua, ()| {
222                let mut state = next.borrow_mut();
223                let reader = match state.as_mut() {
224                    Some(reader) => reader,
225                    None => return Ok(mlua::Value::Nil),
226                };
227                match reader.next_batch() {
228                    Some(batch) => {
229                        let rows = batch_to_lua(lua, &batch)?;
230                        Ok(mlua::Value::Table(rows))
231                    }
232                    None => {
233                        *state = None;
234                        Ok(mlua::Value::Nil)
235                    }
236                }
237            })
238        })?,
239    )?;
240
241    api.set(
242        "write",
243        lua.create_function(
244            |lua, (path, rows, plan): (String, mlua::Table, Option<mlua::Table>)| {
245                let mut settings = Plan::new();
246                if let Some(options) = plan {
247                    for pair in options.pairs::<String, mlua::Value>() {
248                        let (name, value) =
249                            pair.map_err(|error| mlua::Error::RuntimeError(error.to_string()))?;
250                        settings
251                            .set(&name, &value_to_string(&value))
252                            .map_err(runtime_error)?;
253                    }
254                }
255                let records = crate::stdlib::to_json(&mlua::Value::Table(rows))?;
256                let batch = crate::rows::batch_from_json(&records).map_err(runtime_error)?;
257                let bytes = crate::rows::write_batch(Path::new(&path), batch, &settings)
258                    .map_err(runtime_error)?;
259                lua.to_value(&serde_json::json!({ "out": path, "bytes": bytes }))
260            },
261        )?,
262    )?;
263
264    api.set(
265        "list",
266        lua.create_function(|lua, (directory,): (String,)| {
267            let mut names: Vec<String> = std::fs::read_dir(&directory)
268                .map_err(|error| mlua::Error::RuntimeError(error.to_string()))?
269                .filter_map(|entry| entry.ok())
270                .map(|entry| entry.file_name().to_string_lossy().to_string())
271                .collect();
272            names.sort();
273            lua.to_value(&names)
274        })?,
275    )?;
276
277    api.set(
278        "project",
279        lua.create_function(|lua, (path, out, columns): (String, String, Vec<String>)| {
280            crate::rows::convert(
281                Path::new(&path),
282                Path::new(&out),
283                crate::rows::ConvertFormat::Parquet,
284                Some(&columns),
285            )
286            .map_err(runtime_error)?;
287            let bytes = std::fs::metadata(&out).map(|meta| meta.len()).unwrap_or(0);
288            lua.to_value(&serde_json::json!({
289                "file": path,
290                "out": out,
291                "bytes": bytes,
292                "columns": columns,
293            }))
294        })?,
295    )?;
296
297    api.set(
298        "lookup_cost",
299        lua.create_function(|lua, (path,): (String,)| {
300            let facts = meta::file_facts(Path::new(&path)).map_err(runtime_error)?;
301            let value = serde_json::json!({
302                "file": facts.path,
303                "size_bytes": facts.size_bytes,
304                "rows": facts.rows,
305                "row_groups": facts.row_groups,
306                "footer_bytes": facts.footer_bytes,
307                "metadata_bytes": facts.metadata_bytes,
308                "column_bytes": facts.column_bytes,
309                "row_group_bytes": facts.row_group_bytes,
310                "lookup_reads_typical": facts.lookup_reads_typical,
311                "lookup_reads_worst": facts.lookup_reads_worst,
312                "rows_per_group": facts.row_group_rows,
313            });
314            lua.to_value(&value)
315        })?,
316    )?;
317
318    api.set(
319        "options",
320        lua.create_function(|lua, ()| {
321            let value: Vec<Json> = crate::plan::known_options()
322                .into_iter()
323                .map(
324                    |(name, supported)| serde_json::json!({ "name": name, "supported": supported }),
325                )
326                .collect();
327            lua.to_value(&value)
328        })?,
329    )?;
330
331    lua.globals().set("pqt", api)?;
332    Ok(())
333}
334
335/// Our error, as a Lua one.
336fn runtime_error(error: anyhow::Error) -> mlua::Error {
337    mlua::Error::RuntimeError(error.to_string())
338}
339
340/// A batch of rows, as a Luau table of row tables.
341fn batch_to_lua(lua: &Lua, batch: &arrow_array::RecordBatch) -> Result<mlua::Table, mlua::Error> {
342    let schema = batch.schema();
343    let names: Vec<String> = schema
344        .fields()
345        .iter()
346        .map(|field| field.name().clone())
347        .collect();
348    let rows = lua.create_table()?;
349    for row in 0..batch.num_rows() {
350        let record = lua.create_table()?;
351        for (index, name) in names.iter().enumerate() {
352            let value = crate::value::cell(batch.column(index), row);
353            record.set(name.clone(), lua.to_value(&value)?)?;
354        }
355        rows.set(row + 1, record)?;
356    }
357    Ok(rows)
358}
359
360/// A plan's value, as the text the plan takes.
361fn value_to_string(value: &mlua::Value) -> String {
362    match value {
363        mlua::Value::String(text) => match text.to_str() {
364            Ok(text) => text.to_string(),
365            Err(_) => String::new(),
366        },
367        mlua::Value::Boolean(on) => on.to_string(),
368        mlua::Value::Integer(number) => number.to_string(),
369        mlua::Value::Number(number) => number.to_string(),
370        other => format!("{other:?}"),
371    }
372}