2023-05-22 19:19:35 +00:00
|
|
|
use crate::cli::abstraction::{
|
2023-05-26 10:35:46 +00:00
|
|
|
AuthArguments, DatabaseConnectionArguments, DatabaseSelectionOptionalArguments,
|
2023-05-22 19:19:35 +00:00
|
|
|
};
|
2022-08-06 10:34:43 +00:00
|
|
|
use crate::err::Error;
|
2023-05-22 19:19:35 +00:00
|
|
|
use clap::Args;
|
2022-08-06 10:34:43 +00:00
|
|
|
use rustyline::error::ReadlineError;
|
2023-05-12 19:47:41 +00:00
|
|
|
use rustyline::validate::{ValidationContext, ValidationResult, Validator};
|
|
|
|
use rustyline::{Completer, Editor, Helper, Highlighter, Hinter};
|
2023-05-31 07:36:50 +00:00
|
|
|
use serde::Serialize;
|
|
|
|
use serde_json::ser::PrettyFormatter;
|
2023-01-07 08:32:18 +00:00
|
|
|
use surrealdb::engine::any::connect;
|
2022-12-30 21:27:19 +00:00
|
|
|
use surrealdb::opt::auth::Root;
|
2023-05-12 19:47:41 +00:00
|
|
|
use surrealdb::sql::{self, Statement, Value};
|
2023-06-09 13:45:07 +00:00
|
|
|
use surrealdb::Response;
|
2022-08-06 10:34:43 +00:00
|
|
|
|
2023-05-22 19:19:35 +00:00
|
|
|
#[derive(Args, Debug)]
|
|
|
|
pub struct SqlCommandArguments {
|
|
|
|
#[command(flatten)]
|
|
|
|
conn: DatabaseConnectionArguments,
|
|
|
|
#[command(flatten)]
|
|
|
|
auth: AuthArguments,
|
|
|
|
#[command(flatten)]
|
2023-05-26 10:35:46 +00:00
|
|
|
sel: Option<DatabaseSelectionOptionalArguments>,
|
2023-05-22 19:19:35 +00:00
|
|
|
/// Whether database responses should be pretty printed
|
|
|
|
#[arg(long)]
|
|
|
|
pretty: bool,
|
2023-05-31 07:36:50 +00:00
|
|
|
/// Whether to emit results in JSON
|
|
|
|
#[arg(long)]
|
|
|
|
json: bool,
|
2023-05-22 19:19:35 +00:00
|
|
|
/// Whether omitting semicolon causes a newline
|
|
|
|
#[arg(long)]
|
|
|
|
multi: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn init(
|
|
|
|
SqlCommandArguments {
|
|
|
|
auth: AuthArguments {
|
|
|
|
username,
|
|
|
|
password,
|
|
|
|
},
|
|
|
|
conn: DatabaseConnectionArguments {
|
|
|
|
endpoint,
|
|
|
|
},
|
2023-05-26 10:35:46 +00:00
|
|
|
sel,
|
2023-05-22 19:19:35 +00:00
|
|
|
pretty,
|
2023-05-31 07:36:50 +00:00
|
|
|
json,
|
2023-05-22 19:19:35 +00:00
|
|
|
multi,
|
|
|
|
..
|
|
|
|
}: SqlCommandArguments,
|
|
|
|
) -> Result<(), Error> {
|
2023-03-29 18:16:18 +00:00
|
|
|
// Initialize opentelemetry and logging
|
|
|
|
crate::o11y::builder().with_log_level("warn").init();
|
2023-05-22 19:19:35 +00:00
|
|
|
|
2022-12-30 21:27:19 +00:00
|
|
|
let root = Root {
|
2023-05-22 19:19:35 +00:00
|
|
|
username: &username,
|
|
|
|
password: &password,
|
2022-12-20 10:30:06 +00:00
|
|
|
};
|
2023-06-09 13:45:07 +00:00
|
|
|
// Connect to the database engine
|
2023-07-04 10:25:59 +00:00
|
|
|
#[cfg(feature = "has-storage")]
|
2023-07-03 20:23:18 +00:00
|
|
|
let address = (endpoint, root);
|
2023-07-04 10:25:59 +00:00
|
|
|
#[cfg(not(feature = "has-storage"))]
|
2023-07-03 20:23:18 +00:00
|
|
|
let address = endpoint;
|
|
|
|
let client = connect(address).await?;
|
2023-06-09 13:45:07 +00:00
|
|
|
// Sign in to the server
|
|
|
|
client.signin(root).await?;
|
2022-08-06 10:34:43 +00:00
|
|
|
// Create a new terminal REPL
|
2023-05-12 19:47:41 +00:00
|
|
|
let mut rl = Editor::new().unwrap();
|
|
|
|
// Set custom input validation
|
|
|
|
rl.set_helper(Some(InputValidator {
|
2023-05-22 19:19:35 +00:00
|
|
|
multi,
|
2023-05-12 19:47:41 +00:00
|
|
|
}));
|
2022-08-06 10:34:43 +00:00
|
|
|
// Load the command-line history
|
|
|
|
let _ = rl.load_history("history.txt");
|
2023-07-04 20:58:27 +00:00
|
|
|
// Configure the prompt
|
|
|
|
let mut prompt = "> ".to_owned();
|
|
|
|
// Use namespace / database if specified
|
|
|
|
if let Some(DatabaseSelectionOptionalArguments {
|
2023-05-26 10:35:46 +00:00
|
|
|
namespace,
|
|
|
|
database,
|
|
|
|
}) = sel
|
|
|
|
{
|
2023-07-04 20:58:27 +00:00
|
|
|
let is_not_empty = |s: &&str| !s.is_empty();
|
|
|
|
let namespace = namespace.as_deref().map(str::trim).filter(is_not_empty);
|
|
|
|
let database = database.as_deref().map(str::trim).filter(is_not_empty);
|
|
|
|
match (namespace, database) {
|
2023-05-05 18:12:19 +00:00
|
|
|
(Some(namespace), Some(database)) => {
|
2023-07-04 20:58:27 +00:00
|
|
|
client.use_ns(namespace).use_db(database).await?;
|
|
|
|
prompt = format!("{namespace}/{database}> ");
|
2023-05-05 18:12:19 +00:00
|
|
|
}
|
2023-07-04 20:58:27 +00:00
|
|
|
(Some(namespace), None) => {
|
|
|
|
client.use_ns(namespace).await?;
|
|
|
|
prompt = format!("{namespace}> ");
|
|
|
|
}
|
|
|
|
_ => {}
|
2022-12-30 21:27:19 +00:00
|
|
|
}
|
2023-07-04 20:58:27 +00:00
|
|
|
}
|
|
|
|
// Loop over each command-line input
|
|
|
|
loop {
|
2023-05-12 19:47:41 +00:00
|
|
|
// Prompt the user to input SQL and check the input.
|
|
|
|
let line = match rl.readline(&prompt) {
|
2022-08-06 10:34:43 +00:00
|
|
|
// The user typed a query
|
|
|
|
Ok(line) => {
|
2023-05-12 21:09:07 +00:00
|
|
|
// Filter out all new lines
|
2023-05-12 19:47:41 +00:00
|
|
|
let line = filter_line_continuations(&line);
|
2022-08-06 10:34:43 +00:00
|
|
|
// Add the entry to the history
|
2023-03-25 20:49:00 +00:00
|
|
|
if let Err(e) = rl.add_history_entry(line.as_str()) {
|
|
|
|
eprintln!("{e}");
|
|
|
|
}
|
2023-05-12 19:47:41 +00:00
|
|
|
line
|
|
|
|
}
|
|
|
|
// The user typed CTRL-C or CTRL-D
|
|
|
|
Err(ReadlineError::Interrupted | ReadlineError::Eof) => {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
// There was en error
|
|
|
|
Err(e) => {
|
|
|
|
eprintln!("Error: {e:?}");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
// Complete the request
|
|
|
|
match sql::parse(&line) {
|
|
|
|
Ok(query) => {
|
2023-07-04 20:58:27 +00:00
|
|
|
let mut namespace = None;
|
|
|
|
let mut database = None;
|
|
|
|
let mut vars = Vec::new();
|
|
|
|
// Capture `use` and `set/let` statements from the query
|
2023-05-12 19:47:41 +00:00
|
|
|
for statement in query.iter() {
|
|
|
|
match statement {
|
|
|
|
Statement::Use(stmt) => {
|
2023-07-04 20:58:27 +00:00
|
|
|
if let Some(ns) = &stmt.ns {
|
|
|
|
namespace = Some(ns.clone());
|
2022-12-30 21:27:19 +00:00
|
|
|
}
|
2023-07-04 20:58:27 +00:00
|
|
|
if let Some(db) = &stmt.db {
|
|
|
|
database = Some(db.clone());
|
2023-04-14 18:41:37 +00:00
|
|
|
}
|
2023-05-12 19:47:41 +00:00
|
|
|
}
|
|
|
|
Statement::Set(stmt) => {
|
2023-07-04 20:58:27 +00:00
|
|
|
vars.push((stmt.name.clone(), stmt.what.clone()));
|
2022-12-30 21:27:19 +00:00
|
|
|
}
|
2023-05-12 19:47:41 +00:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
2023-07-04 20:58:27 +00:00
|
|
|
// Extract the namespace and database from the current prompt
|
|
|
|
let (prompt_ns, prompt_db) = split_prompt(&prompt);
|
|
|
|
// The namespace should be set before the database can be set
|
|
|
|
if namespace.is_none() && prompt_ns.is_empty() && database.is_some() {
|
|
|
|
eprintln!(
|
|
|
|
"There was a problem with the database: Specify a namespace to use\n"
|
|
|
|
);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// Run the query provided
|
2023-05-12 19:47:41 +00:00
|
|
|
let res = client.query(query).await;
|
2023-05-31 07:36:50 +00:00
|
|
|
match process(pretty, json, res) {
|
2023-05-12 19:47:41 +00:00
|
|
|
Ok(v) => {
|
|
|
|
println!("{v}\n");
|
2022-12-30 21:27:19 +00:00
|
|
|
}
|
2023-04-14 18:41:37 +00:00
|
|
|
Err(e) => {
|
2023-04-20 18:20:50 +00:00
|
|
|
eprintln!("{e}\n");
|
2023-07-04 20:58:27 +00:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Persist the variables extracted from the query
|
|
|
|
for (key, value) in vars {
|
|
|
|
let _ = client.set(key, value).await;
|
|
|
|
}
|
|
|
|
// Process the last `use` statements, if any
|
|
|
|
if namespace.is_some() || database.is_some() {
|
|
|
|
// Use the namespace provided in the query if any, otherwise use the one in the prompt
|
|
|
|
let namespace = namespace.as_deref().unwrap_or(prompt_ns);
|
|
|
|
// Use the database provided in the query if any, otherwise use the one in the prompt
|
|
|
|
let database = database.as_deref().unwrap_or(prompt_db);
|
|
|
|
// If the database is empty we should only use the namespace
|
|
|
|
if database.is_empty() {
|
|
|
|
if client.use_ns(namespace).await.is_ok() {
|
|
|
|
prompt = format!("{namespace}> ");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Otherwise we should use both the namespace and database
|
|
|
|
else if client.use_ns(namespace).use_db(database).await.is_ok() {
|
|
|
|
prompt = format!("{namespace}/{database}> ");
|
2023-04-14 18:41:37 +00:00
|
|
|
}
|
2022-08-06 10:34:43 +00:00
|
|
|
}
|
|
|
|
}
|
2023-03-25 20:49:00 +00:00
|
|
|
Err(e) => {
|
2023-05-12 19:47:41 +00:00
|
|
|
eprintln!("{e}\n");
|
2022-08-06 10:34:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Save the inputs to the history
|
|
|
|
let _ = rl.save_history("history.txt");
|
|
|
|
// Everything OK
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-05-31 07:36:50 +00:00
|
|
|
fn process(pretty: bool, json: bool, res: surrealdb::Result<Response>) -> Result<String, Error> {
|
2023-04-20 18:20:50 +00:00
|
|
|
// Check query response for an error
|
|
|
|
let mut response = res?;
|
|
|
|
// Get the number of statements the query contained
|
|
|
|
let num_statements = response.num_statements();
|
|
|
|
// Prepare a single value from the query response
|
|
|
|
let value = if num_statements > 1 {
|
|
|
|
let mut output = Vec::<Value>::with_capacity(num_statements);
|
|
|
|
for index in 0..num_statements {
|
2023-05-23 22:10:37 +00:00
|
|
|
output.push(match response.take(index) {
|
|
|
|
Ok(v) => v,
|
|
|
|
Err(e) => e.to_string().into(),
|
|
|
|
});
|
2023-04-20 18:20:50 +00:00
|
|
|
}
|
|
|
|
Value::from(output)
|
|
|
|
} else {
|
|
|
|
response.take(0)?
|
2023-03-30 10:41:44 +00:00
|
|
|
};
|
2023-05-31 07:36:50 +00:00
|
|
|
// Check if we should emit JSON and/or prettify
|
|
|
|
Ok(match (json, pretty) {
|
|
|
|
// Don't prettify the SurrealQL response
|
|
|
|
(false, false) => value.to_string(),
|
|
|
|
// Yes prettify the SurrealQL response
|
|
|
|
(false, true) => format!("{value:#}"),
|
|
|
|
// Don't pretty print the JSON response
|
|
|
|
(true, false) => serde_json::to_string(&value.into_json()).unwrap(),
|
|
|
|
// Yes prettify the JSON response
|
|
|
|
(true, true) => {
|
|
|
|
let mut buf = Vec::new();
|
|
|
|
let mut serializer = serde_json::Serializer::with_formatter(
|
|
|
|
&mut buf,
|
|
|
|
PrettyFormatter::with_indent(b"\t"),
|
|
|
|
);
|
|
|
|
value.into_json().serialize(&mut serializer).unwrap();
|
|
|
|
String::from_utf8(buf).unwrap()
|
|
|
|
}
|
2023-04-14 18:41:37 +00:00
|
|
|
})
|
2022-08-06 10:34:43 +00:00
|
|
|
}
|
2023-05-12 19:47:41 +00:00
|
|
|
|
|
|
|
#[derive(Completer, Helper, Highlighter, Hinter)]
|
|
|
|
struct InputValidator {
|
|
|
|
/// If omitting semicolon causes newline.
|
|
|
|
multi: bool,
|
|
|
|
}
|
|
|
|
|
2023-05-12 21:09:07 +00:00
|
|
|
#[allow(clippy::if_same_then_else)]
|
2023-05-12 19:47:41 +00:00
|
|
|
impl Validator for InputValidator {
|
|
|
|
fn validate(&self, ctx: &mut ValidationContext) -> rustyline::Result<ValidationResult> {
|
|
|
|
use ValidationResult::{Incomplete, Invalid, Valid};
|
2023-05-12 21:09:07 +00:00
|
|
|
// Filter out all new line characters
|
2023-05-12 19:47:41 +00:00
|
|
|
let input = filter_line_continuations(ctx.input());
|
2023-05-12 21:09:07 +00:00
|
|
|
// Trim all whitespace from the user input
|
|
|
|
let input = input.trim();
|
|
|
|
// Process the input to check if we can send the query
|
|
|
|
let result = if self.multi && !input.ends_with(';') {
|
2023-05-23 22:10:37 +00:00
|
|
|
Incomplete // The line doesn't end with a ; and we are in multi mode
|
2023-05-12 21:09:07 +00:00
|
|
|
} else if self.multi && input.is_empty() {
|
|
|
|
Incomplete // The line was empty and we are in multi mode
|
|
|
|
} else if input.ends_with('\\') {
|
|
|
|
Incomplete // The line ends with a backslash
|
|
|
|
} else if let Err(e) = sql::parse(input) {
|
2023-05-12 19:47:41 +00:00
|
|
|
Invalid(Some(format!(" --< {e}")))
|
|
|
|
} else {
|
|
|
|
Valid(None)
|
|
|
|
};
|
2023-05-12 21:09:07 +00:00
|
|
|
// Validation complete
|
2023-05-12 19:47:41 +00:00
|
|
|
Ok(result)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn filter_line_continuations(line: &str) -> String {
|
|
|
|
line.replace("\\\n", "").replace("\\\r\n", "")
|
|
|
|
}
|
2023-07-04 20:58:27 +00:00
|
|
|
|
|
|
|
fn split_prompt(prompt: &str) -> (&str, &str) {
|
|
|
|
let selection = prompt.split_once('>').unwrap().0;
|
|
|
|
selection.split_once('/').unwrap_or((selection, ""))
|
|
|
|
}
|