use std::collections::BTreeMap;
use rustyline::error::ReadlineError;
use rustyline::DefaultEditor;
use crate::shell::{parse_shell_command, ShellCommand};
use littlegraph_core::{
Error, Graph, Params, QueryResult, Result, Transaction, TransactionErrorKind, Value,
};
#[derive(Debug, PartialEq, Eq)]
enum ReplInput {
Query(String),
Command(ShellCommand),
Exit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TransactionLoop {
Continue,
Exit,
}
trait LineEditor {
fn readline(&mut self, prompt: &str) -> std::result::Result<String, ReadlineError>;
fn add_history_entry(&mut self, line: &str);
}
impl LineEditor for DefaultEditor {
fn readline(&mut self, prompt: &str) -> std::result::Result<String, ReadlineError> {
DefaultEditor::readline(self, prompt)
}
fn add_history_entry(&mut self, line: &str) {
let _ = DefaultEditor::add_history_entry(self, line);
}
}
pub fn is_complete_statement(input: &str) -> bool {
input.trim_end().ends_with(';')
}
pub fn strip_statement_terminator(input: &str) -> &str {
input
.trim_end()
.strip_suffix(';')
.unwrap_or(input.trim_end())
.trim_end()
}
pub fn format_query_result(result: &QueryResult) -> String {
let rows = result
.rows
.iter()
.map(|record| record.values.iter().map(format_value).collect::<Vec<_>>())
.collect::<Vec<_>>();
let mut widths = result
.columns
.iter()
.map(|column| column.len())
.collect::<Vec<_>>();
for row in &rows {
for (index, value) in row.iter().enumerate() {
if let Some(width) = widths.get_mut(index) {
*width = (*width).max(value.len());
}
}
}
let separator = table_separator(&widths);
let mut output = String::new();
output.push_str(&separator);
output.push('\n');
output.push_str(&table_row(&result.columns, &widths));
output.push('\n');
output.push_str(&separator);
for row in &rows {
output.push('\n');
output.push_str(&table_row(row, &widths));
}
output.push('\n');
output.push_str(&separator);
output.push('\n');
output.push_str(&format!("({} rows)", result.rows.len()));
output
}
pub fn format_value(value: &Value) -> String {
match value {
Value::Null => "null".to_string(),
Value::Boolean(value) => value.to_string(),
Value::Integer(value) => value.to_string(),
Value::Float(value) => value.to_string(),
Value::String(value) => serde_json::to_string(value).expect("serialize string"),
Value::List(values) => {
let values = values
.iter()
.map(format_value)
.collect::<Vec<_>>()
.join(", ");
format!("[{values}]")
}
Value::Map(values) => format_map(values),
Value::Node(node) => {
let mut properties = node.properties.clone();
properties.insert("id".to_string(), Value::String(node.id.clone()));
let labels = node
.labels
.iter()
.map(|label| format!(":{label}"))
.collect::<String>();
format!("({labels} {})", format_map(&properties))
}
Value::Relationship(relationship) => {
let mut properties = relationship.properties.clone();
properties.insert("end".to_string(), Value::String(relationship.end.clone()));
properties.insert("id".to_string(), Value::String(relationship.id.clone()));
properties.insert(
"start".to_string(),
Value::String(relationship.start.clone()),
);
format!("[:{} {}]", relationship.r#type, format_map(&properties))
}
Value::Path(path) => {
let mut parts = Vec::new();
for index in 0..path.nodes.len() {
parts.push(format_value(&Value::Node(path.nodes[index].clone())));
if let Some(relationship) = path.relationships.get(index) {
parts.push(format_value(&Value::Relationship(relationship.clone())));
}
}
parts.join("-")
}
_ => format!("{value:?}"),
}
}
pub fn run_repl(graph: &mut Graph) -> Result<()> {
let mut editor = DefaultEditor::new().map_err(|error| Error::Console(error.to_string()))?;
let stdout = std::io::stdout();
let stderr = std::io::stderr();
let mut output = stdout.lock();
let mut errors = stderr.lock();
run_repl_with(graph, &mut editor, &mut output, &mut errors)
}
fn run_repl_with(
graph: &mut Graph,
editor: &mut impl LineEditor,
output: &mut impl std::io::Write,
errors: &mut impl std::io::Write,
) -> Result<()> {
let mut buffer = String::new();
loop {
match read_input(editor, &mut buffer)? {
ReplInput::Query(statement) => {
write_query_result(graph.query(&statement, Params::new()), output, errors)?;
}
ReplInput::Command(ShellCommand::Begin) => match graph.transaction() {
Ok(transaction) => {
if run_transaction(transaction, editor, output, errors)?
== TransactionLoop::Exit
{
return Ok(());
}
}
Err(error) => writeln!(errors, "error: {error}")?,
},
ReplInput::Command(ShellCommand::Commit | ShellCommand::Rollback) => writeln!(
errors,
"error: {}",
Error::Transaction(TransactionErrorKind::NotActive)
)?,
ReplInput::Command(ShellCommand::Exit) | ReplInput::Exit => return Ok(()),
}
}
}
fn run_transaction(
mut transaction: Transaction<'_>,
editor: &mut impl LineEditor,
output: &mut impl std::io::Write,
errors: &mut impl std::io::Write,
) -> Result<TransactionLoop> {
let mut buffer = String::new();
loop {
match read_input(editor, &mut buffer)? {
ReplInput::Query(statement) => {
write_query_result(transaction.query(&statement, Params::new()), output, errors)?
}
ReplInput::Command(ShellCommand::Begin) => writeln!(
errors,
"error: {}",
Error::Transaction(TransactionErrorKind::AlreadyActive)
)?,
ReplInput::Command(ShellCommand::Commit) => {
if let Err(error) = transaction.commit() {
writeln!(errors, "error: {error}")?;
}
return Ok(TransactionLoop::Continue);
}
ReplInput::Command(ShellCommand::Rollback) => {
if let Err(error) = transaction.rollback() {
writeln!(errors, "error: {error}")?;
}
return Ok(TransactionLoop::Continue);
}
ReplInput::Command(ShellCommand::Exit) | ReplInput::Exit => {
return Ok(TransactionLoop::Exit);
}
}
}
}
fn read_input(editor: &mut impl LineEditor, buffer: &mut String) -> Result<ReplInput> {
loop {
let prompt = if buffer.is_empty() {
"littlegraph> "
} else {
" -> "
};
match editor.readline(prompt) {
Ok(line) => {
let trimmed = line.trim();
if buffer.is_empty() {
if let Some(command) = parse_shell_command(trimmed) {
editor.add_history_entry(trimmed);
return Ok(ReplInput::Command(command));
}
if trimmed.is_empty() {
continue;
}
}
if !buffer.is_empty() {
buffer.push('\n');
}
buffer.push_str(&line);
if is_complete_statement(buffer) {
let statement = strip_statement_terminator(buffer).to_owned();
editor.add_history_entry(&statement);
buffer.clear();
return Ok(ReplInput::Query(statement));
}
}
Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => {
return Ok(ReplInput::Exit)
}
Err(error) => return Err(Error::Console(error.to_string())),
}
}
}
fn write_query_result(
result: Result<QueryResult>,
output: &mut impl std::io::Write,
errors: &mut impl std::io::Write,
) -> Result<()> {
match result {
Ok(result) => writeln!(output, "{}", format_query_result(&result))?,
Err(error) => writeln!(errors, "error: {error}")?,
}
Ok(())
}
fn table_separator(widths: &[usize]) -> String {
let mut separator = String::new();
separator.push('+');
for width in widths {
separator.push_str(&"-".repeat(*width + 2));
separator.push('+');
}
separator
}
fn table_row(values: &[String], widths: &[usize]) -> String {
let mut row = String::new();
row.push('|');
for (value, width) in values.iter().zip(widths) {
row.push(' ');
row.push_str(value);
row.push_str(&" ".repeat(width - value.len() + 1));
row.push('|');
}
row
}
fn format_map(values: &BTreeMap<String, Value>) -> String {
let values = values
.iter()
.map(|(key, value)| format!("{key}: {}", format_value(value)))
.collect::<Vec<_>>()
.join(", ");
format!("{{{values}}}")
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::collections::VecDeque;
use rustyline::error::ReadlineError;
use littlegraph_core::{
Graph, Neo4jStorage, NodeValue, Params, QueryResult, Record, RelationshipValue, Value,
};
struct ScriptedEditor {
lines: VecDeque<String>,
history: Vec<String>,
}
impl ScriptedEditor {
fn new(lines: &[&str]) -> Self {
Self {
lines: lines.iter().map(|line| (*line).to_owned()).collect(),
history: Vec::new(),
}
}
}
impl super::LineEditor for ScriptedEditor {
fn readline(&mut self, _prompt: &str) -> std::result::Result<String, ReadlineError> {
self.lines.pop_front().ok_or(ReadlineError::Eof)
}
fn add_history_entry(&mut self, line: &str) {
self.history.push(line.to_owned());
}
}
fn writable_graph() -> (tempfile::TempDir, Graph) {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let graph = Graph::open_neo4j_writable(database).unwrap();
(home, graph)
}
#[test]
fn detects_semicolon_terminated_statements() {
assert!(!super::is_complete_statement(""));
assert!(!super::is_complete_statement("MATCH (n) RETURN n"));
assert!(super::is_complete_statement("MATCH (n) RETURN n;"));
assert!(super::is_complete_statement("MATCH (n)\nRETURN n; "));
}
#[test]
fn strips_trailing_statement_terminator() {
assert_eq!(
super::strip_statement_terminator("MATCH (n) RETURN n; "),
"MATCH (n) RETURN n"
);
assert_eq!(
super::strip_statement_terminator("MATCH (n)\nRETURN n;"),
"MATCH (n)\nRETURN n"
);
}
#[test]
fn recognizes_cypher_shell_transaction_commands_without_semicolons() {
assert_eq!(
super::parse_shell_command(":begin"),
Some(super::ShellCommand::Begin)
);
assert_eq!(
super::parse_shell_command(":commit"),
Some(super::ShellCommand::Commit)
);
assert_eq!(
super::parse_shell_command(":rollback"),
Some(super::ShellCommand::Rollback)
);
assert_eq!(
super::parse_shell_command(":exit"),
Some(super::ShellCommand::Exit)
);
assert_eq!(
super::parse_shell_command(":quit"),
Some(super::ShellCommand::Exit)
);
}
#[test]
fn repl_commits_and_rolls_back_explicit_transactions() {
let (_home, mut graph) = writable_graph();
let mut editor = ScriptedEditor::new(&[
":begin",
"CREATE (:Person {name: 'discarded'});",
":rollback",
":commit",
":begin",
":begin",
"CREATE (:Person {name: 'kept'});",
":commit",
":exit",
]);
let mut output = Vec::new();
let mut errors = Vec::new();
super::run_repl_with(&mut graph, &mut editor, &mut output, &mut errors).unwrap();
let result = graph
.query(
"MATCH (n:Person) RETURN n.name ORDER BY n.name",
Params::new(),
)
.unwrap();
assert_eq!(
result.rows,
vec![Record {
values: vec![Value::String("kept".to_owned())]
}]
);
let errors = String::from_utf8(errors).unwrap();
assert!(errors.contains("no transaction is active"));
assert!(errors.contains("a transaction is already active"));
assert!(editor.history.contains(&":begin".to_owned()));
assert!(editor.history.contains(&":commit".to_owned()));
assert!(editor.history.contains(&":rollback".to_owned()));
assert!(editor.history.contains(&":exit".to_owned()));
}
#[test]
fn exiting_repl_rolls_back_an_open_transaction() {
for lines in [
vec![":begin", "CREATE (:Person {name: 'discarded'});", ":exit"],
vec![":begin", "CREATE (:Person {name: 'discarded'});"],
] {
let (_home, mut graph) = writable_graph();
let mut editor = ScriptedEditor::new(&lines);
let mut output = Vec::new();
let mut errors = Vec::new();
super::run_repl_with(&mut graph, &mut editor, &mut output, &mut errors).unwrap();
let result = graph
.query("MATCH (n:Person) RETURN n.name", Params::new())
.unwrap();
assert!(result.rows.is_empty());
}
}
#[test]
fn formats_query_results_as_table() {
let result = QueryResult {
columns: vec!["name".to_string(), "age".to_string()],
rows: vec![
Record {
values: vec![Value::String("Alice".to_string()), Value::Integer(30)],
},
Record {
values: vec![Value::String("Bob".to_string()), Value::Null],
},
],
};
assert_eq!(
super::format_query_result(&result),
concat!(
"+---------+------+\n",
"| name | age |\n",
"+---------+------+\n",
"| \"Alice\" | 30 |\n",
"| \"Bob\" | null |\n",
"+---------+------+\n",
"(2 rows)"
)
);
}
#[test]
fn formats_graph_values_compactly() {
let node = Value::Node(NodeValue::new(
"alice".to_string(),
vec!["Person".to_string()],
BTreeMap::from([
("active".to_string(), Value::Boolean(true)),
("name".to_string(), Value::String("Alice".to_string())),
]),
));
let relationship = Value::Relationship(RelationshipValue::new(
"knows-1".to_string(),
"alice".to_string(),
"bob".to_string(),
"KNOWS".to_string(),
BTreeMap::from([("since".to_string(), Value::Integer(2020))]),
));
assert_eq!(
super::format_value(&node),
"(:Person {active: true, id: \"alice\", name: \"Alice\"})"
);
assert_eq!(
super::format_value(&relationship),
"[:KNOWS {end: \"bob\", id: \"knows-1\", since: 2020, start: \"alice\"}]"
);
}
}