use relate_names::SmallName;
use crate::search::SearchSpec;
mod call;
mod expr;
mod pattern;
pub use call::*;
pub use expr::*;
pub use pattern::*;
#[derive(Debug, Clone, PartialEq)]
pub struct Query {
pub parts: Vec<SingleQuery>,
pub union_all: Vec<bool>,
pub next: Option<Box<Query>>,
}
impl Query {
pub fn final_stage(&self) -> &Query {
let mut tail = self;
while let Some(next) = tail.next.as_deref() {
tail = next;
}
tail
}
pub fn is_single_flat_part(&self) -> bool {
self.next.is_none() && self.parts.len() == 1
}
pub fn projects_columns(&self) -> bool {
let part = self
.final_stage()
.parts
.last()
.expect("a Query invariantly carries at least one part");
match part.clauses.last() {
Some(Clause::Return { .. }) => true,
Some(Clause::Conditional { branches, .. }) => {
let (_, branch) = branches
.first()
.expect("a WHEN clause has at least one branch");
branch.projects_columns()
}
Some(Clause::CallSubquery { query, .. }) => query.projects_columns(),
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SingleQuery {
pub clauses: Vec<Clause>,
}
impl SingleQuery {
pub fn leading_importing_with(&self) -> Option<LeadingWith<'_>> {
let clause = self
.clauses
.iter()
.find(|clause| !matches!(clause, Clause::Use { .. }))?;
let Clause::With {
distinct,
items,
order,
skip,
limit,
where_clause,
origin: WithOrigin::Explicit,
..
} = clause
else {
return None;
};
Some(LeadingWith {
distinct: *distinct,
items,
order,
skip: skip.as_ref(),
limit: limit.as_ref(),
where_clause: where_clause.as_ref(),
})
}
pub fn leading_imports(
&self,
outer: &std::collections::BTreeSet<String>,
) -> std::collections::BTreeSet<String> {
self.leading_importing_with()
.map_or_else(Default::default, |with| with.imports(outer))
}
}
impl LeadingWith<'_> {
pub fn imports(
&self,
outer: &std::collections::BTreeSet<String>,
) -> std::collections::BTreeSet<String> {
use std::collections::BTreeSet;
let mut imports = BTreeSet::new();
for item in self.items {
if matches!(item.expr, Expr::Star) {
imports.extend(outer.iter().cloned());
} else if let Some(name) = item.imported_name() {
imports.insert(name.to_string());
}
}
imports
}
}
pub struct LeadingWith<'a> {
pub distinct: bool,
pub items: &'a [Projection],
pub order: &'a [OrderItem],
pub skip: Option<&'a Expr>,
pub limit: Option<&'a Expr>,
pub where_clause: Option<&'a Expr>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum YieldItems {
Default,
Star,
Named(Vec<(SmallName, Option<SmallName>)>),
}
impl YieldItems {
pub fn items(&self) -> &[(SmallName, Option<SmallName>)] {
match self {
YieldItems::Named(items) => items,
YieldItems::Default | YieldItems::Star => &[],
}
}
pub fn names(&self) -> impl Iterator<Item = &SmallName> {
self.items().iter().map(|(name, _)| name)
}
pub fn effective_pairs(&self) -> impl Iterator<Item = (&SmallName, &SmallName)> {
self.items()
.iter()
.map(|(name, alias)| (name, alias.as_ref().unwrap_or(name)))
}
pub fn effective_names(&self) -> impl Iterator<Item = &SmallName> {
self.effective_pairs().map(|(_, effective)| effective)
}
pub fn has_yield(&self) -> bool {
!matches!(self, YieldItems::Default)
}
pub fn resolved_pairs(&self, defaults: &[&str]) -> Vec<(String, Option<String>)> {
match self {
YieldItems::Named(items) => items
.iter()
.map(|(name, alias)| {
(
name.to_string(),
alias.as_ref().map(SmallName::to_string),
)
})
.collect(),
YieldItems::Star | YieldItems::Default => defaults
.iter()
.map(|column| (column.to_string(), None))
.collect(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Clause {
Catalog(Box<relate_parser::Clause>),
Match {
optional: bool,
match_mode: MatchMode,
patterns: Vec<PathPattern>,
where_clause: Option<Expr>,
using_index: Vec<relate_parser::IndexHint>,
using_join: Vec<relate_parser::JoinHint>,
search: Option<Box<SearchClause>>,
},
Create {
patterns: Vec<PathPattern>,
},
Merge {
pattern: PathPattern,
on_create: Vec<SetItem>,
on_match: Vec<SetItem>,
},
Call {
name: SmallName,
args: CallArgs,
yield_items: YieldItems,
optional: bool,
where_clause: Option<Expr>,
},
Delete {
detach: bool,
expressions: Vec<Expr>,
},
Set {
items: Vec<SetItem>,
},
Remove {
items: Vec<RemoveItem>,
},
With {
distinct: bool,
group_by: Option<Vec<Expr>>,
items: Vec<Projection>,
order: Vec<OrderItem>,
skip: Option<Expr>,
limit: Option<Expr>,
where_clause: Option<Expr>,
origin: WithOrigin,
},
Unwind {
expression: Expr,
alias: SmallName,
},
Return {
distinct: bool,
group_by: Option<Vec<Expr>>,
items: Vec<Projection>,
order: Vec<OrderItem>,
skip: Option<Expr>,
limit: Option<Expr>,
},
CreateIndex {
name: Option<String>,
if_not_exists: bool,
label: SmallName,
property: SmallName,
},
DropIndex {
if_exists: bool,
target: DropIndexTarget,
},
ShowIndexes,
Finish,
LoadCsv {
with_headers: bool,
url: Expr,
variable: SmallName,
field_terminator: Option<String>,
},
CallSubquery {
query: Box<Query>,
optional: bool,
scope: CallScope,
in_transactions: Option<InTransactions>,
},
Conditional {
branches: Vec<(Expr, Query)>,
else_query: Option<Box<Query>>,
},
Foreach {
variable: SmallName,
list: Expr,
clauses: Vec<Clause>,
},
Use {
graph: Expr,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct SearchClause {
pub binding_var: SmallName,
pub spec: SearchSpec,
pub score_var: Option<SmallName>,
pub post_where: Option<Expr>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum DropIndexTarget {
Name(String),
Schema {
label: SmallName,
property: SmallName,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct Projection {
pub expr: Expr,
pub alias: Option<SmallName>,
pub source_text: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WithOrigin {
#[default]
Explicit,
Let,
Filter,
Page,
}
#[derive(Debug, Clone, PartialEq)]
pub struct OrderItem {
pub expr: Expr,
pub ascending: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SetItem {
Property { target: Expr, value: Expr },
ReplaceAll { target: Expr, value: Expr },
MergeMap { target: Expr, value: Expr },
Labels {
target: Expr,
labels: Vec<LabelExpr>,
},
LabelsFunction {
target: Expr,
value: Expr,
op: LabelsFunctionOp,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LabelsFunctionOp {
Overwrite,
Extend,
Remove,
}
#[derive(Debug, Clone, PartialEq)]
pub enum RemoveItem {
Property {
target: Expr,
},
Labels {
target: Expr,
labels: Vec<LabelExpr>,
},
}
pub fn var_prop(expr: &Expr) -> Option<(&SmallName, &SmallName)> {
let Expr::Property { expr, key, .. } = expr else {
return None;
};
let Expr::Variable(v) = expr.as_ref() else {
return None;
};
Some((v, key))
}
pub fn var_prop_named(expr: &Expr) -> Option<(&SmallName, relate_names::NamedToken)> {
let Expr::Property { key_id, .. } = expr else {
return None;
};
var_prop(expr).map(|(var, key)| (var, (key.clone(), *key_id)))
}
pub fn var_prop_owned(expr: &Expr) -> Option<(String, String)> {
var_prop(expr).map(|(var, key)| (var.to_string(), key.to_string()))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChronoOp {
Before,
After,
SameInstant,
SameRepresentation,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
Not,
Plus,
Minus,
IsNull,
IsNotNull,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
Or,
Xor,
And,
Eq,
Neq,
Lt,
Gt,
Lte,
Gte,
Add,
Sub,
Mul,
Div,
Mod,
Pow,
Concat,
In,
StartsWith,
EndsWith,
Contains,
Regex,
}
impl Projection {
pub fn output_name(&self, idx: usize) -> String {
if let Some(a) = &self.alias {
return a.to_string();
}
if let Some(name) = canonical_name(&self.expr) {
return name;
}
if let Some(src) = &self.source_text {
return src.clone();
}
format!("column_{idx}")
}
pub fn imported_name(&self) -> Option<&SmallName> {
match (&self.expr, &self.alias) {
(Expr::Variable(name), None) => Some(name),
_ => None,
}
}
}
pub fn canonical_name(expr: &Expr) -> Option<String> {
match expr {
Expr::Star => Some("*".into()),
Expr::Variable(v) => Some(v.to_string()),
Expr::MapProjection { expr, .. } => match expr.as_ref() {
Expr::Variable(v) => Some(v.to_string()),
_ => None,
},
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vector_metric_names_round_trip_through_from_name() {
for (keyword, metric) in VectorMetric::ALL {
assert_eq!(metric.name(), keyword);
assert_eq!(VectorMetric::from_name(keyword), Some(metric));
}
let names: std::collections::BTreeSet<_> = VectorMetric::ALL
.iter()
.map(|(keyword, _)| *keyword)
.collect();
assert_eq!(names.len(), VectorMetric::ALL.len(), "names are unique");
assert_eq!(
VectorMetric::from_name("euclidean_squared"),
Some(VectorMetric::EuclideanSquared)
);
assert_eq!(VectorMetric::from_name("not-a-metric"), None);
}
fn path(variable: Option<&str>, subpath_variable: Option<&str>) -> PathPattern {
PathPattern {
variable: variable.map(SmallName::from_name),
subpath_variable: subpath_variable.map(SmallName::from_name),
elements: vec![],
nodes: vec![],
rels: vec![],
where_clause: None,
mode: None,
selector: None,
is_shortest_path_function: false,
}
}
#[test]
fn path_names_lists_outer_then_subpath_variable() {
let both = path(Some("p"), Some("q"));
assert_eq!(
both.path_names()
.map(SmallName::to_string)
.collect::<Vec<_>>(),
["p", "q"]
);
assert!(both.has_path_name());
let subpath_only = path(None, Some("q"));
assert_eq!(
subpath_only
.path_names()
.map(SmallName::to_string)
.collect::<Vec<_>>(),
["q"]
);
assert!(subpath_only.has_path_name());
let outer_only = path(Some("p"), None);
assert_eq!(
outer_only
.path_names()
.map(SmallName::to_string)
.collect::<Vec<_>>(),
["p"]
);
assert!(outer_only.has_path_name());
let unnamed = path(None, None);
assert!(unnamed.path_names().next().is_none());
assert!(!unnamed.has_path_name());
}
}