use relate_names::{NamedToken, SmallName, Token};
use super::Expr;
pub fn pattern_prop_key(keys: &[NamedToken], name: &str) -> NamedToken {
keys.iter()
.find(|(known, _)| *known == name)
.cloned()
.unwrap_or_else(|| (SmallName::from_name(name), Token::Unresolved))
}
#[derive(Debug, Clone, PartialEq)]
pub struct PathPattern {
pub variable: Option<SmallName>,
pub subpath_variable: Option<SmallName>,
pub elements: Vec<PatternElement>,
pub nodes: Vec<NodePattern>,
pub rels: Vec<RelPattern>,
pub where_clause: Option<Box<Expr>>,
pub mode: Option<PathMode>,
pub selector: Option<PathSelector>,
pub is_shortest_path_function: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum PatternElement {
Node(NodePattern),
Relationship(RelPattern),
Quantified(QuantifiedPathPattern),
}
impl PathPattern {
pub fn path_names(&self) -> impl Iterator<Item = &SmallName> {
[self.variable.as_ref(), self.subpath_variable.as_ref()]
.into_iter()
.flatten()
}
pub fn relationship_variables(&self) -> impl Iterator<Item = &SmallName> {
let mut names: Vec<&SmallName> = Vec::new();
collect_element_rel_vars(&self.elements, &mut names);
for rel in &self.rels {
if let Some(name) = rel.variable.as_ref() {
if !names.contains(&name) {
names.push(name);
}
}
}
names.into_iter()
}
pub fn has_path_name(&self) -> bool {
self.path_names().next().is_some()
}
pub fn needs_gpm(&self) -> bool {
self.nodes.is_empty()
|| self.mode.is_some()
|| self.selector.is_some()
|| self.where_clause.is_some()
|| self.elements.iter().any(|element| match element {
PatternElement::Node(node) => node.where_clause.is_some(),
PatternElement::Relationship(rel) => rel.where_clause.is_some() || rel.quantified,
PatternElement::Quantified(_) => true,
})
}
}
fn collect_element_rel_vars<'a>(elements: &'a [PatternElement], out: &mut Vec<&'a SmallName>) {
for element in elements {
match element {
PatternElement::Relationship(rel) => {
if let Some(name) = rel.variable.as_ref() {
if !out.contains(&name) {
out.push(name);
}
}
}
PatternElement::Quantified(qpp) => collect_element_rel_vars(&qpp.elements, out),
PatternElement::Node(_) => {}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct QuantifiedPathPattern {
pub subpath_variable: Option<SmallName>,
pub elements: Vec<PatternElement>,
pub where_clause: Option<Expr>,
pub min: u32,
pub max: Option<u32>,
}
impl QuantifiedPathPattern {
pub fn implicit_var_length_rel(&self) -> Option<&RelPattern> {
if self.subpath_variable.is_some() || self.where_clause.is_some() {
return None;
}
let [PatternElement::Node(head), PatternElement::Relationship(rel), PatternElement::Node(tail)] =
self.elements.as_slice()
else {
return None;
};
let implicit = |node: &NodePattern| {
node.variable.is_none()
&& node.labels.is_empty()
&& node.label_expr.is_none()
&& node.properties.is_none()
&& node.where_clause.is_none()
};
if !implicit(head) || !implicit(tail) || rel.var_length {
return None;
}
Some(rel)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MatchMode {
#[default]
DifferentRelationships,
RepeatableElements,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathMode {
Walk,
Trail,
Acyclic,
Simple,
}
#[derive(Debug, Clone, PartialEq)]
pub enum PathCount {
Literal(u32),
Parameter(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum PathSelector {
All,
Any(Option<PathCount>),
AnyShortest,
AllShortest,
Shortest {
count: Option<PathCount>,
group: bool,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct NodePattern {
pub variable: Option<SmallName>,
pub labels: Vec<NamedToken>,
pub label_expr: Option<LabelExpr>,
pub properties: Option<Expr>,
pub prop_keys: Vec<NamedToken>,
pub where_clause: Option<Expr>,
pub force_scan: bool,
}
impl NodePattern {
pub fn anonymous() -> Self {
NodePattern {
variable: None,
labels: Vec::new(),
label_expr: None,
properties: None,
prop_keys: Vec::new(),
where_clause: None,
force_scan: false,
}
}
pub fn label_names(&self) -> impl Iterator<Item = &SmallName> {
self.labels.iter().map(|(name, _)| name)
}
pub fn static_disjunction_arms(&self) -> Option<DisjunctionArms<'_>> {
self.label_expr.as_ref()?.static_disjunction_arms()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RelPattern {
pub variable: Option<SmallName>,
pub types: Vec<NamedToken>,
pub type_expr: Option<LabelExpr>,
pub direction: Direction,
pub properties: Option<Expr>,
pub prop_keys: Vec<NamedToken>,
pub var_length: bool,
pub min_hops: u32,
pub max_hops: Option<u32>,
pub where_clause: Option<Expr>,
pub quantified: bool,
}
impl RelPattern {
pub fn type_names(&self) -> impl Iterator<Item = &SmallName> {
self.types.iter().map(|(name, _)| name)
}
pub fn type_expr_is_static_types(&self) -> bool {
match self.type_expr.as_ref() {
Some(LabelExpr::Label(label)) => self.types.len() == 1 && label == &self.types[0].0,
Some(LabelExpr::Or(items)) => {
items.len() == self.types.len()
&& items
.iter()
.zip(&self.types)
.all(|(item, ty)| matches!(item, LabelExpr::Label(label) if *label == ty.0))
}
_ => false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Direction {
Outgoing,
Incoming,
Both,
}
impl Direction {
pub fn flip(self) -> Direction {
match self {
Direction::Outgoing => Direction::Incoming,
Direction::Incoming => Direction::Outgoing,
Direction::Both => Direction::Both,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum LabelExpr {
Label(SmallName),
Wildcard,
Dynamic {
expr: Box<Expr>,
quantifier: DynamicLabelQuantifier,
},
Not(Box<LabelExpr>),
And(Vec<LabelExpr>),
Or(Vec<LabelExpr>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DynamicLabelQuantifier {
Default,
All,
Any,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuantifierKind {
All,
Any,
None,
Single,
}
impl LabelExpr {
pub fn is_static_conjunction(&self) -> bool {
match self {
LabelExpr::Label(_) => true,
LabelExpr::And(items) => {
!items.is_empty() && items.iter().all(LabelExpr::is_static_conjunction)
}
_ => false,
}
}
pub fn is_static_disjunction(&self) -> bool {
match self {
LabelExpr::Label(_) => true,
LabelExpr::Or(items) => {
!items.is_empty() && items.iter().all(LabelExpr::is_static_disjunction)
}
_ => false,
}
}
pub fn static_disjunction_arms(&self) -> Option<DisjunctionArms<'_>> {
let (base, items): (Vec<&SmallName>, &[LabelExpr]) = match self {
LabelExpr::Or(items) => (Vec::new(), items),
LabelExpr::And(items) => {
if self.is_static_conjunction() {
return None;
}
let mut base: Vec<&SmallName> = Vec::new();
let mut or = None;
for item in items {
match item {
LabelExpr::Label(label) => base.push(label),
LabelExpr::Or(items) if or.is_none() => or = Some(items.as_slice()),
_ => return None,
}
}
(base, or?)
}
_ => return None,
};
if items.is_empty() {
return None;
}
let disjuncts: Option<Vec<&SmallName>> = items
.iter()
.map(|item| match item {
LabelExpr::Label(label) => Some(label),
_ => None,
})
.collect();
Some(DisjunctionArms {
base,
disjuncts: disjuncts?,
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct DisjunctionArms<'a> {
base: Vec<&'a SmallName>,
disjuncts: Vec<&'a SmallName>,
}
impl<'a> DisjunctionArms<'a> {
pub fn single(label: &'a SmallName) -> Self {
DisjunctionArms {
base: Vec::new(),
disjuncts: vec![label],
}
}
pub fn base(&self) -> &[&'a SmallName] {
&self.base
}
pub fn disjuncts(&self) -> &[&'a SmallName] {
&self.disjuncts
}
pub fn len(&self) -> usize {
self.disjuncts.len()
}
pub fn is_empty(&self) -> bool {
self.disjuncts.is_empty()
}
pub fn arms(&self) -> impl Iterator<Item = impl Iterator<Item = &'a SmallName> + '_> + '_ {
self.disjuncts
.iter()
.map(|disjunct| self.base.iter().copied().chain(std::iter::once(*disjunct)))
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum TypeExpr {
Predefined {
kind: PredefinedType,
not_null: bool,
},
List {
element: Box<TypeExpr>,
not_null: bool,
},
PropertyValue {
not_null: bool,
},
Union(Vec<TypeExpr>),
Vector {
coord: Option<String>,
dimension: Option<i64>,
not_null: bool,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PredefinedType {
Nothing,
Null,
Any,
Boolean,
String,
Integer,
Float,
Date,
Duration,
Point,
LocalTime,
ZonedTime,
LocalDateTime,
ZonedDateTime,
Node,
Relationship,
Path,
Map,
Uuid,
}
impl PredefinedType {
pub fn as_str(self) -> &'static str {
match self {
PredefinedType::Nothing => "NOTHING",
PredefinedType::Null => "NULL",
PredefinedType::Any => "ANY",
PredefinedType::Boolean => "BOOLEAN",
PredefinedType::String => "STRING",
PredefinedType::Integer => "INTEGER",
PredefinedType::Float => "FLOAT",
PredefinedType::Date => "DATE",
PredefinedType::Duration => "DURATION",
PredefinedType::Point => "POINT",
PredefinedType::LocalTime => "LOCAL TIME",
PredefinedType::ZonedTime => "ZONED TIME",
PredefinedType::LocalDateTime => "LOCAL DATETIME",
PredefinedType::ZonedDateTime => "ZONED DATETIME",
PredefinedType::Node => "NODE",
PredefinedType::Relationship => "RELATIONSHIP",
PredefinedType::Path => "PATH",
PredefinedType::Map => "MAP",
PredefinedType::Uuid => "UUID",
}
}
}
#[cfg(test)]
mod tests {
use super::{DisjunctionArms, LabelExpr, SmallName};
fn label(name: &str) -> LabelExpr {
LabelExpr::Label(SmallName::from_name(name))
}
fn rendered(arms: &DisjunctionArms<'_>) -> Vec<Vec<String>> {
arms.arms()
.map(|arm| arm.map(|label| label.to_string()).collect())
.collect()
}
#[test]
fn the_fold_shapes_answer_their_per_arm_views() {
let bare = LabelExpr::Or(vec![label("Model"), label("Source")]);
let arms = bare.static_disjunction_arms().expect("the bare Or folds");
assert_eq!(
rendered(&arms),
vec![vec!["Model".to_string()], vec!["Source".to_string()]]
);
assert!(arms.base().is_empty());
assert_eq!(arms.len(), 2);
let nested = LabelExpr::And(vec![
label("C"),
LabelExpr::Or(vec![label("A"), label("B")]),
]);
let arms = nested.static_disjunction_arms().expect("the And folds");
assert_eq!(
rendered(&arms),
vec![
vec!["C".to_string(), "A".to_string()],
vec!["C".to_string(), "B".to_string()]
]
);
assert_eq!(
arms.base(),
vec![&SmallName::from_name("C")],
"the shared conjunction every arm carries"
);
}
#[test]
fn every_other_shape_declines() {
assert!(label("A").static_disjunction_arms().is_none());
assert!(LabelExpr::And(vec![label("A"), label("B")])
.static_disjunction_arms()
.is_none());
let nested = LabelExpr::Or(vec![
label("A"),
LabelExpr::Or(vec![label("B"), label("C")]),
]);
assert!(nested.static_disjunction_arms().is_none());
let dnf = LabelExpr::And(vec![
LabelExpr::Or(vec![label("A"), label("B")]),
LabelExpr::Or(vec![label("C"), label("D")]),
]);
assert!(dnf.static_disjunction_arms().is_none());
assert!(LabelExpr::Or(Vec::new())
.static_disjunction_arms()
.is_none());
let wild = LabelExpr::Or(vec![label("A"), LabelExpr::Wildcard]);
assert!(wild.static_disjunction_arms().is_none());
let negated = LabelExpr::Or(vec![label("A"), LabelExpr::Not(Box::new(label("B")))]);
assert!(negated.static_disjunction_arms().is_none());
assert!(LabelExpr::Wildcard.static_disjunction_arms().is_none());
}
#[test]
fn the_single_label_view_answers_one_arm() {
let name = SmallName::from_name("Model");
let arms = DisjunctionArms::single(&name);
assert_eq!(rendered(&arms), vec![vec!["Model".to_string()]]);
assert!(arms.base().is_empty());
assert_eq!(arms.disjuncts(), vec![&name]);
assert!(!arms.is_empty());
}
}