Skip to main content

rudb_cli/
lib.rs

1//! The command line shell.
2//!
3//! Rank 15 in the layer rule. See `xtask/layers.toml` and `spec/18-package-layout.md`.
4//!
5//! The binary is a few lines over this, so that the shell can be driven from a test without
6//! spawning a process and so that `rudb-compat` can drive it as a target the same way it drives the
7//! library. Everything the shell does goes through [`rudb::Database`], which means the shell has no
8//! way to reach anything the embedding API cannot, which is the point: if the prompt can do it, a
9//! program can do it.
10//!
11//! The command line and the dot commands are DuckDB's, down to the single dash long options it
12//! inherits from SQLite. The output modes are DuckDB's too, byte for byte, because the reason
13//! anybody pipes a shell into another program is that they already know what comes out.
14
15#![forbid(unsafe_code)]
16
17pub mod args;
18pub mod format;
19pub mod help;
20pub mod shell;
21
22use std::io::{IsTerminal, Read, Write};
23use std::process::ExitCode;
24
25use rudb::Database;
26
27pub use args::{Action, Command, Options, parse};
28pub use format::{Format, Settings};
29pub use shell::{Shell, Stop};
30
31/// The version, which `-version` prints and which the greeting carries.
32pub const VERSION: &str = env!("CARGO_PKG_VERSION");
33
34/// The whole program, minus the process it runs in.
35///
36/// `out` and `err` are handed in rather than taken from the process so that a test can read what
37/// came out of each without a pipe and without a temporary file.
38pub fn run(arguments: &[String], out: Box<dyn Write>, err: Box<dyn Write>) -> ExitCode {
39    let mut err = err;
40    match parse(arguments) {
41        Action::Version => {
42            let mut out = out;
43            let _ = writeln!(out, "rudb {VERSION}");
44            ExitCode::SUCCESS
45        }
46        Action::Help => {
47            let mut out = out;
48            let _ = write!(out, "{}", help::USAGE);
49            ExitCode::SUCCESS
50        }
51        Action::Config => {
52            let mut out = out;
53            print_config(&mut out);
54            ExitCode::SUCCESS
55        }
56        Action::Wrong(why) => {
57            let _ = writeln!(err, "rudb: {why}");
58            let _ = writeln!(err, "rudb: try `rudb -help`");
59            ExitCode::FAILURE
60        }
61        Action::Run(options) => {
62            // The library decides what a database name means, here and behind `.open`, so there is
63            // one rule about it rather than a copy of the rule in the shell.
64            let database = match Database::open(&options.database) {
65                Ok(database) => database,
66                Err(problem) => {
67                    let _ = writeln!(err, "rudb: {}", problem.message());
68                    return ExitCode::FAILURE;
69                }
70            };
71            let mut shell = Shell::new(&options, database, out, err);
72            let mut stop = shell.run_commands(&options.commands);
73            if stop == Stop::Done && !options.stop_after_commands {
74                stop = read_input(&mut shell, &options);
75            }
76            let _ = stop;
77            if shell.failed() { ExitCode::FAILURE } else { ExitCode::SUCCESS }
78        }
79    }
80}
81
82/// Reads whatever is on standard input, with a prompt if that is a terminal.
83///
84/// There is no line editing, so no history, no arrow keys and no completion. That wants a
85/// dependency and the dependency budget in `spec/18-package-layout.md` is a decision to make on
86/// purpose rather than in passing, so it is a separate change. Everything else about the prompt
87/// works, including multi line statements.
88fn read_input(shell: &mut Shell, options: &Options) -> Stop {
89    let stdin = std::io::stdin();
90    let interactive = options.interactive.unwrap_or_else(|| stdin.is_terminal());
91    if !interactive {
92        let mut text = String::new();
93        if stdin.lock().read_to_string(&mut text).is_err() {
94            return Stop::Done;
95        }
96        return shell.run_input(&text);
97    }
98    shell.greet();
99    shell.prompt(&stdin)
100}
101
102/// The settled decisions from `spec/00-README.md` that a reader would otherwise have to take on
103/// trust. Printing them is cheap and it makes a bug report say which build it came from.
104fn print_config(out: &mut dyn Write) {
105    let _ = writeln!(out, "version: {VERSION}");
106    let _ = writeln!(out, "vector-size: 1024");
107    let _ = writeln!(out, "row-group-size: 122880");
108    let _ = writeln!(out, "storage-format: native (rudb v1), DuckDB import and export");
109    let _ = writeln!(out, "execution-tiers: interpreted");
110    let _ = writeln!(out, "duckdb-compat-level: 0 (nothing is implemented yet)");
111    let _ = writeln!(out, "target: {}", std::env::consts::ARCH);
112    let _ = writeln!(out, "os: {}", std::env::consts::OS);
113}