use relate_ir::Clause;
use crate::clause_kind::ir_clause_keyword;
use crate::LogicalPlan;
pub fn is_write(plan: &LogicalPlan) -> bool {
crate::access::plan_access(plan, &mut |_| false).is_write()
}
pub fn plan_calls_write_procedure(
plan: &LogicalPlan,
is_write_procedure: &mut impl FnMut(&str) -> bool,
) -> bool {
let mut calls_write = false;
crate::walk_plan_clauses(plan, &mut |clause| {
if let Clause::Call { name, .. } = clause {
calls_write |= name.with_str(|text| is_write_procedure(text));
}
});
calls_write
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum DatabaseAdminCommand {
ShowDatabases,
AlterDatabase,
}
fn database_admin_command(command: &relate_parser::Clause) -> Option<DatabaseAdminCommand> {
use relate_parser::Clause as C;
match command {
C::ShowDatabases(_) => Some(DatabaseAdminCommand::ShowDatabases),
C::AlterDatabase(_) => Some(DatabaseAdminCommand::AlterDatabase),
_ => None,
}
}
fn admin_command_clause(clause: &Clause) -> Option<DatabaseAdminCommand> {
match clause {
Clause::Catalog(command) => database_admin_command(command.as_ref()),
_ => None,
}
}
pub fn is_database_admin_command(plan: &LogicalPlan) -> bool {
!plan.parts.is_empty()
&& plan.next.is_none()
&& plan
.parts
.iter()
.flatten()
.all(|clause| admin_command_clause(clause).is_some())
}
pub fn is_show_databases_with_next(plan: &LogicalPlan) -> bool {
plan.next.is_some()
&& plan.parts().any(|part| {
part.iter().any(|clause| {
admin_command_clause(clause) == Some(DatabaseAdminCommand::ShowDatabases)
})
})
}
pub fn admin_command_heads_statement(plan: &LogicalPlan) -> bool {
plan.parts.first().is_some_and(|head| {
head.iter()
.find(|clause| !matches!(clause, Clause::Use { .. }))
.and_then(admin_command_clause)
.is_some()
})
}
pub fn unsupported_system_clause_names(plan: &LogicalPlan) -> Option<String> {
let mut offending: Vec<&'static str> = Vec::new();
crate::walk_plan_parts(plan, &mut |clauses| {
collect_system_offenders(clauses, &mut offending);
});
if offending.is_empty() {
None
} else {
Some(offending.join(", "))
}
}
const SYSTEM_TAIL_KEYWORDS: &[&str] = &["RETURN", "WITH", "FINISH"];
fn collect_system_offenders(clauses: &[Clause], out: &mut Vec<&'static str>) {
let is_system_head =
|clause: &Clause| is_system_show(clause) || matches!(clause, Clause::Call { .. });
let has_show_or_call = clauses.iter().any(&is_system_head);
let is_tail = |clause: &Clause| SYSTEM_TAIL_KEYWORDS.contains(&ir_clause_keyword(clause));
let allowed = |clause: &Clause| {
is_system_head(clause)
|| matches!(clause, Clause::Use { .. })
|| (is_tail(clause) && has_show_or_call)
};
let (non_tail, tail): (Vec<&'static str>, Vec<&'static str>) = clauses
.iter()
.filter(|clause| !allowed(clause))
.map(ir_clause_keyword)
.partition(|name| !SYSTEM_TAIL_KEYWORDS.contains(name));
let part_offenders = if non_tail.is_empty() { tail } else { non_tail };
for name in part_offenders {
if !out.contains(&name) {
out.push(name);
}
}
}
fn catalog_allowed_on_system(command: &relate_parser::Clause) -> bool {
use relate_parser::Clause as C;
matches!(
command,
C::ShowFunctions(_)
| C::ShowConstraints(_)
| C::ShowIndexes(_)
| C::ShowDatabases(_)
| C::ShowRoles(_)
| C::ShowServers(_)
| C::ShowUsers(_)
| C::ShowProcedures(_)
| C::ShowSettings(_)
| C::ShowTransactions(_)
| C::ShowGraphType(_)
| C::ShowCurrentGraphType(_)
| C::AlterDatabase(_)
)
}
fn is_system_show(clause: &Clause) -> bool {
match clause {
Clause::Catalog(command) => catalog_allowed_on_system(command.as_ref()),
Clause::ShowIndexes => true,
_ => false,
}
}
pub fn composed_show_disallowed_clause(plan: &LogicalPlan) -> Option<&'static str> {
let mut offending = None;
crate::walk_plan_parts(plan, &mut |clauses| {
let composes_show = clauses.iter().any(is_system_show);
if !composes_show {
return;
}
for clause in clauses {
if offending.is_none() && matches!(clause, Clause::With { .. }) {
offending = Some(ir_clause_keyword(clause));
}
}
});
offending
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plan_of;
#[test]
fn writes_classify_as_writes() {
for cypher in [
"CREATE (n)",
"MERGE (n:N {id: 1})",
"MATCH (n) SET n.x = 1",
"MATCH (n) DELETE n",
"MATCH (n) REMOVE n.x",
"CREATE INDEX i FOR (n:N) ON (n.p)",
"CREATE CONSTRAINT c FOR (n:N) REQUIRE n.id IS UNIQUE",
"FOREACH (x IN [1] | CREATE (n))",
] {
assert!(is_write(&plan_of(cypher)), "{cypher}");
}
}
#[test]
fn reads_classify_as_reads() {
for cypher in [
"RETURN 1 AS n",
"MATCH (n) RETURN n",
"SHOW INDEXES",
"CALL db.labels()",
] {
assert!(!is_write(&plan_of(cypher)), "{cypher}");
}
}
#[test]
fn read_only_call_in_expression_subqueries_classifies_as_read() {
for cypher in [
"RETURN EXISTS { CALL { RETURN 1 AS x } } AS x",
"RETURN COUNT { CALL { RETURN 1 AS x } } AS x",
"RETURN COLLECT { CALL { RETURN 1 AS x } RETURN x } AS x",
] {
assert!(!is_write(&plan_of(cypher)), "{cypher}");
}
}
#[test]
fn nested_queries_recurse_through_one_predicate() {
assert!(is_write(&plan_of("WHEN true THEN { CREATE (n) }")));
assert!(!is_write(&plan_of(
"WHEN true THEN { RETURN 1 AS x } ELSE { RETURN 2 AS x }"
)));
assert!(is_write(&plan_of(
"WHEN false THEN { MATCH (n) RETURN count(n) AS x } \
ELSE { CREATE (m) RETURN 0 AS x }"
)));
assert!(is_write(&plan_of("RETURN 1 AS x NEXT CREATE (n)")));
assert!(!is_write(&plan_of("RETURN 1 AS x UNION RETURN 2 AS x")));
}
#[test]
fn write_procedure_calls_are_found_anywhere_in_the_clause_tree() {
let is_write_proc = &mut |name: &str| name == "db.createLabel";
for cypher in [
"CALL db.createLabel('X')",
"WHEN true THEN { CALL db.createLabel('X') }",
"WHEN false THEN { RETURN 1 AS x } ELSE { CALL db.createLabel('X') RETURN 1 AS x }",
"CALL { CALL db.createLabel('X') }",
"RETURN 1 AS x NEXT CALL db.createLabel('X')",
] {
assert!(
plan_calls_write_procedure(&plan_of(cypher), is_write_proc),
"{cypher}"
);
}
for cypher in [
"CALL db.labels()",
"WHEN true THEN { CALL db.labels() YIELD label RETURN label }",
"RETURN 1 AS x",
] {
assert!(
!plan_calls_write_procedure(&plan_of(cypher), is_write_proc),
"{cypher}"
);
}
}
#[test]
fn database_admin_commands_classify() {
assert!(is_database_admin_command(&plan_of("SHOW DATABASES")));
assert!(is_database_admin_command(&plan_of(
"ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 25"
)));
assert!(!is_database_admin_command(&plan_of("MATCH (n) RETURN n")));
assert!(!is_database_admin_command(&plan_of("SHOW INDEXES")));
assert!(!is_database_admin_command(&plan_of(
"SHOW DATABASES YIELD name RETURN name"
)));
}
fn show_databases_clause() -> Clause {
Clause::Catalog(Box::new(relate_parser::Clause::ShowDatabases(
relate_parser::ShowDatabasesClause {
filter: relate_parser::DatabaseFilter::All,
yields: Default::default(),
where_expr: None,
stages: Vec::new(),
},
)))
}
#[test]
fn show_databases_with_next_classifies_the_chain() {
let mut head = plan_of("RETURN 1 AS x NEXT RETURN x");
head.parts[0] = vec![show_databases_clause()];
assert!(is_show_databases_with_next(&head));
let mut tail = plan_of("RETURN 1 AS x NEXT RETURN x");
tail.next.as_mut().unwrap().parts[0] = vec![show_databases_clause()];
assert!(is_show_databases_with_next(&tail));
let mut plain = plan_of("RETURN 1 AS x");
plain.parts[0] = vec![show_databases_clause()];
assert!(!is_show_databases_with_next(&plain));
let mut alter = plan_of("ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 25");
alter.next = Some(Box::new(plan_of("RETURN 1 AS x")));
assert!(!is_show_databases_with_next(&alter));
assert!(!is_show_databases_with_next(&plan_of(
"RETURN 1 AS x NEXT RETURN x + 1 AS y"
)));
}
#[test]
fn system_offender_names_follow_ce() {
assert_eq!(
unsupported_system_clause_names(&plan_of("MATCH (n) RETURN count(n) AS c")),
Some("MATCH".to_string())
);
assert_eq!(
unsupported_system_clause_names(&plan_of("RETURN 1 AS x")),
Some("RETURN".to_string())
);
for cypher in [
"CALL db.labels()",
"CALL db.labels() YIELD label RETURN label",
"SHOW INDEXES",
"SHOW DATABASES",
] {
assert_eq!(
unsupported_system_clause_names(&plan_of(cypher)),
None,
"{cypher}"
);
}
}
#[test]
fn composed_show_disallowed_clause_flags_with_around_show_commands() {
for cypher in [
"SHOW DATABASES YIELD name AS d1 WITH 1 AS n RETURN n",
"USE system SHOW DATABASES YIELD name AS d1 WITH 1 AS n RETURN n",
"WITH 1 AS n SHOW DATABASES YIELD name RETURN name",
"SHOW DEFAULT DATABASE YIELD name WITH 1 AS n RETURN n",
"SHOW HOME DATABASE YIELD name WITH 1 AS n RETURN n",
"SHOW DATABASE neo4j YIELD name WITH 1 AS n RETURN n",
"SHOW PROCEDURES YIELD name AS p1 WITH 1 AS n RETURN n",
"SHOW FUNCTIONS YIELD name AS f1 WITH 1 AS n RETURN n",
"SHOW SETTINGS YIELD name AS s1 WITH 1 AS n RETURN n",
"SHOW CURRENT GRAPH TYPE YIELD specification AS spec1 WITH 1 AS n RETURN n",
] {
assert_eq!(
composed_show_disallowed_clause(&plan_of(cypher)),
Some("WITH"),
"{cypher}"
);
}
for cypher in [
"CALL db.labels() YIELD label WITH 1 AS n RETURN n",
"WITH 1 AS n RETURN n",
] {
assert_eq!(
composed_show_disallowed_clause(&plan_of(cypher)),
None,
"{cypher}"
);
}
for cypher in [
"SHOW DATABASES",
"SHOW DATABASES YIELD name RETURN name",
"USE system SHOW DEFAULT DATABASE YIELD name AS defaultDb SHOW DATABASES YIELD name AS db, access WHERE defaultDb = db RETURN *",
"ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 25",
] {
assert_eq!(
composed_show_disallowed_clause(&plan_of(cypher)),
None,
"{cypher}"
);
}
}
#[test]
fn admin_command_heads_statement_classifies_the_head() {
for cypher in [
"SHOW DATABASES",
"USE system SHOW DATABASES",
"USE neo4j SHOW DATABASES",
"USE neo4j SHOW DEFAULT DATABASE",
"USE neo4j SHOW HOME DATABASE",
"USE neo4j SHOW DATABASE neo4j",
"USE neo4j ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 5",
"USE neo4j SHOW DATABASES YIELD name RETURN name",
"USE neo4j SHOW DATABASES YIELD name AS a RETURN a UNION SHOW DATABASES YIELD name AS a RETURN a",
] {
assert!(
admin_command_heads_statement(&plan_of(cypher)),
"{cypher}"
);
}
for cypher in [
"MATCH (n) RETURN n",
"USE neo4j MATCH (n) SHOW DATABASES YIELD name RETURN name",
"USE neo4j WITH 1 AS n SHOW DATABASES YIELD name RETURN name",
"SHOW INDEXES",
] {
assert!(!admin_command_heads_statement(&plan_of(cypher)), "{cypher}");
}
}
}