Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-gql/src/ast.rs

//! The parsed form of a query (GQL terms: node pattern, edge pattern, label, quantifier).

pub use kleene_plan::{BinOp, Func, TextOp, UnOp};

/// `[CALL ...]`, `MATCH ... [WHERE ...]` clauses, then `RETURN` (or `WITH` and the next
/// part).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Query {
    /// The part before a `WITH`: its `ret` is the `WITH`'s items (with its `DISTINCT`,
    /// `ORDER BY`, `SKIP` and `LIMIT`), whose rows bind this part's first variables (a
    /// node as a node, a path as its length, any other value as a value).
    pub prior: Option<Box<Query>>,
    /// The `WITH`'s `WHERE` (on the variables it binds), parts joined by `AND`.
    pub with_filter: Vec<Condition>,
    /// `UNWIND list AS x` first: each row (of the part before) once per item, `x` the item.
    pub unwind: Option<Unwind>,
    /// A procedure call first: its yielded columns are variables of the query.
    pub call: Option<CallClause>,
    /// The `MATCH` clauses, in order (all must hold: their patterns are joined).
    pub matches: Vec<Match>,
    /// The `RETURN` clause.
    pub ret: Return,
    /// The queries after `UNION [ALL]`, each with its own `RETURN` of the same columns.
    pub union: Vec<Query>,
    /// `UNION ALL` (every row of each part) rather than `UNION` (the distinct rows).
    pub union_all: bool,
}

/// `CALL name(arg, ...) [YIELD column [AS name], ...] [WHERE condition]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallClause {
    /// The procedure's name as written (dotted parts joined by `.`).
    pub procedure: String,
    /// The arguments.
    pub args: Vec<CallArg>,
    /// The yielded columns; empty: every column under its own name.
    pub yields: Vec<YieldItem>,
    /// The `WHERE` condition's parts joined by `AND` at the top.
    pub filter: Vec<Condition>,
}

/// An argument of a procedure call.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CallArg {
    /// A name: an edge label (`CALLS`, `'CALLS'`) or a property key.
    Name(String),
    /// A value: an integer or a `$parameter`.
    Value(Operand),
}

/// `column [AS name]` of a `YIELD`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct YieldItem {
    /// The procedure's column.
    pub column: String,
    /// The variable it binds (default: the column's name).
    pub alias: Option<String>,
}

/// `MATCH path, path ... [WHERE condition]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match {
    /// The comma-separated path patterns.
    pub paths: Vec<PathPattern>,
    /// The `WHERE` condition as its parts joined by `AND` at the top (outside brackets
    /// too), all of which must be true.
    pub filter: Vec<Condition>,
    /// `OPTIONAL MATCH`: each match of the clauses before it is kept, with its extensions
    /// by this pattern and condition, or with nulls for the new variables when it has none.
    pub optional: bool,
}

/// A `WHERE` condition. Its value is true, false or unknown (GQL's three-valued logic):
/// a comparison that reads a property a node does not have is unknown, `NOT` of unknown
/// is unknown, `AND` is false when a part is false, `OR` true when a part is true; a match
/// is kept only where the condition is true.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Condition {
    /// `left op right`.
    Cmp(Comparison),
    /// `value IN (v, ...)` or `value IN [v, ...]`: equal to one of the list.
    In {
        /// The value tested.
        value: Operand,
        /// The list.
        list: Vec<Operand>,
    },
    /// `value IS NULL` (`null`) or `value IS NOT NULL`: never unknown; a property a node
    /// does not have is null.
    IsNull {
        /// The value tested.
        value: Operand,
        /// True for `IS NULL`.
        null: bool,
    },
    /// `value STARTS WITH pattern`, `ENDS WITH`, `CONTAINS`: a string property against a
    /// string literal, decided once per distinct string, not per row.
    Text {
        /// The value tested (a string property).
        value: Operand,
        /// The test.
        op: TextOp,
        /// The pattern (a string literal).
        pattern: Operand,
    },
    /// `NOT c`.
    Not(Box<Condition>),
    /// `c AND c ...`.
    And(Vec<Condition>),
    /// `c OR c ...`.
    Or(Vec<Condition>),
    /// `c XOR c`: exactly one is true.
    Xor(Box<Condition>, Box<Condition>),
    /// `all(x IN r WHERE c)`, `any(...)`, `none(...)`, `single(...)`: `c` of the edges of
    /// the quantified edge `r`, each named `x`.
    EdgeList {
        /// Which of the edges must pass.
        quant: ListQuant,
        /// The name of each edge in `pred`.
        var: String,
        /// The quantified edge variable.
        list: String,
        /// The condition on one edge.
        pred: Box<Condition>,
    },
}

/// How many of a list's items a list predicate needs to pass.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ListQuant {
    /// `all`: every one.
    All,
    /// `any`: one at least.
    Any,
    /// `none`: none.
    None,
    /// `single`: exactly one.
    Single,
}

impl ListQuant {
    /// The function's name.
    pub fn name(self) -> &'static str {
        match self {
            ListQuant::All => "all",
            ListQuant::Any => "any",
            ListQuant::None => "none",
            ListQuant::Single => "single",
        }
    }
}

/// `[p =] [selector] (a)-[:T]->(b)<-[:U]-(c)...`: a node, then edges each followed by a
/// node.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PathPattern {
    /// The path variable (`p = ...`).
    pub var: Option<String>,
    /// Which paths are kept per pair of ends (`ANY SHORTEST`, `ALL SHORTEST`, Cypher's
    /// `shortestPath(..)` and `allShortestPaths(..)`); `None`: every match.
    pub selector: Option<Selector>,
    /// The first node.
    pub start: NodePattern,
    /// Each edge and the node after it.
    pub steps: Vec<(EdgePattern, NodePattern)>,
}

/// A path selector: which paths of a pattern are kept for each pair of ends.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Selector {
    /// `ANY SHORTEST` (Cypher `shortestPath`): one shortest path per pair.
    AnyShortest,
    /// `ALL SHORTEST` (Cypher `allShortestPaths`): every shortest path.
    AllShortest,
    /// `ANY`: one path per pair (a shortest one is chosen).
    Any,
}

/// `(var:Label)`, `(var IS Label)` or `(var:A|B)`; both parts optional.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct NodePattern {
    /// The variable.
    pub var: Option<String>,
    /// The labels the node may have, one of them (`:A|B`); empty: any node.
    pub labels: Vec<String>,
}

/// Which way an edge pattern points.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Dir {
    /// `-[..]->`: from the node before to the node after.
    Out,
    /// `<-[..]-`: from the node after to the node before.
    In,
    /// `-[..]-` or `<-[..]->`: either way.
    Any,
}

/// `-[var:Label]->`, `<-[var IS A|B]-`, `-[]-`, or with no brackets `->`, `<-`, `-` (and
/// Cypher's `-->`, `<--`, `--`), with an optional quantifier.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EdgePattern {
    /// The variable.
    pub var: Option<String>,
    /// The edge labels (types) it may have, one of them; empty: any edge.
    pub labels: Vec<String>,
    /// Direction.
    pub dir: Dir,
    /// How many edges in a row: `None` for exactly one.
    pub quant: Option<Quantifier>,
}

/// A path length range: GQL's `*` (0 or more), `+` (1 or more), `{m,n}`, `{m,}`, `{m}`;
/// the Cypher form `[:T*]` (1 or more) and `[:T*m..n]` is read too.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Quantifier {
    /// The fewest edges.
    pub min: u64,
    /// The most edges; `None`: no bound.
    pub max: Option<u64>,
}

/// A comparison operator.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CmpOp {
    /// `=`
    Eq,
    /// `<>`
    Ne,
    /// `<`
    Lt,
    /// `<=`
    Le,
    /// `>`
    Gt,
    /// `>=`
    Ge,
}

/// One side of a comparison, or a returned value.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Operand {
    /// A node variable (its id).
    Var(String),
    /// `var.key`: a property of a node or an edge. A key `k@form` is property `k` read by
    /// that form, the catalog's relation `L.k@form`: `hex(var.k)` is `k@hex`, the hex of
    /// the property's bytes.
    Prop(String, String),
    /// An unsigned integer.
    Int(u64),
    /// `$name`: a parameter, given a value when the query is lowered ([`crate::lower_with`]).
    Param(String),
    /// A string literal (escapes read).
    Str(String),
    /// A negative integer (`-5`; a non-negative one is [`Operand::Int`]).
    Signed(i64),
    /// A number with a fraction or exponent (`1.5`, `-2e3`).
    Float(Float),
    /// `TRUE` or `FALSE`.
    Bool(bool),
    /// `NULL`.
    Null,
    /// `length(p)`: the number of edges of path `p` (or a path's length through a `WITH`).
    Length(String),
    /// `id(n)`: node `n`'s id (its row number plus its vertex table's base, see
    /// [`crate::Catalog::vertex_table`]).
    Id(String),
    /// `a op b`: integer or float arithmetic (`+ - * / %`), null when a side is null; the
    /// bit operators of `bitand(a, b)`, `bitor`, `bitxor`, `shiftleft(a, n)`,
    /// `shiftright(a, n)` over integers.
    Arith(Box<Operand>, BinOp, Box<Operand>),
    /// `-a` (of a value, not a number literal) or `bitnot(a)`.
    Unary(UnOp, Box<Operand>),
    /// A string function: `a || b` ([`Func::Concat`]), `char_length(s)` /
    /// `character_length(s)` ([`Func::Len`], characters), `substring(s, start [, len])`
    /// ([`Func::Substr`], from 0; past the end shorter); null where an argument is null or
    /// a place or length is negative.
    Call(Func, Vec<Operand>),
    /// Edge variable `e`'s row (the catalog's `E@row`), passed on by the part before an
    /// `UNWIND e.key` ([`UnwindList::EdgeProp`]); no query writes it.
    EdgeRow(String),
}

/// A float literal, equal to another when its bits are.
#[derive(Clone, Copy, Debug)]
pub struct Float(pub f64);

impl PartialEq for Float {
    fn eq(&self, o: &Float) -> bool {
        self.0.to_bits() == o.0.to_bits()
    }
}

impl Eq for Float {}

/// `left op right`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Comparison {
    /// The left side.
    pub left: Operand,
    /// The operator.
    pub op: CmpOp,
    /// The right side.
    pub right: Operand,
}

/// `RETURN [DISTINCT] item, ... [LIMIT n]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Return {
    /// `DISTINCT`: repeated rows dropped. (A query of a `CALL` alone, with no `RETURN`,
    /// has no items: it returns every yielded column.)
    pub distinct: bool,
    /// The returned values.
    pub items: Vec<ReturnItem>,
    /// `ORDER BY key [ASC | DESC], ...`: rows sorted by the keys in turn (rows equal on
    /// every key: by their values, rising). Empty: rows sorted by their values.
    pub order: Vec<OrderKey>,
    /// `OFFSET n` (or `SKIP n`): the first `n` rows (in order) left out.
    pub offset: Option<u64>,
    /// `LIMIT n`: at most `n` rows, after the offset.
    pub limit: Option<u64>,
}

/// `value [ASC | DESC]` of an `ORDER BY`: a returned column's name (its alias, `var` or
/// `var.key`), or (without `DISTINCT`) any variable or property of the match.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OrderKey {
    /// The value.
    pub value: Operand,
    /// `DESC` (or `DESCENDING`): falling.
    pub descending: bool,
}

/// `value [AS alias]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReturnItem {
    /// A variable, a property or an aggregate (never a literal).
    pub value: ReturnValue,
    /// The alias.
    pub alias: Option<String>,
}

/// What a `RETURN` item gives.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReturnValue {
    /// A variable or a property.
    Value(Operand),
    /// `length(p)`: the number of edges of path `p`.
    Length(String),
    /// `nodes(p)` (or `p` itself): the nodes of path `p`, a list.
    Nodes(String),
    /// `shortestPath(pattern)` / `allShortestPaths(pattern)` as an item (`AS p` needed):
    /// read as `OPTIONAL MATCH p = ANY SHORTEST pattern` (`ALL SHORTEST`) before it, the
    /// item `p` (left by the parser as the path variable).
    Path(Box<PathPattern>),
    /// `labels(n)`, `type(r)`, `properties(x)`, `relationships(p)`: a part of a whole node,
    /// edge or path ([`crate::Entity`]).
    Whole(WholeFn, String),
    /// `count(*)`, `count([DISTINCT] x)`, `min(x)`, `max(x)`, `sum(x)`, `avg(x)` over the
    /// matches of each group (the rows equal on every item that is not an aggregate).
    Aggregate {
        /// The function.
        func: AggFn,
        /// `DISTINCT`: each value once.
        distinct: bool,
        /// The value; `None` for `count(*)`.
        arg: Option<Operand>,
    },
    /// `rank(x BY g, ..)`: per row, the number of distinct values of `x` before the row's
    /// own among the rows equal on every `g` (from 0, rising), a row kept per row (no group
    /// collapses); without `BY` all rows are one group.
    Rank {
        /// The value ordered.
        arg: Operand,
        /// The values that group.
        by: Vec<Operand>,
    },
}

/// A function of a whole node, edge or path.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WholeFn {
    /// `labels(n)`
    Labels,
    /// `type(r)`
    Type,
    /// `properties(n)` or `properties(r)`
    Properties,
    /// `relationships(p)`
    Relationships,
}

impl WholeFn {
    /// The function's name.
    pub fn name(self) -> &'static str {
        match self {
            WholeFn::Labels => "labels",
            WholeFn::Type => "type",
            WholeFn::Properties => "properties",
            WholeFn::Relationships => "relationships",
        }
    }
}

/// An aggregate function.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AggFn {
    /// `count`
    Count,
    /// `min`
    Min,
    /// `max`
    Max,
    /// `sum`
    Sum,
    /// `avg`
    Avg,
}

impl AggFn {
    /// The function's name, lower case.
    pub fn name(self) -> &'static str {
        match self {
            AggFn::Count => "count",
            AggFn::Min => "min",
            AggFn::Max => "max",
            AggFn::Sum => "sum",
            AggFn::Avg => "avg",
        }
    }
}

impl Operand {
    /// As written: `var`, `var.key`, the integer, `$name`.
    pub fn text(&self) -> String {
        match self {
            Operand::Var(v) => v.clone(),
            Operand::Prop(v, k) => match k.split_once('@') {
                Some((k, f)) => format!("{f}({v}.{k})"),
                None => format!("{v}.{k}"),
            },
            Operand::Int(i) => i.to_string(),
            Operand::Param(p) => format!("${p}"),
            Operand::Str(t) => format!("{t:?}"),
            Operand::Signed(i) => i.to_string(),
            Operand::Float(x) => format!("{:?}", x.0),
            Operand::Bool(b) => b.to_string().to_uppercase(),
            Operand::Null => "NULL".into(),
            Operand::Length(p) => format!("length({p})"),
            Operand::Id(n) => format!("id({n})"),
            Operand::EdgeRow(e) => format!("#row({e})"),
            Operand::Arith(a, op, b) => match bit_fn(*op) {
                Some(f) => format!("{f}({}, {})", a.text(), b.text()),
                None => format!("{} {} {}", a.text(), op.symbol(), b.text()),
            },
            Operand::Unary(UnOp::Neg, a) => format!("-{}", a.text()),
            Operand::Unary(_, a) => format!("bitnot({})", a.text()),
            Operand::Call(Func::Concat, args) => args
                .iter()
                .map(Operand::text)
                .collect::<Vec<_>>()
                .join(" || "),
            Operand::Call(f, args) => format!(
                "{}({})",
                if *f == Func::Len {
                    "char_length"
                } else {
                    "substring"
                },
                args.iter()
                    .map(Operand::text)
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        }
    }
}

impl ReturnItem {
    /// The column name: the alias, else as written (`var`, `var.key`, `count(*)`,
    /// `count(DISTINCT var)`, `min(var.key)`).
    pub fn name(&self) -> String {
        if let Some(a) = &self.alias {
            return a.clone();
        }
        match &self.value {
            ReturnValue::Value(o) => o.text(),
            ReturnValue::Length(p) => format!("length({p})"),
            ReturnValue::Nodes(p) => format!("nodes({p})"),
            ReturnValue::Whole(f, x) => format!("{}({x})", f.name()),
            ReturnValue::Path(p) => p.var.clone().unwrap_or_else(|| "path".into()),
            ReturnValue::Aggregate {
                func,
                distinct,
                arg,
            } => format!(
                "{}({}{})",
                func.name(),
                if *distinct { "DISTINCT " } else { "" },
                arg.as_ref().map_or("*".into(), Operand::text)
            ),
            ReturnValue::Rank { arg, by } if by.is_empty() => format!("rank({})", arg.text()),
            ReturnValue::Rank { arg, by } => {
                let by: Vec<String> = by.iter().map(Operand::text).collect();
                format!("rank({} BY {})", arg.text(), by.join(", "))
            }
        }
    }
}

/// `UNWIND list AS name`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Unwind {
    /// The list.
    pub list: UnwindList,
    /// The name each item binds.
    pub alias: String,
}

/// The list of an `UNWIND`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnwindList {
    /// `[v, ...]`: values, constants or expressions over bound values.
    Items(Vec<Operand>),
    /// `$name`: a list parameter ([`crate::Param::List`]).
    Param(String),
    /// `n.key`: list property `key` of a node bound before (`crate::Catalog::list_property`),
    /// one item per element.
    Prop(String, String),
    /// `e.key`: list property `key` of an edge of the `MATCH` before, between its nodes
    /// `from` and `to` (named by the parser when the query names them not), of one of
    /// `labels` (`crate::Catalog::list_edge_property`), one item per element.
    EdgeProp {
        /// The edge variable, for messages.
        edge: String,
        /// The node the edge goes from.
        from: String,
        /// The node the edge goes to.
        to: String,
        /// The edge's labels (one of them).
        labels: Vec<String>,
        /// The name of the edge's row passed on by the part before ([`Operand::EdgeRow`]):
        /// with one label that has rows, the list is read by row (`E@row.key`), so two
        /// edges between the same nodes keep their own lists.
        row: String,
        /// The property.
        key: String,
    },
}

/// The function a bit operator is written as (`None` for `+ - * / %`).
pub(crate) fn bit_fn(op: BinOp) -> Option<&'static str> {
    Some(match op {
        BinOp::And => "bitand",
        BinOp::Or => "bitor",
        BinOp::Xor => "bitxor",
        BinOp::Shl => "shiftleft",
        BinOp::Shr => "shiftright",
        _ => return None,
    })
}