Repository navigation
feat(cli): infoctl query runs read-only SQL against the warehouse #46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ab8d8fe
feat(cli): infoctl query runs read-only SQL against the warehouse
codecapo 1014038
fix(engine): reject COPY TO in tests and name unknown tables as typed
codecapo 7436e92
test(engine): pin the unknown-table message
codecapo 6f1a64e
fix(cli): fail when the output cannot be flushed
codecapo b3017eb
fix(cli): refuse a warehouse directory without a catalog
codecapo 56b6217
docs: add infoctl query to the changelog
codecapo a059e93
Merge remote-tracking branch 'origin/main' into feat/infoctl-query
codecapo 1f72f4e
Merge remote-tracking branch 'origin/main' into feat/infoctl-query
codecapo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,266 @@ | ||
| //! The commands behind `infoctl`. `main.rs` only passes in the arguments and | ||
| //! the output streams, so everything here can be tested in-process. | ||
|
|
||
| use std::io::Write; | ||
| use std::path::PathBuf; | ||
|
|
||
| use datafusion::arrow::util::pretty::pretty_format_batches_with_schema; | ||
| use infostash_engine::{QueryResult, query}; | ||
| use infostash_storage::Warehouse; | ||
|
|
||
| pub const USAGE: &str = "\ | ||
| infoctl: medallion pipelines on open tables | ||
|
|
||
| USAGE: | ||
| infoctl <command> | ||
|
|
||
| COMMANDS: | ||
| init create a new project | ||
| run build Raw, Clean and Ready tables (incremental) | ||
| query run SQL against the lake | ||
|
|
||
| QUERY: | ||
| infoctl query [--warehouse <dir>] [--format table|csv|json] \"<sql>\" | ||
|
|
||
| Name tables <layer>.<table>, as raw.orders or bronze.orders. Statements | ||
| that write are rejected. json prints one object per row. | ||
| --warehouse defaults to .infostash/warehouse. | ||
| "; | ||
|
|
||
| /// Where `infoctl init` puts the warehouse (RFC 0001 draft). | ||
| const DEFAULT_WAREHOUSE: &str = ".infostash/warehouse"; | ||
|
|
||
| /// The catalog file `Warehouse::open_local` keeps in the warehouse directory. | ||
| /// It repeats the private constant in `crates/storage/src/lib.rs` rather than | ||
| /// widening the storage API for one check. | ||
| const CATALOG_FILE: &str = "catalog.db"; | ||
|
|
||
| /// Exit code for a command line infoctl can't parse. | ||
| const USAGE_ERROR: i32 = 2; | ||
|
|
||
| #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| enum Format { | ||
| Table, | ||
| Csv, | ||
| Json, | ||
| } | ||
|
|
||
| #[derive(Debug, PartialEq, Eq)] | ||
| struct Query { | ||
| warehouse: PathBuf, | ||
| format: Format, | ||
| sql: String, | ||
| } | ||
|
|
||
| /// Run `infoctl` with `args` (without the program name) and return the | ||
| /// exit code: 0 on success, 1 when a command fails, 2 for a usage error. | ||
| pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 { | ||
| let code = match args.first().map(String::as_str) { | ||
| Some(c @ ("init" | "run")) => { | ||
| let _ = writeln!(err, "infoctl {c}: not implemented yet"); | ||
| USAGE_ERROR | ||
| } | ||
| Some("query") => match parse_query(&args[1..]) { | ||
| Ok(q) => run_query(&q, out, err), | ||
| Err(msg) => { | ||
| let _ = writeln!(err, "infoctl query: {msg}\n\n{USAGE}"); | ||
| USAGE_ERROR | ||
| } | ||
| }, | ||
| _ => match write!(out, "{USAGE}") { | ||
| Ok(()) => 0, | ||
| Err(e) => output_error(err, &e), | ||
| }, | ||
| }; | ||
| // stdout is buffered, so a reader that closed the pipe can show up here. | ||
| match out.flush() { | ||
| Err(e) if code == 0 => output_error(err, &e), | ||
| _ => code, | ||
| } | ||
| } | ||
|
|
||
| /// Report a failed write to stdout. The output is incomplete, so the | ||
| /// command fails. | ||
| fn output_error(err: &mut dyn Write, e: &std::io::Error) -> i32 { | ||
| let _ = writeln!(err, "infoctl: output error: {e}"); | ||
| 1 | ||
| } | ||
|
|
||
| fn parse_query(args: &[String]) -> Result<Query, String> { | ||
| let mut warehouse = PathBuf::from(DEFAULT_WAREHOUSE); | ||
| let mut format = Format::Table; | ||
| let mut sql = None; | ||
| let mut args = args.iter(); | ||
| while let Some(arg) = args.next() { | ||
| match arg.as_str() { | ||
| "--warehouse" => { | ||
| warehouse = args.next().ok_or("--warehouse needs a directory")?.into(); | ||
| } | ||
| "--format" => { | ||
| format = match args.next().map(String::as_str) { | ||
| Some("table") => Format::Table, | ||
| Some("csv") => Format::Csv, | ||
| Some("json") => Format::Json, | ||
| _ => return Err("--format must be table, csv or json".into()), | ||
| }; | ||
| } | ||
| flag if flag.starts_with("--") => return Err(format!("unknown option {flag}")), | ||
| text if sql.is_none() => sql = Some(text.to_string()), | ||
| _ => return Err("pass the SQL as one quoted argument".into()), | ||
| } | ||
| } | ||
| let sql = sql.ok_or("no SQL given")?; | ||
| Ok(Query { | ||
| warehouse, | ||
| format, | ||
| sql, | ||
| }) | ||
| } | ||
|
|
||
| fn run_query(q: &Query, out: &mut dyn Write, err: &mut dyn Write) -> i32 { | ||
| match execute(q).and_then(|result| print(&result, q.format, out)) { | ||
| Ok(()) => 0, | ||
| Err(e) => { | ||
| let _ = writeln!(err, "infoctl query: {e}"); | ||
| 1 | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn execute(q: &Query) -> Result<QueryResult, String> { | ||
| // Opening a directory without a catalog (or a missing one) would create a | ||
| // catalog there, which a read-only command must not do. | ||
| if !q.warehouse.join(CATALOG_FILE).is_file() { | ||
|
codecapo marked this conversation as resolved.
Resolved
|
||
| return Err(format!( | ||
| "no warehouse at {} (pass --warehouse)", | ||
| q.warehouse.display() | ||
| )); | ||
| } | ||
| let runtime = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?; | ||
| runtime.block_on(async { | ||
| let warehouse = Warehouse::open_local(&q.warehouse) | ||
| .await | ||
| .map_err(|e| e.to_string())?; | ||
| query(&warehouse, &q.sql).await.map_err(|e| e.to_string()) | ||
| }) | ||
| } | ||
|
|
||
| fn print(result: &QueryResult, format: Format, out: &mut dyn Write) -> Result<(), String> { | ||
| match format { | ||
| Format::Table => { | ||
| let table = pretty_format_batches_with_schema(result.schema.clone(), &result.batches) | ||
| .map_err(|e| e.to_string())?; | ||
| writeln!(out, "{table}").map_err(|e| e.to_string()) | ||
| } | ||
| Format::Csv => { | ||
| let mut writer = arrow_csv::WriterBuilder::new().with_header(true).build(out); | ||
| if result.batches.is_empty() { | ||
| let empty = datafusion::arrow::array::RecordBatch::new_empty(result.schema.clone()); | ||
| writer.write(&empty).map_err(|e| e.to_string())?; | ||
| } | ||
| for batch in &result.batches { | ||
| writer.write(batch).map_err(|e| e.to_string())?; | ||
| } | ||
| Ok(()) | ||
| } | ||
| Format::Json => { | ||
| let mut writer = arrow_json::WriterBuilder::new() | ||
| .with_explicit_nulls(true) | ||
| .build::<_, arrow_json::writer::LineDelimited>(out); | ||
| for batch in &result.batches { | ||
| writer.write(batch).map_err(|e| e.to_string())?; | ||
| } | ||
| writer.finish().map_err(|e| e.to_string()) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| fn args(list: &[&str]) -> Vec<String> { | ||
| list.iter().map(|s| s.to_string()).collect() | ||
| } | ||
|
|
||
| #[test] | ||
| fn query_flags_parse() { | ||
| let q = parse_query(&args(&["--format", "csv", "--warehouse", "w", "select 1"])).unwrap(); | ||
| assert_eq!( | ||
| q, | ||
| Query { | ||
| warehouse: "w".into(), | ||
| format: Format::Csv, | ||
| sql: "select 1".into() | ||
| } | ||
| ); | ||
| let q = parse_query(&args(&["select 1"])).unwrap(); | ||
| assert_eq!(q.warehouse, PathBuf::from(DEFAULT_WAREHOUSE)); | ||
| assert_eq!(q.format, Format::Table); | ||
| assert_eq!( | ||
| parse_query(&args(&["--format", "json", "x"])) | ||
| .unwrap() | ||
| .format, | ||
| Format::Json | ||
| ); | ||
| assert_eq!( | ||
| parse_query(&args(&["--format", "table", "x"])) | ||
| .unwrap() | ||
| .format, | ||
| Format::Table | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn bad_query_flags_are_usage_errors() { | ||
| for (bad, msg) in [ | ||
| (&[][..], "no SQL"), | ||
| (&["--warehouse"][..], "needs a directory"), | ||
| (&["--format", "xml", "x"][..], "table, csv or json"), | ||
| (&["--verbose", "x"][..], "unknown option --verbose"), | ||
| (&["select", "1"][..], "one quoted argument"), | ||
| ] { | ||
| let e = parse_query(&args(bad)).unwrap_err(); | ||
| assert!(e.contains(msg), "{bad:?}: {e}"); | ||
| } | ||
| } | ||
|
|
||
| /// Stdout after the reader closed the pipe. With `buffered`, writes | ||
| /// still succeed and only the flush fails. | ||
| struct ClosedPipe { | ||
| buffered: bool, | ||
| } | ||
|
|
||
| impl Write for ClosedPipe { | ||
| fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { | ||
| if self.buffered { | ||
| Ok(buf.len()) | ||
| } else { | ||
| Err(std::io::ErrorKind::BrokenPipe.into()) | ||
| } | ||
| } | ||
|
|
||
| fn flush(&mut self) -> std::io::Result<()> { | ||
| Err(std::io::ErrorKind::BrokenPipe.into()) | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn output_that_cannot_be_delivered_fails_the_command() { | ||
| for buffered in [true, false] { | ||
| let mut err = Vec::new(); | ||
| let code = run(&[], &mut ClosedPipe { buffered }, &mut err); | ||
| assert_eq!(code, 1, "buffered={buffered}"); | ||
| let err = String::from_utf8(err).unwrap(); | ||
| assert!(err.contains("output error"), "{err}"); | ||
| } | ||
| // A command that already failed keeps its own exit code. | ||
| let mut err = Vec::new(); | ||
| let code = run( | ||
| &args(&["query"]), | ||
| &mut ClosedPipe { buffered: true }, | ||
| &mut err, | ||
| ); | ||
| assert_eq!(code, USAGE_ERROR); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,24 +1,7 @@ | ||
| //! `infoctl`: the Infostash command line. | ||
|
|
||
| const USAGE: &str = "\ | ||
| infoctl: medallion pipelines on open tables | ||
|
|
||
| USAGE: | ||
| infoctl <command> | ||
|
|
||
| COMMANDS: | ||
| init create a new project | ||
| run build Raw, Clean and Ready tables (incremental) | ||
| query run SQL against the lake | ||
| "; | ||
|
|
||
| fn main() { | ||
| let cmd = std::env::args().nth(1); | ||
| match cmd.as_deref() { | ||
| Some(c @ ("init" | "run" | "query")) => { | ||
| eprintln!("infoctl {c}: not implemented yet"); | ||
| std::process::exit(2); | ||
| } | ||
| _ => print!("{USAGE}"), | ||
| } | ||
| let args: Vec<String> = std::env::args().skip(1).collect(); | ||
| let code = infostash_cli::run(&args, &mut std::io::stdout(), &mut std::io::stderr()); | ||
| std::process::exit(code); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.