use std::fs;
use std::io::{self, Read};
use std::net::{SocketAddr, ToSocketAddrs};
use std::path::PathBuf;
use std::process::ExitCode;
use clap::{Parser, Subcommand};
use littlegraph_bolt::{
BoltAuth, BoltLimits, BoltServer, BoltServerConfig, BoltTlsConfig, CancellationToken,
};
use littlegraph_core::{Error, Graph, Neo4jStorage, Params, Result};
use littlegraph_mcp::{McpAuth, McpLimits, McpServer, McpServerConfig, McpTlsConfig};
use littlegraph_query_api::{
QueryApiAuth, QueryApiLimits, QueryApiServer, QueryApiServerConfig, QueryApiTlsConfig,
};
use crate::shell::{parse_shell_command, ShellCommand};
mod console;
mod shell;
#[derive(Debug, Parser)]
#[command(
name = "littlegraph",
version,
about = "An embedded openCypher graph database"
)]
struct Cli {
#[command(subcommand)]
command: CliCommand,
}
#[derive(Clone, Debug, PartialEq, Eq, Subcommand)]
enum CliCommand {
Repl {
#[arg(value_name = "NEO4J_DATABASE_DIR")]
database_path: PathBuf,
},
Load {
#[arg(value_name = "NEO4J_DATABASE_DIR")]
database_path: PathBuf,
#[arg(value_name = "CYPHER_FILE")]
cypher_path: Option<PathBuf>,
},
#[command(after_help = "At least one of --bolt, --query, or --mcp is required.")]
Serve {
#[arg(value_name = "NEO4J_DATABASE_DIR")]
database_path: PathBuf,
#[arg(
long = "bolt",
value_name = "HOST:PORT",
value_parser = resolve_address,
required_unless_present_any = ["query_addr", "mcp_addr"]
)]
bolt_addr: Option<SocketAddr>,
#[arg(
long = "bolt-auth-file",
value_name = "PATH",
requires = "bolt_addr",
value_parser = parse_bolt_auth_file
)]
bolt_auth_file: Option<Box<PathBuf>>,
#[arg(
long = "query",
value_name = "HOST:PORT",
value_parser = resolve_address,
required_unless_present_any = ["bolt_addr", "mcp_addr"]
)]
query_addr: Option<SocketAddr>,
#[arg(
long = "query-auth-file",
value_name = "PATH",
requires = "query_addr",
value_parser = parse_query_auth_file
)]
query_auth_file: Option<Box<PathBuf>>,
#[arg(
long = "mcp",
value_name = "HOST:PORT",
value_parser = resolve_mcp_address,
required_unless_present_any = ["bolt_addr", "query_addr"]
)]
mcp_addr: Option<McpListenAddress>,
#[arg(
long = "mcp-auth-file",
value_name = "PATH",
requires = "mcp_addr",
value_parser = parse_mcp_auth_file
)]
mcp_auth_file: Option<Box<PathBuf>>,
#[arg(long = "tls-cert", value_name = "CERTFILE")]
tls_cert: Option<PathBuf>,
#[arg(long = "tls-ca", value_name = "CAFILE", requires = "tls_cert")]
tls_ca: Option<PathBuf>,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ScriptItem {
line: usize,
kind: ScriptItemKind,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum ScriptItemKind {
Query(String),
Command(ShellCommand),
}
fn main() -> ExitCode {
match run() {
Ok(code) => code,
Err(error) => {
eprintln!("error: {error}");
ExitCode::FAILURE
}
}
}
fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
let command = Cli::parse().command;
let database_path = match &command {
CliCommand::Repl { database_path } | CliCommand::Load { database_path, .. } => {
database_path
}
CliCommand::Serve { database_path, .. } => database_path,
};
if Neo4jStorage::initialize_if_empty(database_path)? {
eprintln!(
"initialized empty Neo4j store at {}",
database_path.display()
);
}
match command {
CliCommand::Repl { database_path } => {
let mut graph = Graph::open_neo4j_writable(database_path)?;
console::run_repl(&mut graph)?;
}
CliCommand::Load {
database_path,
cypher_path,
} => {
let mut graph = Graph::open_neo4j_writable(database_path)?;
let (source, input) = read_cypher(cypher_path.as_ref())?;
execute_cypher_script(&mut graph, &source, &input)?;
}
CliCommand::Serve {
database_path,
bolt_addr,
bolt_auth_file,
query_addr,
query_auth_file,
mcp_addr,
mcp_auth_file,
tls_cert,
tls_ca,
} => run_server(
database_path,
ServeOptions {
bolt_addr,
bolt_auth_file,
query_addr,
query_auth_file,
mcp_addr,
mcp_auth_file,
tls_cert,
tls_ca,
},
)?,
}
Ok(ExitCode::SUCCESS)
}
fn resolve_address(address: &str) -> std::result::Result<SocketAddr, String> {
address
.to_socket_addrs()
.map_err(|error| format!("failed to resolve {address}: {error}"))?
.next()
.ok_or_else(|| format!("address {address} resolved to no socket addresses"))
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct McpListenAddress {
socket_addr: SocketAddr,
allowed_host: String,
}
fn resolve_mcp_address(address: &str) -> std::result::Result<McpListenAddress, String> {
Ok(McpListenAddress {
socket_addr: resolve_address(address)?,
allowed_host: address.to_owned(),
})
}
fn parse_bolt_auth_file(path: &str) -> std::result::Result<Box<PathBuf>, String> {
Ok(Box::new(PathBuf::from(path)))
}
fn parse_query_auth_file(path: &str) -> std::result::Result<Box<PathBuf>, String> {
Ok(Box::new(PathBuf::from(path)))
}
fn parse_mcp_auth_file(path: &str) -> std::result::Result<Box<PathBuf>, String> {
Ok(Box::new(PathBuf::from(path)))
}
struct ServeOptions {
bolt_addr: Option<SocketAddr>,
bolt_auth_file: Option<Box<PathBuf>>,
query_addr: Option<SocketAddr>,
query_auth_file: Option<Box<PathBuf>>,
mcp_addr: Option<McpListenAddress>,
mcp_auth_file: Option<Box<PathBuf>>,
tls_cert: Option<PathBuf>,
tls_ca: Option<PathBuf>,
}
fn run_server(
database_path: PathBuf,
options: ServeOptions,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let ServeOptions {
bolt_addr,
bolt_auth_file,
query_addr,
query_auth_file,
mcp_addr,
mcp_auth_file,
tls_cert,
tls_ca,
} = options;
if bolt_addr.is_none() && query_addr.is_none() && mcp_addr.is_none() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"serve requires at least one of --bolt, --query, or --mcp",
)
.into());
}
let bolt_auth = bolt_auth_file
.map(|path| BoltAuth::from_file(path.as_ref()))
.transpose()?;
let query_auth = query_auth_file
.map(|path| QueryApiAuth::from_file(path.as_ref()))
.transpose()?;
let mcp_auth = mcp_auth_file
.map(|path| McpAuth::from_file(path.as_ref()))
.transpose()?;
let tls_enabled = tls_cert.is_some();
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
runtime.block_on(async move {
let bolt_server = match bolt_addr {
Some(listen_addr) => Some(
BoltServer::bind(BoltServerConfig {
listen_addr,
advertised_addr: listen_addr,
database_path: database_path.clone(),
auth: bolt_auth,
tls: tls_cert.clone().map(|certificate_file| BoltTlsConfig {
certificate_file,
ca_file: tls_ca.clone(),
}),
limits: BoltLimits::default(),
})
.await?,
),
None => None,
};
let query_server = match query_addr {
Some(listen_addr) => Some(
QueryApiServer::bind(QueryApiServerConfig {
listen_addr,
database_path: database_path.clone(),
auth: query_auth,
tls: tls_cert.clone().map(|certificate_file| QueryApiTlsConfig {
certificate_file,
ca_file: tls_ca.clone(),
}),
limits: QueryApiLimits::default(),
})
.await?,
),
None => None,
};
let mcp_server = match mcp_addr {
Some(address) => Some(
McpServer::bind(McpServerConfig {
listen_addr: address.socket_addr,
allowed_hosts: vec![address.allowed_host],
database_path,
auth: mcp_auth,
tls: tls_cert.map(|certificate_file| McpTlsConfig {
certificate_file,
ca_file: tls_ca,
}),
limits: McpLimits::default(),
})
.await?,
),
None => None,
};
let shutdown = CancellationToken::new();
let signal_shutdown = shutdown.clone();
let (signal_ready, signal_ready_receiver) = tokio::sync::oneshot::channel();
let signal_task = tokio::spawn(async move {
wait_for_shutdown_signal(signal_ready).await;
signal_shutdown.cancel();
});
signal_ready_receiver
.await
.map_err(|_| io::Error::other("shutdown signal handler failed to start"))?;
if let Some(server) = &bolt_server {
eprintln!(
"Bolt server listening on {}{}",
server.local_addr()?,
if tls_enabled { " with TLS" } else { "" }
);
}
if let Some(server) = &query_server {
eprintln!(
"Query API server listening on {}{}",
server.local_addr()?,
if tls_enabled { " with TLS" } else { "" }
);
}
if let Some(server) = &mcp_server {
eprintln!(
"MCP server listening on {}{}",
server.local_addr()?,
if tls_enabled { " with TLS" } else { "" }
);
}
let mut servers = tokio::task::JoinSet::new();
if let Some(server) = bolt_server {
let server_shutdown = shutdown.clone();
servers.spawn(async move {
server
.serve(server_shutdown)
.await
.map_err(|error| error.to_string())
});
}
if let Some(server) = query_server {
let server_shutdown = shutdown.clone();
servers.spawn(async move {
server
.serve(server_shutdown)
.await
.map_err(|error| error.to_string())
});
}
if let Some(server) = mcp_server {
let server_shutdown = shutdown.clone();
servers.spawn(async move {
server
.serve(server_shutdown)
.await
.map_err(|error| error.to_string())
});
}
let first = servers
.join_next()
.await
.ok_or_else(|| io::Error::other("serve has no configured listener"))?;
let shutdown_requested = shutdown.is_cancelled();
shutdown.cancel();
let mut result = match first {
Ok(Ok(())) if !shutdown_requested => Err("server stopped unexpectedly".into()),
Ok(result) => result,
Err(error) => Err(format!("server task failed: {error}")),
};
while let Some(next) = servers.join_next().await {
match next {
Ok(Err(error)) if result.is_ok() => result = Err(error),
Err(error) if result.is_ok() => {
result = Err(format!("server task failed: {error}"))
}
_ => {}
}
}
signal_task.abort();
result.map_err(|error| Box::new(io::Error::other(error)) as Box<dyn std::error::Error>)
})?;
Ok(())
}
async fn wait_for_shutdown_signal(ready: tokio::sync::oneshot::Sender<()>) {
#[cfg(unix)]
{
let mut interrupt =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()).ok();
let mut terminate =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).ok();
let _ = ready.send(());
tokio::select! {
_ = async {
if let Some(signal) = &mut interrupt {
signal.recv().await;
} else {
std::future::pending::<()>().await;
}
} => {}
_ = async {
if let Some(signal) = &mut terminate {
signal.recv().await;
} else {
std::future::pending::<()>().await;
}
} => {}
}
}
#[cfg(not(unix))]
{
let _ = ready.send(());
let _ = tokio::signal::ctrl_c().await;
}
}
fn read_cypher(path: Option<&PathBuf>) -> Result<(String, String)> {
match path {
Some(path) if path.as_os_str() != "-" => {
Ok((path.display().to_string(), fs::read_to_string(path)?))
}
_ => {
let mut input = String::new();
io::stdin().lock().read_to_string(&mut input)?;
Ok(("stdin".to_owned(), input))
}
}
}
fn execute_cypher_script(graph: &mut Graph, source: &str, input: &str) -> Result<()> {
let items = parse_cypher_script(input);
let mut transaction = graph.transaction().map_err(|error| {
Error::Execution(format!(
"{source}: failed to start script transaction: {error}"
))
})?;
let mut query_number = 0;
for item in &items {
match &item.kind {
ScriptItemKind::Query(query) => {
query_number += 1;
transaction
.query(query, Params::new())
.map_err(|error| script_query_error(source, query_number, item.line, error))?;
}
ScriptItemKind::Command(
ShellCommand::Begin | ShellCommand::Commit | ShellCommand::Rollback,
) => {
return Err(Error::Execution(format!(
"{source} line {}: transaction commands are not supported by load; the entire script runs in one transaction",
item.line
)));
}
ScriptItemKind::Command(ShellCommand::Exit) => {
return Err(Error::Execution(format!(
"{source} line {}: exit commands are not supported in scripts",
item.line
)));
}
}
}
transaction
.commit()
.map_err(|error| Error::Execution(format!("{source}: failed to commit script: {error}")))
}
fn script_query_error(source: &str, number: usize, line: usize, error: Error) -> Error {
Error::Execution(format!(
"{source} statement {number} (line {line}): {error}"
))
}
fn parse_cypher_script(input: &str) -> Vec<ScriptItem> {
let mut items = Vec::new();
let mut current = String::new();
let mut quote = None;
let mut escaped = false;
let mut block_comment = false;
let mut statement_line = 1;
let mut has_query_content = false;
for (line_index, line) in input.split_inclusive('\n').enumerate() {
let line_number = line_index + 1;
let directive = line.trim_end_matches(['\r', '\n']).trim();
if quote.is_none() && !block_comment && !has_query_content {
if let Some(command) = parse_shell_command(directive) {
current.clear();
items.push(ScriptItem {
line: line_number,
kind: ScriptItemKind::Command(command),
});
statement_line = line_number + 1;
continue;
}
}
let mut line_comment = false;
let mut characters = line.chars().peekable();
while let Some(character) = characters.next() {
if line_comment {
current.push(character);
continue;
}
if block_comment {
current.push(character);
if character == '*' && characters.peek() == Some(&'/') {
current.push(characters.next().expect("peeked block comment terminator"));
block_comment = false;
}
continue;
}
if let Some(delimiter) = quote {
current.push(character);
if escaped {
escaped = false;
} else if character == '\\' {
escaped = true;
} else if character == delimiter {
if characters.peek() == Some(&delimiter) {
current.push(characters.next().expect("peeked escaped quote"));
} else {
quote = None;
}
}
continue;
}
match character {
'\'' | '"' | '`' => {
if !has_query_content {
statement_line = line_number;
has_query_content = true;
}
quote = Some(character);
current.push(character);
}
'/' if characters.peek() == Some(&'/') => {
current.push(character);
current.push(characters.next().expect("peeked line comment marker"));
line_comment = true;
}
'/' if characters.peek() == Some(&'*') => {
current.push(character);
current.push(characters.next().expect("peeked block comment marker"));
block_comment = true;
}
';' => {
if has_query_content {
items.push(ScriptItem {
line: statement_line,
kind: ScriptItemKind::Query(current.trim().to_owned()),
});
}
current.clear();
statement_line = line_number;
has_query_content = false;
}
_ if !character.is_whitespace() => {
if !has_query_content {
statement_line = line_number;
has_query_content = true;
}
current.push(character);
}
_ => current.push(character),
}
}
}
if has_query_content {
items.push(ScriptItem {
line: statement_line,
kind: ScriptItemKind::Query(current.trim().to_owned()),
});
}
items
}
#[cfg(test)]
mod tests {
use clap::Parser;
use littlegraph_core::{Graph, Neo4jStorage, Params, Value};
fn cli_args(args: &[&str]) -> std::result::Result<super::CliCommand, String> {
super::Cli::try_parse_from(args.iter().copied())
.map(|cli| cli.command)
.map_err(|error| error.to_string())
}
fn query_texts(input: &str) -> Vec<String> {
super::parse_cypher_script(input)
.into_iter()
.filter_map(|item| match item.kind {
super::ScriptItemKind::Query(query) => Some(query),
super::ScriptItemKind::Command(_) => None,
})
.collect()
}
#[test]
fn resolves_repl_database_directory() {
let args = cli_args(&["littlegraph", "repl", "/data/graph"]);
assert_eq!(
args,
Ok(super::CliCommand::Repl {
database_path: std::path::PathBuf::from("/data/graph")
})
);
}
#[test]
fn resolves_load_from_stdin_or_file() {
let stdin = cli_args(&["littlegraph", "load", "/data/graph"]);
assert_eq!(
stdin,
Ok(super::CliCommand::Load {
database_path: std::path::PathBuf::from("/data/graph"),
cypher_path: None,
})
);
let file = cli_args(&["littlegraph", "load", "/data/graph", "fixture.cypher"]);
assert_eq!(
file,
Ok(super::CliCommand::Load {
database_path: std::path::PathBuf::from("/data/graph"),
cypher_path: Some(std::path::PathBuf::from("fixture.cypher")),
})
);
assert_eq!(
cli_args(&["littlegraph", "load", "/data/graph", "-"]),
Ok(super::CliCommand::Load {
database_path: std::path::PathBuf::from("/data/graph"),
cypher_path: Some(std::path::PathBuf::from("-")),
})
);
}
#[test]
fn resolves_serve_with_bolt_before_or_after_the_database() {
let expected = Ok(super::CliCommand::Serve {
database_path: std::path::PathBuf::from("/data/graph"),
bolt_addr: Some("127.0.0.1:7687".parse().unwrap()),
bolt_auth_file: None,
query_addr: None,
query_auth_file: None,
mcp_addr: None,
mcp_auth_file: None,
tls_cert: None,
tls_ca: None,
});
assert_eq!(
cli_args(&[
"littlegraph",
"serve",
"/data/graph",
"--bolt",
"127.0.0.1:7687",
]),
expected
);
assert_eq!(
cli_args(&[
"littlegraph",
"serve",
"--bolt",
"127.0.0.1:7687",
"/data/graph",
]),
expected
);
}
#[test]
fn resolves_bolt_auth_file_path() {
let command = cli_args(&[
"littlegraph",
"serve",
"/data/graph",
"--bolt",
"127.0.0.1:7687",
"--bolt-auth-file",
"auth.txt",
])
.unwrap();
let super::CliCommand::Serve { bolt_auth_file, .. } = command else {
panic!("expected serve command");
};
assert_eq!(
bolt_auth_file,
Some(Box::new(std::path::PathBuf::from("auth.txt")))
);
}
#[test]
fn resolves_serve_tls_files_in_any_order() {
let expected = Ok(super::CliCommand::Serve {
database_path: std::path::PathBuf::from("/data/graph"),
bolt_addr: Some("127.0.0.1:7687".parse().unwrap()),
bolt_auth_file: None,
query_addr: None,
query_auth_file: None,
mcp_addr: None,
mcp_auth_file: None,
tls_cert: Some(std::path::PathBuf::from("server.pem")),
tls_ca: Some(std::path::PathBuf::from("ca.pem")),
});
assert_eq!(
cli_args(&[
"littlegraph",
"serve",
"--tls-ca",
"ca.pem",
"/data/graph",
"--bolt",
"127.0.0.1:7687",
"--tls-cert",
"server.pem",
]),
expected
);
}
#[test]
fn resolves_query_api_auth_file_path() {
let command = cli_args(&[
"littlegraph",
"serve",
"/data/graph",
"--bolt",
"127.0.0.1:7687",
"--query",
"127.0.0.1:7474",
"--query-auth-file",
"query-auth.txt",
])
.unwrap();
let super::CliCommand::Serve {
query_addr,
query_auth_file,
..
} = command
else {
panic!("expected serve command");
};
assert_eq!(query_addr, Some("127.0.0.1:7474".parse().unwrap()));
assert_eq!(
query_auth_file,
Some(Box::new(std::path::PathBuf::from("query-auth.txt")))
);
}
#[test]
fn resolves_mcp_address_and_auth_file_path() {
let command = cli_args(&[
"littlegraph",
"serve",
"/data/graph",
"--mcp",
"127.0.0.1:3000",
"--mcp-auth-file",
"mcp-auth.txt",
])
.unwrap();
let super::CliCommand::Serve {
bolt_addr,
query_addr,
mcp_addr,
mcp_auth_file,
..
} = command
else {
panic!("expected serve command");
};
assert_eq!(bolt_addr, None);
assert_eq!(query_addr, None);
assert_eq!(
mcp_addr,
Some(super::McpListenAddress {
socket_addr: "127.0.0.1:3000".parse().unwrap(),
allowed_host: "127.0.0.1:3000".into(),
})
);
assert_eq!(
mcp_auth_file,
Some(Box::new(std::path::PathBuf::from("mcp-auth.txt")))
);
}
#[test]
fn accepts_query_only_and_rejects_serve_without_a_listener() {
let command = cli_args(&[
"littlegraph",
"serve",
"/data/graph",
"--query",
"127.0.0.1:7474",
])
.unwrap();
let super::CliCommand::Serve {
bolt_addr,
query_addr,
..
} = command
else {
panic!("expected serve command");
};
assert_eq!(bolt_addr, None);
assert_eq!(query_addr, Some("127.0.0.1:7474".parse().unwrap()));
assert!(cli_args(&["littlegraph", "serve", "/data/graph"]).is_err());
}
#[test]
fn rejects_invalid_serve_addresses_options_and_duplicates() {
for arguments in [
vec!["serve", "database", "--bolt", "not-an-address"],
vec![
"serve",
"database",
"--bolt",
"127.0.0.1:7687",
"--query",
"not-an-address",
],
vec![
"serve",
"database",
"--query",
"127.0.0.1:7474",
"--bolt-auth-file",
"auth.txt",
],
vec![
"serve",
"database",
"--bolt",
"127.0.0.1:7687",
"--bolt-auth",
"alice:secret",
],
vec![
"serve",
"database",
"--bolt",
"127.0.0.1:7687",
"--query-auth-file",
"query-auth.txt",
],
vec![
"serve",
"database",
"--query",
"127.0.0.1:7474",
"--query-bearer-token",
"secret-token",
],
vec![
"serve",
"database",
"--bolt",
"127.0.0.1:7687",
"--mcp-auth-file",
"mcp-auth.txt",
],
vec!["serve", "database", "--http", "127.0.0.1:7687"],
vec![
"serve",
"database",
"--bolt",
"127.0.0.1:7687",
"--tls-ca",
"ca.pem",
],
vec![
"serve",
"database",
"--bolt",
"127.0.0.1:7687",
"--tls-cert",
],
vec![
"serve",
"database",
"--bolt",
"127.0.0.1:7687",
"--bolt",
"127.0.0.1:7688",
],
] {
let mut args = vec!["littlegraph"];
args.extend(arguments);
assert!(cli_args(&args).is_err());
}
}
#[test]
fn rejects_invalid_arguments() {
assert!(cli_args(&["littlegraph"]).is_err());
assert!(cli_args(&["littlegraph", "repl", "database-dir", "extra"]).is_err());
}
#[test]
fn splits_statements_without_splitting_quoted_semicolons() {
assert_eq!(
query_texts("CREATE ({text: 'a;b''c'}); CREATE ({name: `semi;colon`});"),
["CREATE ({text: 'a;b''c'})", "CREATE ({name: `semi;colon`})"]
);
}
#[test]
fn ignores_semicolons_inside_cypher_comments() {
assert_eq!(
query_texts("// first; node\nCREATE (a); /* second; node */ CREATE (b);"),
[
"// first; node\nCREATE (a)",
"/* second; node */ CREATE (b)"
]
);
}
#[test]
fn executes_cypher_scripts_against_writable_storage() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
super::execute_cypher_script(
&mut graph,
"fixture.cyp",
"CREATE (:Person {name: 'Alice;A'}); CREATE (:Person {name: 'Bob'});",
)
.unwrap();
let result = graph
.query(
"MATCH (n:Person) RETURN n.name ORDER BY n.name",
Params::new(),
)
.unwrap();
assert_eq!(
result
.rows
.into_iter()
.map(|row| row.values[0].clone())
.collect::<Vec<_>>(),
[
Value::String("Alice;A".to_owned()),
Value::String("Bob".to_owned())
]
);
let error = super::execute_cypher_script(
&mut graph,
"broken.cyp",
"CREATE (:FailedScript); definitely not Cypher;",
)
.unwrap_err();
assert!(error.to_string().contains("broken.cyp statement 2"));
assert!(graph
.query("MATCH (n:FailedScript) RETURN n", Params::new())
.unwrap()
.rows
.is_empty());
}
#[test]
fn parses_line_transaction_directives_outside_queries_and_comments() {
let items = super::parse_cypher_script(concat!(
":begin\r\n",
"CREATE ({text: ':commit;'});\n",
"// :rollback\n",
"CREATE ({name: `:begin`});\n",
":commit\n",
));
assert_eq!(items[0].line, 1);
assert_eq!(
items[0].kind,
super::ScriptItemKind::Command(crate::shell::ShellCommand::Begin)
);
assert_eq!(items[1].line, 2);
assert_eq!(
items[1].kind,
super::ScriptItemKind::Query("CREATE ({text: ':commit;'})".to_owned())
);
assert_eq!(items[2].line, 4);
assert!(matches!(items[2].kind, super::ScriptItemKind::Query(_)));
assert_eq!(items[3].line, 5);
assert_eq!(
items[3].kind,
super::ScriptItemKind::Command(crate::shell::ShellCommand::Commit)
);
}
#[test]
fn recognizes_transaction_directive_after_comment_only_lines() {
let items = super::parse_cypher_script(concat!(
"// import users atomically\n",
"/* the directive starts on the next line */\n",
":begin\n",
"CREATE (:CommentedScript);\n",
":commit\n",
));
assert_eq!(items.len(), 3);
assert_eq!(items[0].line, 3);
assert_eq!(
items[0].kind,
super::ScriptItemKind::Command(crate::shell::ShellCommand::Begin)
);
assert_eq!(items[1].line, 4);
assert_eq!(items[2].line, 5);
assert_eq!(
items[2].kind,
super::ScriptItemKind::Command(crate::shell::ShellCommand::Commit)
);
}
#[test]
fn script_rejects_transaction_commands_and_rolls_back() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
let error = super::execute_cypher_script(
&mut graph,
"transactions.cyp",
"CREATE (:ScriptNode);\n:commit\n",
)
.unwrap_err();
assert!(error.to_string().contains("transactions.cyp line 2"));
assert!(error
.to_string()
.contains("the entire script runs in one transaction"));
let result = graph
.query("MATCH (n:ScriptNode) RETURN n", Params::new())
.unwrap();
assert!(result.rows.is_empty());
}
}