Skip to main content

ursa_engine/graph/
pattern.rs

1//! SQL/PGQ pattern matching: `GRAPH_TABLE (g MATCH … COLUMNS (…))` (#296).
2//!
3//! Ursa's parser rewrites `GRAPH_TABLE ( body )` into `graph_table('body')`;
4//! the relation planner hands the body here. [`parse`] reads it into a
5//! [`Pattern`]; [`lower`] resolves each variable to one of the graph's element
6//! tables and says what to join: a [`Lowered`] match, which the planner
7//! builds as a logical plan (scans of the element tables, equality
8//! conditions, the pattern's conditions and `COLUMNS`). DataFusion's
9//! optimizer turns the equalities into hash joins.
10//!
11//! Supported:
12//!
13//! ```text
14//! GRAPH_TABLE ( graph
15//!   MATCH path [, path …]
16//!   [WHERE condition]
17//!   COLUMNS ( expression [AS name], … ) )
18//!
19//! path       := [var =] [selector] [mode [PATH | PATHS]] node (edge node)*
20//! selector   := ANY SHORTEST | ALL SHORTEST | ANY [k] | SHORTEST k | ALL
21//! mode       := WALK | TRAIL | SIMPLE | ACYCLIC
22//! node       := ( [var] [:label | IS label] [WHERE condition] )
23//! edge       := (-[ spec ]->  |  <-[ spec ]-  |  -[ spec ]-  |  ->  |  <-  |  -) [quantifier]
24//! quantifier := * | + | ? | {n} | {m,n} | {m,} | {,n}
25//! spec       := [var] [:label | IS label] [WHERE condition]
26//! ```
27//!
28//! Conditions and `COLUMNS` are SQL expressions over the variables
29//! (`a.name`); each variable is a relation of that name. A label names an element table: by its name or one of
30//! its labels. A variable without one gets the only table it can be: from the
31//! edges next to it and their `REFERENCES`, or because the graph has one table
32//! of that kind; otherwise the pattern is refused, never guessed.
33//!
34//! Each variable reads its element table's properties: every column, or what
35//! its labels' `PROPERTIES` clauses give, under their property names. An
36//! undirected edge `-[e]-` matches both orientations of each edge (a self-loop
37//! once): the match is a `UNION ALL` with one branch per orientation, so every
38//! join stays an equality join.
39//!
40//! A quantified edge, and the edge of a path with a path variable, a selector
41//! or a mode, is not joined: it is a [`Segment`], searched on the graph index
42//! (see [`super::path_search`]), and joined to the nodes at its ends. A path
43//! with a variable, a selector or a mode is one edge between two nodes for
44//! now. Label expressions (`|`, `&`, `!`) and parenthesized path patterns are
45//! refused with a message.
46//!
47//! ## Through the index
48//!
49//! A node is *bound* when a condition on it alone limits its key to values
50//! the query names: `a.id = 7`, `a.id IN (1, 2)` or `a.id IN (SELECT …)`.
51//! From a bound node, the fixed-length edges of its path are expanded
52//! through the graph index too, one [`Segment`] of exactly one edge each,
53//! outward from it: each segment starts from the keys the one before it
54//! reached ([`Starts::After`]), so only the edges at the nodes reached are
55//! read, never the whole edge table. A segment is a relation of edges as the
56//! join's is, one row per edge row, so the rows are the same. A node whose
57//! query reads only its key, at the end of a segment whose index's nodes are
58//! that node's table's keys, is not joined to its table at all: its key is
59//! the segment's column ([`Lowered::aliases`]). Edges stay joins when no node
60//! is bound, when the query reads an edge's columns, or when
61//! [`Usage::indexed`] does not list the edge table (its index could not be
62//! kept between queries).
63
64use std::collections::{BTreeMap, BTreeSet};
65
66use datafusion::arrow::datatypes::SchemaRef;
67use datafusion::common::TableReference;
68use datafusion::error::{DataFusionError, Result};
69use datafusion::sql::sqlparser::dialect::GenericDialect;
70use datafusion::sql::sqlparser::parser::Parser;
71use datafusion::sql::sqlparser::tokenizer::{Location, Token, TokenWithSpan, Tokenizer};
72
73use super::provenance::{self, PatternEdge};
74use super::{EdgeTable, Label, Properties, PropertyGraph, VertexTable};
75
76/// The table function Ursa's parser rewrites `GRAPH_TABLE ( … )` into.
77pub const FUNCTION: &str = "graph_table";
78
79/// Undirected edges allowed in one pattern: each doubles the query's branches.
80const MAX_UNDIRECTED: usize = 3;
81
82/// A parsed `GRAPH_TABLE` body.
83#[derive(Debug, Clone, PartialEq)]
84pub struct Pattern {
85    /// The graph's name, as written.
86    pub graph: String,
87    pub paths: Vec<PathPattern>,
88    /// The pattern's `WHERE` condition, as written.
89    pub condition: Option<String>,
90    /// The `COLUMNS` list, as written (without its parentheses).
91    pub columns: String,
92}
93
94/// One path of a `MATCH`: `[p =] [selector] [mode] (a)-[e]->…(b)`.
95#[derive(Debug, Clone, PartialEq)]
96pub struct PathPattern {
97    /// The path variable, `p` in `p = …`.
98    pub var: Option<String>,
99    pub selector: Selector,
100    pub mode: Mode,
101    /// Nodes and edges alternate, starting and ending with a node.
102    pub elements: Vec<Element>,
103}
104
105/// Which of a pair of nodes' paths a path keeps.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd)]
107pub enum Selector {
108    /// No selector (or `ALL`): every path.
109    All,
110    /// `ANY SHORTEST`, `ANY`, `ANY k` and `SHORTEST k`: the `k` shortest
111    /// paths, the first by edge row among paths as short (see [`super::path_search`]).
112    Shortest(u32),
113    /// `ALL SHORTEST`: every path as short as the shortest.
114    AllShortest,
115}
116
117/// Which walks a path may be (SQL/PGQ's path modes).
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd)]
119pub enum Mode {
120    /// Any walk: nodes and edges may repeat (the default).
121    Walk,
122    /// No edge twice.
123    Trail,
124    /// No node twice, except that the last may be the first.
125    Simple,
126    /// No node twice.
127    Acyclic,
128}
129
130/// An edge's quantifier: how many times it repeats, `{min,max}`.
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd)]
132pub struct Quantifier {
133    pub min: u32,
134    /// `None`: no upper bound.
135    pub max: Option<u32>,
136}
137
138impl Quantifier {
139    /// An edge without a quantifier: exactly once.
140    pub const ONCE: Quantifier = Quantifier {
141        min: 1,
142        max: Some(1),
143    };
144}
145
146/// One element of a path: nodes and edges alternate, starting with a node.
147#[derive(Debug, Clone, PartialEq)]
148pub enum Element {
149    Node(Spec),
150    /// An edge, with its quantifier if it has one.
151    Edge(Spec, Direction, Option<Quantifier>),
152}
153
154/// A node or edge: `[var] [:label] [WHERE condition]`.
155#[derive(Debug, Clone, PartialEq, Default)]
156pub struct Spec {
157    pub var: Option<String>,
158    pub label: Option<String>,
159    pub condition: Option<String>,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd)]
163pub enum Direction {
164    /// `-[e]->`: from the node on the left to the node on the right.
165    Right,
166    /// `<-[e]-`: from the node on the right to the node on the left.
167    Left,
168    /// `-[e]-`: either way.
169    Any,
170}
171
172fn pattern_err<T>(message: impl Into<String>) -> Result<T> {
173    Err(DataFusionError::Plan(format!(
174        "in GRAPH_TABLE: {}",
175        message.into()
176    )))
177}
178
179/// The body's tokens, without whitespace and comments, with their byte ranges.
180struct Tokens<'a> {
181    text: &'a str,
182    tokens: Vec<(Token, usize, usize)>,
183    at: usize,
184}
185
186impl<'a> Tokens<'a> {
187    fn new(text: &'a str) -> Result<Self> {
188        let tokens = Tokenizer::new(&GenericDialect {}, text)
189            .tokenize_with_location()
190            .map_err(|e| DataFusionError::Plan(format!("in GRAPH_TABLE: {e}")))?;
191        let tokens = tokens
192            .into_iter()
193            .filter(|t| !matches!(t.token, Token::Whitespace(_)))
194            .map(|TokenWithSpan { token, span }| {
195                let start = offset(text, span.start).unwrap_or(text.len());
196                let end = offset(text, span.end).unwrap_or(text.len());
197                (token, start, end)
198            })
199            .filter(|(token, _, _)| *token != Token::EOF)
200            .collect();
201        Ok(Self {
202            text,
203            tokens,
204            at: 0,
205        })
206    }
207
208    fn peek(&self, n: usize) -> Option<&Token> {
209        self.tokens.get(self.at + n).map(|(t, _, _)| t)
210    }
211
212    fn next(&mut self) -> Option<Token> {
213        let token = self.tokens.get(self.at).map(|(t, _, _)| t.clone());
214        self.at += 1;
215        token
216    }
217
218    fn is_word(&self, n: usize, word: &str) -> bool {
219        matches!(self.peek(n), Some(Token::Word(w)) if w.quote_style.is_none() && w.value.eq_ignore_ascii_case(word))
220    }
221
222    /// Whether a `KEEP` or `ONE ROW PER` clause starts at the next token: the
223    /// word, not a property of that name (`a.keep`).
224    fn starts_clause(&self) -> bool {
225        let after_period = self.at > 0 && self.tokens[self.at - 1].0 == Token::Period;
226        !after_period
227            && (self.is_word(0, "KEEP") || (self.is_word(0, "ONE") && self.is_word(1, "ROW")))
228    }
229
230    /// The text of token `i`, as written.
231    fn raw(&self, i: usize) -> &'a str {
232        match self.tokens.get(i) {
233            Some((_, start, end)) => &self.text[*start..*end],
234            None => "",
235        }
236    }
237
238    fn eat(&mut self, token: &Token) -> bool {
239        if self.peek(0) == Some(token) {
240            self.at += 1;
241            true
242        } else {
243            false
244        }
245    }
246
247    /// What the next token is, for an error: "'x' (at character 12)" or "the end".
248    fn found(&self) -> String {
249        match self.tokens.get(self.at) {
250            Some((token, start, _)) => {
251                format!("'{token}' (at character {} of the pattern)", start + 1)
252            }
253            None => "the end".to_string(),
254        }
255    }
256
257    fn expect(&mut self, token: &Token, what: &str) -> Result<()> {
258        if self.eat(token) {
259            Ok(())
260        } else {
261            pattern_err(format!("expected {what}, found {}", self.found()))
262        }
263    }
264
265    /// An identifier: an unquoted word (normalized as DataFusion normalizes
266    /// identifiers: lower-cased) or a quoted one (kept).
267    fn identifier(&mut self, what: &str) -> Result<String> {
268        match self.peek(0) {
269            Some(Token::Word(w)) => {
270                let name = match w.quote_style {
271                    Some(_) => w.value.clone(),
272                    None => w.value.to_lowercase(),
273                };
274                self.at += 1;
275                Ok(name)
276            }
277            _ => pattern_err(format!("expected {what}, found {}", self.found())),
278        }
279    }
280
281    /// The text from the current token up to (not including) the first token
282    /// at bracket depth 0 for which `stop` holds; the tokens are consumed.
283    fn text_until(&mut self, stop: impl Fn(&Self, usize) -> bool) -> Option<String> {
284        let start = self.at;
285        let mut depth = 0i32;
286        while self.at < self.tokens.len() {
287            let token = &self.tokens[self.at].0;
288            if depth == 0 && stop(self, 0) {
289                break;
290            }
291            match token {
292                Token::LParen | Token::LBracket => depth += 1,
293                Token::RParen | Token::RBracket => {
294                    if depth == 0 {
295                        break;
296                    }
297                    depth -= 1;
298                }
299                _ => {}
300            }
301            self.at += 1;
302        }
303        if self.at == start {
304            return None;
305        }
306        let from = self.tokens[start].1;
307        let to = self.tokens[self.at - 1].2;
308        Some(self.text[from..to].trim().to_string())
309    }
310
311    /// [`Self::text_until`], for text that is SQL: a condition or the
312    /// `COLUMNS` list. Text left over after it is an error (#409): SQL's
313    /// parser stops at the first token it cannot use, so `WHERE a.id = 0
314    /// b.id = 3` would otherwise run as `WHERE a.id = 0`.
315    fn sql_until(
316        &mut self,
317        sql: Sql,
318        stop: impl Fn(&Self, usize) -> bool,
319    ) -> Result<Option<String>> {
320        let from = self.tokens.get(self.at).map(|(_, start, _)| *start);
321        let text = self
322            .text_until(stop)
323            .map(|t| graph_predicates(&t))
324            .transpose()?;
325        if let (Some(text), Some(from)) = (&text, from) {
326            check_sql(text, from, sql)?;
327        }
328        Ok(text)
329    }
330}
331
332/// The function `x IS [NOT] LABELED l` is rewritten to, as
333/// `__ursa_is_labeled(x, 'l')`; the planner replaces it with `TRUE` or
334/// `FALSE` once it knows `x`'s table.
335pub const IS_LABELED: &str = "__ursa_is_labeled";
336/// The function `a IS [NOT] SOURCE OF e` is rewritten to.
337pub const IS_SOURCE: &str = "__ursa_is_source";
338/// The function `a IS [NOT] DESTINATION OF e` is rewritten to.
339pub const IS_DESTINATION: &str = "__ursa_is_destination";
340
341/// `text`, a condition or `COLUMNS` list, with SQL/PGQ's predicates that SQL
342/// cannot parse rewritten to function calls: `x IS [NOT] LABELED l`, `a IS
343/// [NOT] SOURCE OF e` and `a IS [NOT] DESTINATION OF e`. The planner
344/// replaces the calls, as it does `SAME` and `ALL_DIFFERENT`.
345fn graph_predicates(text: &str) -> Result<String> {
346    let Ok(tokens) = Tokenizer::new(&GenericDialect {}, text).tokenize_with_location() else {
347        return Ok(text.to_string());
348    };
349    let tokens: Vec<(Token, usize, usize)> = tokens
350        .into_iter()
351        .filter(|t| !matches!(t.token, Token::Whitespace(_) | Token::EOF))
352        .filter_map(|TokenWithSpan { token, span }| {
353            Some((token, offset(text, span.start)?, offset(text, span.end)?))
354        })
355        .collect();
356    let word = |i: usize, w: &str| matches!(tokens.get(i), Some((Token::Word(x), _, _)) if x.quote_style.is_none() && x.value.eq_ignore_ascii_case(w));
357    let name = |i: usize| match tokens.get(i) {
358        Some((Token::Word(w), start, end)) => Some((w, &text[*start..*end])),
359        _ => None,
360    };
361    let mut out = String::new();
362    let mut copied = 0;
363    let mut i = 0;
364    while i < tokens.len() {
365        let variable = name(i).filter(|_| i == 0 || tokens[i - 1].0 != Token::Period);
366        let (Some((_, var)), true) = (variable, word(i + 1, "IS")) else {
367            i += 1;
368            continue;
369        };
370        let mut j = i + 2;
371        let negated = word(j, "NOT");
372        if negated {
373            j += 1;
374        }
375        let call = if word(j, "LABELED") {
376            let Some((label, _)) = name(j + 1) else {
377                return pattern_err(format!(
378                    "{var} IS LABELED needs a label, as {var} IS LABELED person"
379                ));
380            };
381            if matches!(
382                tokens.get(j + 2).map(|t| &t.0),
383                Some(Token::Pipe | Token::Ampersand | Token::ExclamationMark | Token::Mod)
384            ) {
385                return pattern_err(LABEL_EXPRESSIONS);
386            }
387            let label = match label.quote_style {
388                Some(_) => label.value.clone(),
389                None => label.value.to_lowercase(),
390            };
391            j += 2;
392            format!("{IS_LABELED}({var}, '{}')", label.replace('\'', "''"))
393        } else if (word(j, "SOURCE") || word(j, "DESTINATION")) && word(j + 1, "OF") {
394            let function = match word(j, "SOURCE") {
395                true => IS_SOURCE,
396                false => IS_DESTINATION,
397            };
398            let Some((_, edge)) = name(j + 2) else {
399                return pattern_err(format!(
400                    "IS SOURCE OF and IS DESTINATION OF take an edge variable, as {var} IS SOURCE OF e"
401                ));
402            };
403            j += 3;
404            format!("{function}({var}, {edge})")
405        } else {
406            i += 1;
407            continue;
408        };
409        out.push_str(&text[copied..tokens[i].1]);
410        match negated {
411            true => out.push_str(&format!("(NOT {call})")),
412            false => out.push_str(&call),
413        }
414        copied = tokens[j - 1].2;
415        i = j;
416    }
417    out.push_str(&text[copied..]);
418    Ok(out)
419}
420
421/// The refusal of a label expression (#412).
422const LABEL_EXPRESSIONS: &str =
423    "label expressions (|, &, !, %) are not supported yet; use one label (#412)";
424
425/// What a piece of a pattern's text is, as SQL.
426#[derive(Clone, Copy)]
427enum Sql {
428    /// A `WHERE` condition: one expression.
429    Condition,
430    /// The `COLUMNS` list: select items.
431    Columns,
432}
433
434/// Refuse `text`, which starts at byte `from` of the pattern, when it is
435/// `sql` followed by something else. A syntax error in the SQL itself is
436/// left to the planner, which reports it when it parses the text.
437fn check_sql(text: &str, from: usize, sql: Sql) -> Result<()> {
438    let Ok(mut parser) = Parser::new(&GenericDialect {}).try_with_sql(text) else {
439        return Ok(());
440    };
441    let parsed = match sql {
442        Sql::Condition => parser.parse_expr().is_ok(),
443        Sql::Columns => parser
444            .parse_comma_separated(Parser::parse_select_item)
445            .is_ok(),
446    };
447    if !parsed {
448        return Ok(());
449    }
450    let next = parser.peek_token();
451    if next.token == Token::EOF {
452        return Ok(());
453    }
454    if let Some(clause) = unsupported_clause(&next.token, &parser.peek_nth_token(1).token) {
455        return pattern_err(clause);
456    }
457    let read = offset(text, next.span.start).unwrap_or(text.len());
458    let (after, hint) = match sql {
459        Sql::Condition => ("the WHERE condition", "join conditions with AND or OR"),
460        Sql::Columns => ("the COLUMNS item", "separate items with commas"),
461    };
462    pattern_err(format!(
463        "unexpected '{}' (at character {} of the pattern) after {after} '{}'; {hint}",
464        next.token,
465        from + read + 1,
466        text[..read].trim_end()
467    ))
468}
469
470/// The refusal of a pattern clause written where it does not go, if `token`
471/// (and the token after it, `next`) starts one: `KEEP …` or `ONE ROW PER …`
472/// inside a node or an edge, or in `COLUMNS`.
473fn unsupported_clause(token: &Token, next: &Token) -> Option<&'static str> {
474    let is = |token: &Token, word: &str| matches!(token, Token::Word(w) if w.quote_style.is_none() && w.value.eq_ignore_ascii_case(word));
475    if is(token, "KEEP") {
476        Some(
477            "KEEP goes after the whole pattern, before WHERE and COLUMNS, as MATCH (a)-[e]->*(b) KEEP ANY SHORTEST WHERE a.id = 0",
478        )
479    } else if is(token, "ONE") && is(next, "ROW") {
480        Some(
481            "ONE ROW PER goes after the pattern and its WHERE, before COLUMNS, as MATCH (a)-[e]->(b) ONE ROW PER MATCH COLUMNS (a.id)",
482        )
483    } else {
484        None
485    }
486}
487
488/// The byte offset of a tokenizer location in `text`.
489fn offset(text: &str, at: Location) -> Option<usize> {
490    if at.line == 0 || at.column == 0 {
491        return None;
492    }
493    let mut line_start = 0;
494    for _ in 1..at.line {
495        line_start += text[line_start..].find('\n')? + 1;
496    }
497    let column = usize::try_from(at.column - 1).ok()?;
498    let line = &text[line_start..];
499    match line.char_indices().nth(column) {
500        Some((o, _)) => Some(line_start + o),
501        None if line.chars().count() == column => Some(text.len()),
502        None => None,
503    }
504}
505
506/// Parse a `GRAPH_TABLE` body: `graph MATCH … [WHERE …] COLUMNS (…)`.
507pub fn parse(body: &str) -> Result<Pattern> {
508    let mut t = Tokens::new(body)?;
509    let graph = t.identifier("the graph's name")?;
510    if !t.is_word(0, "MATCH") {
511        return pattern_err(format!(
512            "expected MATCH after the graph's name, found {}",
513            t.found()
514        ));
515    }
516    t.next();
517    let mut paths = vec![parse_path(&mut t)?];
518    while t.eat(&Token::Comma) {
519        paths.push(parse_path(&mut t)?);
520    }
521    // KEEP, WHERE and ONE ROW PER, each at most once. The standard puts them
522    // in that order; another order is read the same.
523    let mut condition = None;
524    let mut keep: Option<(Selector, Mode)> = None;
525    let mut rows = false;
526    loop {
527        if t.is_word(0, "WHERE") {
528            if condition.is_some() {
529                return pattern_err("a pattern takes one WHERE; join its conditions with AND");
530            }
531            t.next();
532            condition = t.sql_until(Sql::Condition, |t, _| {
533                t.is_word(0, "COLUMNS") || t.starts_clause()
534            })?;
535            if condition.is_none() {
536                return pattern_err("WHERE needs a condition");
537            }
538        } else if t.is_word(0, "KEEP") {
539            if keep.is_some() {
540                return pattern_err("a pattern takes one KEEP");
541            }
542            t.next();
543            let before = t.at;
544            let prefix = parse_prefix(&mut t)?;
545            if t.at == before {
546                return pattern_err(format!(
547                    "KEEP takes a path selector or path mode, as KEEP ANY SHORTEST or KEEP TRAIL; found {}",
548                    t.found()
549                ));
550            }
551            keep = Some(prefix);
552        } else if t.is_word(0, "ONE") && t.is_word(1, "ROW") {
553            if rows {
554                return pattern_err("a pattern takes one ONE ROW PER clause");
555            }
556            t.next();
557            t.next();
558            if !t.is_word(0, "PER") {
559                return pattern_err(format!("expected PER after ONE ROW, found {}", t.found()));
560            }
561            t.next();
562            if t.is_word(0, "VERTEX") || t.is_word(0, "STEP") {
563                return pattern_err(ONE_ROW_PER_VERTEX);
564            }
565            if !t.is_word(0, "MATCH") {
566                return pattern_err(format!(
567                    "expected MATCH, VERTEX or STEP after ONE ROW PER, found {}",
568                    t.found()
569                ));
570            }
571            t.next();
572            rows = true;
573        } else {
574            break;
575        }
576    }
577    if let Some((selector, mode)) = keep {
578        let [path] = paths.as_mut_slice() else {
579            return pattern_err(
580                "KEEP over several path patterns is not supported yet; put the selector or path mode before each path, as MATCH ANY SHORTEST (a)-[e]->*(b), TRAIL (c)-[f]->*(d)",
581            );
582        };
583        if (selector != Selector::All && path.selector != Selector::All)
584            || (mode != Mode::Walk && path.mode != Mode::Walk)
585        {
586            return pattern_err(
587                "the path has a selector or path mode both before it and in KEEP; write it once",
588            );
589        }
590        if selector != Selector::All {
591            path.selector = selector;
592        }
593        if mode != Mode::Walk {
594            path.mode = mode;
595        }
596    }
597    let columns = if t.is_word(0, "COLUMNS") {
598        t.next();
599        t.expect(&Token::LParen, "'(' after COLUMNS")?;
600        let Some(columns) = t.sql_until(Sql::Columns, |_, _| false)? else {
601            return pattern_err("COLUMNS (…) lists nothing");
602        };
603        t.expect(&Token::RParen, "')' to close COLUMNS")?;
604        if t.peek(0).is_some() {
605            return pattern_err(format!("unexpected {} after COLUMNS (…)", t.found()));
606        }
607        match columns.as_str() {
608            "*" => all_properties(&paths, "COLUMNS (*)")?,
609            _ => columns,
610        }
611    } else if t.peek(0).is_none() {
612        all_properties(&paths, "a GRAPH_TABLE without COLUMNS")?
613    } else {
614        if let Some(token) = t.peek(0) {
615            if let Some(clause) = unsupported_clause(token, t.peek(1).unwrap_or(&Token::EOF)) {
616                return pattern_err(clause);
617            }
618        }
619        return pattern_err(format!(
620            "expected ',', WHERE or COLUMNS after the pattern, found {}",
621            t.found()
622        ));
623    };
624    Ok(Pattern {
625        graph,
626        paths,
627        condition,
628        columns,
629    })
630}
631
632/// The refusal of `ONE ROW PER VERTEX` and `ONE ROW PER STEP`.
633const ONE_ROW_PER_VERTEX: &str = "ONE ROW PER VERTEX and ONE ROW PER STEP are not supported yet; return vertices(p) or edges(p) in COLUMNS and unnest them";
634
635/// `COLUMNS (*)`, and `COLUMNS` left out: every property of each named node
636/// and edge, in the order they first appear (`a.*, k.*, b.*`). An edge that
637/// stands for several edges (quantified, or in a path searched as a whole)
638/// has no properties to return, so it is left out. `what` names the form,
639/// for the error when nothing is named.
640fn all_properties(paths: &[PathPattern], what: &str) -> Result<String> {
641    let mut vars: Vec<&str> = Vec::new();
642    for path in paths {
643        let whole = path.var.is_some() || path.selector != Selector::All || path.mode != Mode::Walk;
644        for element in &path.elements {
645            let var = match element {
646                Element::Node(spec) => spec.var.as_deref(),
647                Element::Edge(spec, _, quantifier) => match whole || quantifier.is_some() {
648                    true => None,
649                    false => spec.var.as_deref(),
650                },
651            };
652            if let Some(var) = var {
653                if !vars.contains(&var) {
654                    vars.push(var);
655                }
656            }
657        }
658    }
659    if vars.is_empty() {
660        return pattern_err(format!(
661            "{what} returns the properties of the pattern's named nodes and edges, and it names none; name one, as (a:person), or list what to return, as COLUMNS (a.id)"
662        ));
663    }
664    Ok(vars
665        .iter()
666        .map(|v| format!("\"{}\".*", v.replace('"', "\"\"")))
667        .collect::<Vec<_>>()
668        .join(", "))
669}
670
671/// A path: `[p =] [selector] [mode [PATH | PATHS]]`, then a node, then edges
672/// and nodes.
673fn parse_path(t: &mut Tokens) -> Result<PathPattern> {
674    let var = if matches!(t.peek(0), Some(Token::Word(_))) && t.peek(1) == Some(&Token::Eq) {
675        let var = t.identifier("a path variable")?;
676        t.next();
677        Some(var)
678    } else {
679        None
680    };
681    let (selector, mode) = parse_prefix(t)?;
682    if t.peek(0) == Some(&Token::LParen) && t.peek(1) == Some(&Token::LParen) {
683        return pattern_err(
684            "parenthesized path patterns, as ((a)-[e]->(b))*, are not supported yet; quantify an edge instead, as (a)-[e]->*(b)",
685        );
686    }
687    let mut elements = vec![Element::Node(parse_node(t)?)];
688    while let Some((spec, direction, quantifier)) = parse_edge(t)? {
689        elements.push(Element::Edge(spec, direction, quantifier));
690        elements.push(Element::Node(parse_node(t)?));
691    }
692    Ok(PathPattern {
693        var,
694        selector,
695        mode,
696        elements,
697    })
698}
699
700/// A path's prefix, `[selector] [mode] [PATH | PATHS]`, every part optional;
701/// also what `KEEP` takes.
702fn parse_prefix(t: &mut Tokens) -> Result<(Selector, Mode)> {
703    let selector = parse_selector(t)?;
704    let mode = if t.is_word(0, "WALK") {
705        Some(Mode::Walk)
706    } else if t.is_word(0, "TRAIL") {
707        Some(Mode::Trail)
708    } else if t.is_word(0, "SIMPLE") {
709        Some(Mode::Simple)
710    } else if t.is_word(0, "ACYCLIC") {
711        Some(Mode::Acyclic)
712    } else {
713        None
714    };
715    if mode.is_some() {
716        t.next();
717    }
718    if t.is_word(0, "PATH") || t.is_word(0, "PATHS") {
719        t.next();
720    }
721    Ok((selector, mode.unwrap_or(Mode::Walk)))
722}
723
724/// `ANY SHORTEST`, `ALL SHORTEST`, `ANY [k]`, `SHORTEST k`, `ALL`, or none.
725fn parse_selector(t: &mut Tokens) -> Result<Selector> {
726    let count = |t: &mut Tokens, what: &str| -> Result<Option<u32>> {
727        let Some(Token::Number(n, _)) = t.peek(0) else {
728            return Ok(None);
729        };
730        let k = n.parse::<u32>().ok().filter(|&k| k > 0).ok_or_else(|| {
731            DataFusionError::Plan(format!(
732                "in GRAPH_TABLE: {what} takes a whole number of paths above 0; got {n}"
733            ))
734        })?;
735        t.next();
736        Ok(Some(k))
737    };
738    if t.is_word(0, "ANY") && t.is_word(1, "SHORTEST") {
739        t.next();
740        t.next();
741        if matches!(t.peek(0), Some(Token::Number(..))) {
742            return pattern_err(
743                "ANY SHORTEST keeps one path; for several, write SHORTEST k, as SHORTEST 3",
744            );
745        }
746        return Ok(Selector::Shortest(1));
747    }
748    if t.is_word(0, "ALL") && t.is_word(1, "SHORTEST") {
749        t.next();
750        t.next();
751        return Ok(Selector::AllShortest);
752    }
753    if t.is_word(0, "ANY") {
754        t.next();
755        return Ok(Selector::Shortest(count(t, "ANY")?.unwrap_or(1)));
756    }
757    if t.is_word(0, "SHORTEST") {
758        t.next();
759        let Some(k) = count(t, "SHORTEST")? else {
760            return pattern_err(format!(
761                "SHORTEST takes a number of paths, as SHORTEST 3; found {}",
762                t.found()
763            ));
764        };
765        if t.is_word(0, "GROUP") || t.is_word(0, "GROUPS") {
766            return pattern_err(
767                "SHORTEST k GROUP is not supported yet; use SHORTEST k or ALL SHORTEST",
768            );
769        }
770        return Ok(Selector::Shortest(k));
771    }
772    if t.is_word(0, "ALL") {
773        t.next();
774    }
775    Ok(Selector::All)
776}
777
778fn parse_node(t: &mut Tokens) -> Result<Spec> {
779    t.expect(&Token::LParen, "'(' to start a node")?;
780    let spec = parse_spec(t, None)?;
781    t.expect(&Token::RParen, "')' to close the node")?;
782    Ok(spec)
783}
784
785/// `[var] [:label | IS label] [WHERE condition]`, up to `close`.
786/// `edge` is the edge's opening, `-` or `<-`, for an edge (closed by `]`);
787/// `None` for a node (closed by `)`).
788fn parse_spec(t: &mut Tokens, edge: Option<&str>) -> Result<Spec> {
789    let close = &match edge {
790        Some(_) => Token::RBracket,
791        None => Token::RParen,
792    };
793    let start = t.at;
794    let mut spec = Spec::default();
795    if matches!(t.peek(0), Some(Token::Word(_))) && !t.is_word(0, "WHERE") && !t.is_word(0, "IS") {
796        spec.var = Some(t.identifier("a variable")?);
797    }
798    if t.eat(&Token::Colon) || (t.is_word(0, "IS") && t.next().is_some()) {
799        spec.label = Some(t.identifier("a label")?);
800        if matches!(
801            t.peek(0),
802            Some(Token::Pipe | Token::Ampersand | Token::ExclamationMark | Token::Mod)
803        ) {
804            return pattern_err(LABEL_EXPRESSIONS);
805        }
806    }
807    // Cypher habits: a property map, and a range inside an edge's brackets.
808    let written = |t: &Tokens| {
809        let last = t.at.checked_sub(1).and_then(|i| t.tokens.get(i));
810        match (start < t.at, t.tokens.get(start), last) {
811            (true, Some((_, from, _)), Some((_, _, to))) => t.text[*from..*to].to_string(),
812            _ => String::new(),
813        }
814    };
815    if t.peek(0) == Some(&Token::LBrace) {
816        return pattern_err(property_map(t, &spec, &written(t), edge));
817    }
818    if let (Some(open), Some(Token::Mul)) = (edge, t.peek(0)) {
819        return pattern_err(cypher_range(t, &written(t), open));
820    }
821    if t.is_word(0, "WHERE") {
822        t.next();
823        let close = close.clone();
824        spec.condition = t.sql_until(Sql::Condition, move |t, n| t.peek(n) == Some(&close))?;
825        if spec.condition.is_none() {
826            return pattern_err("WHERE needs a condition");
827        }
828    }
829    if t.peek(0) != Some(close) {
830        return pattern_err(format!(
831            "expected a variable, ':label', WHERE or '{close}', found {}",
832            t.found()
833        ));
834    }
835    Ok(spec)
836}
837
838/// The refusal of a Cypher property map, `(a:Person {name: 'Daniel'})`, at
839/// the `{`: with the condition to write instead, when the map is simple.
840/// `written` is the spec's text before the map; `edge`, the edge's opening.
841fn property_map(t: &Tokens, spec: &Spec, written: &str, edge: Option<&str>) -> String {
842    let var = spec
843        .var
844        .clone()
845        .unwrap_or_else(|| if edge.is_some() { "e" } else { "a" }.to_string());
846    let head = match spec.var {
847        Some(_) => written.trim().to_string(),
848        None => format!("{var}{}", written.trim()),
849    };
850    // The entries, `key: value`, up to the `}` that closes the map.
851    let mut conditions = Vec::new();
852    let mut i = t.at + 1;
853    let simple = loop {
854        let (Some(Token::Word(_)), Some(Token::Colon)) = (
855            t.tokens.get(i).map(|x| &x.0),
856            t.tokens.get(i + 1).map(|x| &x.0),
857        ) else {
858            break false;
859        };
860        let key = t.raw(i);
861        let from = i + 2;
862        let mut depth = 0i32;
863        let mut j = from;
864        while let Some((token, _, _)) = t.tokens.get(j) {
865            match token {
866                Token::LParen | Token::LBracket | Token::LBrace => depth += 1,
867                Token::RParen | Token::RBracket => depth -= 1,
868                Token::RBrace if depth > 0 => depth -= 1,
869                Token::RBrace | Token::Comma if depth == 0 => break,
870                _ => {}
871            }
872            j += 1;
873        }
874        if j == from || j >= t.tokens.len() {
875            break false;
876        }
877        let value = &t.text[t.tokens[from].1..t.tokens[j - 1].2];
878        conditions.push(format!("{var}.{key} = {value}"));
879        if t.tokens[j].0 == Token::RBrace {
880            break true;
881        }
882        i = j + 1;
883    };
884    let (open, close) = match edge {
885        Some(_) => ("[", "]"),
886        None => ("(", ")"),
887    };
888    let example = match simple && !conditions.is_empty() {
889        true => format!("{open}{head} WHERE {}{close}", conditions.join(" AND ")),
890        false => format!("{open}{head} WHERE {var}.name = 'Daniel'{close}"),
891    };
892    format!("property maps ({{…}}) are Cypher; write the condition with WHERE, as {example}")
893}
894
895/// The refusal of a Cypher range inside an edge's brackets,
896/// `-[k:knows*1..3]->`, at the `*`: with the quantifier to write after the
897/// edge instead. `written` is the spec's text before the `*`; `open`, the
898/// edge's opening.
899fn cypher_range(t: &Tokens, written: &str, open: &str) -> String {
900    // The range's text, up to the `]`.
901    let mut j = t.at;
902    while j < t.tokens.len() && t.tokens[j].0 != Token::RBracket {
903        j += 1;
904    }
905    let close = match t.tokens.get(j + 1).map(|x| &x.0) {
906        Some(Token::Arrow) => "->",
907        _ if open == "<-" => "-",
908        _ => "-",
909    };
910    let range: String = match j > t.at {
911        true => t.text[t.tokens[t.at].1..t.tokens[j - 1].2]
912            .chars()
913            .filter(|c| !c.is_whitespace())
914            .collect(),
915        false => "*".to_string(),
916    };
917    let bounds = range.trim_start_matches('*');
918    // Cypher's `*` is one or more edges; `*n` exactly n; `*m..n` m to n.
919    let quantifier = match bounds.split_once("..") {
920        None if bounds.is_empty() => Some("+".to_string()),
921        None => bounds.parse::<u32>().ok().map(|n| format!("{{{n}}}")),
922        Some((m, n)) => {
923            let m = match m {
924                "" => Some(1),
925                m => m.parse::<u32>().ok(),
926            };
927            let n = match n {
928                "" => Some(None),
929                n => n.parse::<u32>().ok().map(Some),
930            };
931            match (m, n) {
932                (Some(m), Some(Some(n))) => Some(format!("{{{m},{n}}}")),
933                (Some(m), Some(None)) => Some(format!("{{{m},}}")),
934                _ => None,
935            }
936        }
937    };
938    let quantifier = quantifier.unwrap_or_else(|| "{1,3}".to_string());
939    format!(
940        "{range} inside an edge's brackets is Cypher's range; in SQL/PGQ the quantifier follows the edge: write {open}[{}]{close}{quantifier}",
941        written.trim()
942    )
943}
944
945/// The refusal of an undirected edge written with `~`.
946const TILDE_EDGES: &str =
947    "Ursa's edges are directed; use -[e]- to follow them either way (~[e]~, <~[e]~, ~[e]~> and ~ are for undirected edges)";
948
949/// An edge, if one is next: `-[…]->`, `<-[…]-`, `-[…]-`, `<-[…]->`, `->`,
950/// `<-`, `-` or `<->`, and its quantifier, if it has one. `<-[…]->` and
951/// `<->` are "left or right": every edge of an Ursa graph is directed, so
952/// they mean `-[…]-` and `-`. Edges written with `~` (undirected) are
953/// refused.
954fn parse_edge(t: &mut Tokens) -> Result<Option<(Spec, Direction, Option<Quantifier>)>> {
955    let edge = match (t.peek(0), t.peek(1)) {
956        // Abbreviated edges.
957        (Some(Token::Arrow), _) => {
958            t.next();
959            (Spec::default(), Direction::Right)
960        }
961        (Some(Token::TwoWayArrow), _) => {
962            t.next();
963            (Spec::default(), Direction::Any)
964        }
965        (Some(Token::Lt), Some(Token::Arrow)) => {
966            t.next();
967            t.next();
968            (Spec::default(), Direction::Any)
969        }
970        (Some(Token::Lt), Some(Token::Minus)) if t.peek(2) != Some(&Token::LBracket) => {
971            t.next();
972            t.next();
973            if t.eat(&Token::Gt) {
974                (Spec::default(), Direction::Any)
975            } else {
976                (Spec::default(), Direction::Left)
977            }
978        }
979        (Some(Token::Tilde), _) | (Some(Token::Lt), Some(Token::Tilde)) => {
980            return pattern_err(TILDE_EDGES)
981        }
982        (Some(Token::Minus), Some(Token::LBracket)) => {
983            t.next();
984            t.next();
985            let spec = parse_spec(t, Some("-"))?;
986            t.expect(&Token::RBracket, "']' to close the edge")?;
987            let direction = match t.next() {
988                Some(Token::Arrow) => Direction::Right,
989                // `- >`, as DuckPGQ also reads it.
990                Some(Token::Minus) if t.peek(0) == Some(&Token::Gt) => {
991                    t.next();
992                    Direction::Right
993                }
994                Some(Token::Minus) => Direction::Any,
995                Some(Token::LongArrow) => {
996                    return pattern_err("expected '->' or '-' after ']', found '->>'")
997                }
998                Some(Token::Tilde) => return pattern_err(TILDE_EDGES),
999                _ => {
1000                    t.at -= 1;
1001                    return pattern_err(format!(
1002                        "expected '->' or '-' after ']', found {}",
1003                        t.found()
1004                    ));
1005                }
1006            };
1007            (spec, direction)
1008        }
1009        (Some(Token::Lt), Some(Token::Minus)) => {
1010            t.next();
1011            t.next();
1012            t.expect(&Token::LBracket, "'[' after '<-'")?;
1013            let spec = parse_spec(t, Some("<-"))?;
1014            t.expect(&Token::RBracket, "']' to close the edge")?;
1015            let direction = match t.next() {
1016                // `<-[e]->`: left or right.
1017                Some(Token::Arrow) => Direction::Any,
1018                Some(Token::Minus) if t.eat(&Token::Gt) => Direction::Any,
1019                Some(Token::Minus) => Direction::Left,
1020                Some(Token::Tilde) => return pattern_err(TILDE_EDGES),
1021                _ => {
1022                    t.at -= 1;
1023                    return pattern_err(format!(
1024                        "expected '-' or '->' after ']', found {}",
1025                        t.found()
1026                    ));
1027                }
1028            };
1029            (spec, direction)
1030        }
1031        (Some(Token::Minus), _) => {
1032            t.next();
1033            (Spec::default(), Direction::Any)
1034        }
1035        _ => return Ok(None),
1036    };
1037    let quantifier = parse_quantifier(t)?;
1038    Ok(Some((edge.0, edge.1, quantifier)))
1039}
1040
1041/// `*`, `+`, `?`, `{n}`, `{m,n}`, `{m,}`, `{,n}` or `{,}`, if one is next.
1042fn parse_quantifier(t: &mut Tokens) -> Result<Option<Quantifier>> {
1043    let q = |min, max| Ok(Some(Quantifier { min, max }));
1044    match t.peek(0) {
1045        Some(Token::Mul) => {
1046            t.next();
1047            q(0, None)
1048        }
1049        Some(Token::Plus) => {
1050            t.next();
1051            q(1, None)
1052        }
1053        Some(Token::Placeholder(p)) if p == "?" => {
1054            t.next();
1055            q(0, Some(1))
1056        }
1057        Some(Token::LBrace) => {
1058            t.next();
1059            let bound = |t: &mut Tokens| -> Result<Option<u32>> {
1060                match t.peek(0) {
1061                    Some(Token::Number(n, _)) => {
1062                        let n = n.parse::<u32>().map_err(|_| {
1063                            DataFusionError::Plan(format!(
1064                                "in GRAPH_TABLE: a quantifier's bounds are whole numbers from 0; got {n}"
1065                            ))
1066                        })?;
1067                        t.next();
1068                        Ok(Some(n))
1069                    }
1070                    _ => Ok(None),
1071                }
1072            };
1073            let min = bound(t)?;
1074            let max = if t.eat(&Token::Comma) {
1075                bound(t)?
1076            } else if min.is_some() {
1077                min
1078            } else {
1079                return pattern_err(format!(
1080                    "expected a number or ',' in the quantifier, found {}",
1081                    t.found()
1082                ));
1083            };
1084            t.expect(&Token::RBrace, "'}' to close the quantifier")?;
1085            let min = min.unwrap_or(0);
1086            if max.is_some_and(|max| max < min) {
1087                return pattern_err(format!(
1088                    "the quantifier's lower bound {min} is above its upper bound {}",
1089                    max.unwrap()
1090                ));
1091            }
1092            q(min, max)
1093        }
1094        _ => Ok(None),
1095    }
1096}
1097
1098/// Where a vertex variable reads from.
1099#[derive(Debug, Clone)]
1100enum VertexSource<'g> {
1101    Table(&'g VertexTable),
1102    /// The graph's `nodes` table: a graph without vertex tables.
1103    Nodes,
1104}
1105
1106/// One variable of the pattern.
1107#[derive(Debug, Default)]
1108struct Binding<'g> {
1109    is_edge: bool,
1110    label: Option<String>,
1111    vertex: Option<VertexSource<'g>>,
1112    edge: Option<&'g EdgeTable>,
1113    conditions: Vec<String>,
1114}
1115
1116/// One edge of the pattern, with its two ends.
1117struct Step {
1118    left: String,
1119    edge: String,
1120    right: String,
1121    direction: Direction,
1122    quantifier: Option<Quantifier>,
1123    /// The path it is in.
1124    path: usize,
1125}
1126
1127/// A column of a variable: (variable, column).
1128pub type VarColumn = (String, String);
1129
1130/// What a variable reads: an element table (or the graph's `nodes` table),
1131/// all its columns or `columns` as (column, property name).
1132#[derive(Debug, Clone, PartialEq)]
1133pub struct Source {
1134    pub var: String,
1135    pub table: TableReference,
1136    /// `None`: every column, under its own name.
1137    pub columns: Option<Vec<(String, String)>>,
1138    /// Whether the match joins it: a node whose key is a segment's column
1139    /// ([`Lowered::aliases`]) is read only for its start keys, if at all.
1140    pub joined: bool,
1141    /// For a node of a vertex table: the table's element name and its key,
1142    /// which must identify one row (#411).
1143    pub vertex: Option<(String, String)>,
1144}
1145
1146/// A variable's columns, as [`Source::columns`] lists them.
1147type Columns = Option<Vec<(String, String)>>;
1148
1149/// A condition the lowering adds.
1150#[derive(Debug, Clone, PartialEq)]
1151pub enum Join {
1152    Equal(VarColumn, VarColumn),
1153    /// Not equal: keeps a self-loop out of an undirected edge's reverse branch.
1154    NotEqual(VarColumn, VarColumn),
1155}
1156
1157/// An edge searched on the graph index rather than joined: a quantified
1158/// edge, or the edge of a path with a path variable, a selector or a mode.
1159/// It is a relation of paths, named `var`, with the columns of
1160/// [`super::path_search`]: the path's first and last node, its length, and
1161/// its nodes and edges.
1162#[derive(Debug, Clone, PartialEq)]
1163pub struct Segment {
1164    /// The relation's name: the path variable, or an unnamed one.
1165    pub var: String,
1166    /// The path variable, if the path has one.
1167    pub path: Option<String>,
1168    /// The edge variable it searches (an unnamed edge's is `__ursa_…`).
1169    pub edge: String,
1170    /// The edge table, and its source and destination columns.
1171    pub edges: TableReference,
1172    pub source: String,
1173    pub destination: String,
1174    /// The node variables at its two ends, and their keys.
1175    pub start: String,
1176    pub start_key: VarColumn,
1177    pub end: String,
1178    pub end_key: VarColumn,
1179    pub direction: Direction,
1180    pub quantifier: Quantifier,
1181    pub selector: Selector,
1182    pub mode: Mode,
1183    /// A fixed-length edge expanded through the index, not a searched path.
1184    pub fixed: bool,
1185    pub starts: Starts,
1186    /// Whether the index's nodes are the start node's table's keys, so a
1187    /// start that is not a node of the index is no node at all.
1188    pub known_only: bool,
1189    /// The keys the last node can have, when they are known: the values its
1190    /// conditions name ([`Starts::Node`]: it is bound, see [`Usage::bound`]),
1191    /// or the keys an earlier segment reached. The search's targets.
1192    pub targets: Option<Starts>,
1193}
1194
1195/// What the query reads and binds, from its conditions and `COLUMNS`: what
1196/// decides which edges are expanded through the graph index (see the module
1197/// docs). The default plans joins, as a pattern was planned before.
1198#[derive(Debug, Clone, Default, PartialEq)]
1199pub struct Usage {
1200    /// Whether the rest was found: if not, every edge is joined and every
1201    /// node too.
1202    pub enabled: bool,
1203    /// Per variable, the properties the query reads of it: `None` for all of
1204    /// them (`v.*`). A variable that is not listed is not read.
1205    pub reads: BTreeMap<String, Option<BTreeSet<String>>>,
1206    /// Per variable with a condition on it alone that limits a property to
1207    /// values the query names (`v.p = 1`, `v.p IN (…)`), those properties.
1208    pub bound: BTreeMap<String, BTreeSet<String>>,
1209    /// The edge tables whose index is kept between queries: the ones fixed
1210    /// edges may be expanded on. Empty: every edge is joined.
1211    pub indexed: BTreeSet<TableReference>,
1212}
1213
1214/// Where a segment's start nodes come from.
1215#[derive(Debug, Clone, Copy, PartialEq)]
1216pub enum Starts {
1217    /// The start node's keys that the conditions on it alone keep.
1218    Node,
1219    /// The keys an earlier segment reached: its last node's (`end`), or its
1220    /// first's.
1221    After { segment: usize, end: bool },
1222}
1223
1224/// A node not joined to its table: its key is a segment's column.
1225#[derive(Debug, Clone, PartialEq)]
1226pub struct Alias {
1227    pub var: String,
1228    /// The segment column its key is.
1229    pub column: VarColumn,
1230}
1231
1232/// A pattern resolved against a graph: what to scan and join.
1233#[derive(Debug, Clone, PartialEq)]
1234pub struct Lowered {
1235    /// One per variable, in order of appearance, except the edges searched as
1236    /// segments.
1237    pub sources: Vec<Source>,
1238    /// The edges searched on the graph index, joined to their end nodes in
1239    /// every branch. A segment's [`Starts::After`] names an earlier one.
1240    pub segments: Vec<Segment>,
1241    /// The nodes whose sources are not joined: their keys are segment columns.
1242    pub aliases: Vec<Alias>,
1243    /// One per orientation of the undirected edges: the joins of each branch
1244    /// of the `UNION ALL` (one branch when every edge has a direction).
1245    pub branches: Vec<Vec<Join>>,
1246    /// Whether the match planned as joins would be a `UNION ALL`: it has an
1247    /// undirected fixed edge, joined or not.
1248    pub union: bool,
1249    /// The pattern's conditions as written: in elements, then after the paths.
1250    pub conditions: Vec<String>,
1251    /// The `COLUMNS` list as written.
1252    pub columns: String,
1253    /// What each variable is, for the result's field metadata
1254    /// ([`super::provenance`]): every named node, edge and path variable.
1255    pub variables: Vec<Variable>,
1256    /// The pattern's edges, in the order written, for the result's
1257    /// `ursa.pattern`.
1258    pub edges: Vec<PatternEdge>,
1259}
1260
1261/// A pattern variable, as a result's field metadata describes it.
1262#[derive(Debug, Clone, PartialEq)]
1263pub struct Variable {
1264    pub var: String,
1265    pub kind: VariableKind,
1266}
1267
1268/// What a pattern variable binds.
1269#[derive(Debug, Clone, PartialEq)]
1270pub enum VariableKind {
1271    /// A node: its vertex table (element name), if the graph has one, and
1272    /// the property names of its key.
1273    Node {
1274        label: Option<String>,
1275        keys: Vec<String>,
1276    },
1277    /// An edge of the edge table `label`.
1278    Edge { label: String },
1279    /// A path over the edge table `edges`, between nodes of the vertex table
1280    /// `vertices`, if the graph has one.
1281    Path {
1282        edges: String,
1283        vertices: Option<String>,
1284    },
1285}
1286
1287impl Lowered {
1288    /// The field metadata of `column` of the relation `relation` (a
1289    /// variable), if it is something a result should say: a node's key, a
1290    /// property, or a path's nodes, edges or elements.
1291    pub fn provenance(
1292        &self,
1293        graph: &str,
1294        relation: &str,
1295        column: &str,
1296    ) -> Option<BTreeMap<String, String>> {
1297        use super::path_search::{EDGES, ELEMENTS, VERTICES};
1298        let variable = self.variables.iter().find(|v| v.var == relation)?;
1299        let (role, label) = match &variable.kind {
1300            VariableKind::Node { label, keys } => match keys.iter().any(|k| k == column) {
1301                true => (provenance::ROLE_NODE, label.as_deref()),
1302                false => (provenance::ROLE_PROPERTY, label.as_deref()),
1303            },
1304            VariableKind::Edge { label } => (provenance::ROLE_PROPERTY, Some(label.as_str())),
1305            VariableKind::Path { edges, vertices } => match column {
1306                VERTICES => (provenance::ROLE_PATH_NODES, vertices.as_deref()),
1307                EDGES => (provenance::ROLE_PATH_EDGES, Some(edges.as_str())),
1308                ELEMENTS => (provenance::ROLE_PATH_ELEMENTS, None),
1309                _ => return None,
1310            },
1311        };
1312        let mut metadata = provenance::metadata(role, graph, label);
1313        metadata.insert(provenance::VAR.to_string(), relation.to_string());
1314        Some(metadata)
1315    }
1316}
1317
1318/// Resolve `pattern` against `graph`. `schema_of` gives a table's columns
1319/// (for properties).
1320pub fn lower(
1321    pattern: &Pattern,
1322    graph: &PropertyGraph,
1323    schema_of: &dyn Fn(&TableReference) -> Result<SchemaRef>,
1324    usage: &Usage,
1325) -> Result<Lowered> {
1326    // Collect the variables, naming anonymous ones.
1327    let mut bindings: BTreeMap<String, Binding> = BTreeMap::new();
1328    let mut order: Vec<String> = Vec::new();
1329    let mut steps = Vec::new();
1330    let mut anonymous = 0;
1331    for (path_index, path) in pattern.paths.iter().enumerate() {
1332        // (left node, direction, edge, quantifier)
1333        let mut previous: Option<(String, Direction, String, Option<Quantifier>)> = None;
1334        for element in &path.elements {
1335            let (spec, is_edge) = match element {
1336                Element::Node(spec) => (spec, false),
1337                Element::Edge(spec, _, _) => (spec, true),
1338            };
1339            let var = match &spec.var {
1340                Some(v) => v.clone(),
1341                None => {
1342                    anonymous += 1;
1343                    format!("__ursa_{anonymous}")
1344                }
1345            };
1346            let binding = bindings.entry(var.clone()).or_insert_with(|| {
1347                order.push(var.clone());
1348                Binding {
1349                    is_edge,
1350                    ..Binding::default()
1351                }
1352            });
1353            if binding.is_edge != is_edge {
1354                return pattern_err(format!("'{var}' is used for both a node and an edge"));
1355            }
1356            if is_edge
1357                && (binding.label.is_some()
1358                    || !binding.conditions.is_empty()
1359                    || steps.iter().any(|s: &Step| s.edge == var))
1360            {
1361                return pattern_err(format!(
1362                    "edge variable '{var}' appears twice; an edge variable binds one edge"
1363                ));
1364            }
1365            if let Some(label) = &spec.label {
1366                if binding.label.as_ref().is_some_and(|l| l != label) {
1367                    return pattern_err(format!(
1368                        "'{var}' has two labels, {} and {label}",
1369                        binding.label.as_ref().unwrap()
1370                    ));
1371                }
1372                binding.label = Some(label.clone());
1373            }
1374            binding.conditions.extend(spec.condition.clone());
1375            match element {
1376                Element::Node(_) => {
1377                    if let Some((left, direction, edge, quantifier)) = previous.take() {
1378                        steps.push(Step {
1379                            left,
1380                            edge,
1381                            right: var.clone(),
1382                            direction,
1383                            quantifier,
1384                            path: path_index,
1385                        });
1386                    }
1387                    previous = Some((var, Direction::Right, String::new(), None));
1388                }
1389                Element::Edge(_, direction, quantifier) => {
1390                    let (left, ..) = previous.take().expect("a path starts with a node");
1391                    previous = Some((left, *direction, var, *quantifier));
1392                }
1393            }
1394        }
1395    }
1396
1397    // Labels as written.
1398    for (var, b) in bindings.iter_mut() {
1399        let Some(label) = &b.label else { continue };
1400        if b.is_edge {
1401            let tables: Vec<&EdgeTable> = graph
1402                .edge_tables
1403                .iter()
1404                .filter(|e| e.answers_to(label))
1405                .collect();
1406            match tables.as_slice() {
1407                [only] => b.edge = Some(only),
1408                [] => return pattern_err(format!(
1409                    "graph '{}' has no edge table or edge label '{label}' (for '{}'); its edge tables are {}",
1410                    graph.name, shown(var), names(graph.edge_tables.iter().map(|e| e.name.as_str()))
1411                )),
1412                _ => return pattern_err(format!(
1413                    "label '{label}' is on several edge tables; a label shared by several tables is not supported yet"
1414                )),
1415            }
1416        } else {
1417            let tables: Vec<&VertexTable> = graph
1418                .vertex_tables
1419                .iter()
1420                .filter(|v| v.answers_to(label))
1421                .collect();
1422            match tables.as_slice() {
1423                [only] => b.vertex = Some(VertexSource::Table(only)),
1424                [] => return pattern_err(format!(
1425                    "graph '{}' has no vertex table or vertex label '{label}' (for '{}'); its vertex tables are {}",
1426                    graph.name, shown(var), names(graph.vertex_tables.iter().map(|v| v.name.as_str()))
1427                )),
1428                _ => return pattern_err(format!(
1429                    "label '{label}' is on several vertex tables; a label shared by several tables is not supported yet"
1430                )),
1431            }
1432        }
1433    }
1434
1435    // Infer the rest from the edges' REFERENCES, until nothing changes.
1436    loop {
1437        let mut changed = false;
1438        for step in &steps {
1439            let left = vertex_table(&bindings[&step.left]);
1440            let right = vertex_table(&bindings[&step.right]);
1441            let edge = bindings[&step.edge].edge;
1442            match edge {
1443                None => {
1444                    let candidates: Vec<&EdgeTable> = graph
1445                        .edge_tables
1446                        .iter()
1447                        .filter(|e| fits(graph, e, left, right, step.direction))
1448                        .collect();
1449                    if let [only] = candidates.as_slice() {
1450                        bindings.get_mut(&step.edge).unwrap().edge = Some(only);
1451                        changed = true;
1452                    }
1453                }
1454                Some(e) => {
1455                    let (from, to) = (
1456                        graph.endpoint_vertex(e, true),
1457                        graph.endpoint_vertex(e, false),
1458                    );
1459                    let (l, r) = match step.direction {
1460                        Direction::Right => (from, to),
1461                        Direction::Left => (to, from),
1462                        Direction::Any if from.map(|v| &v.name) == to.map(|v| &v.name) => {
1463                            (from, to)
1464                        }
1465                        Direction::Any => (None, None),
1466                    };
1467                    for (var, table) in [(&step.left, l), (&step.right, r)] {
1468                        let b = bindings.get_mut(var).unwrap();
1469                        if b.vertex.is_none() {
1470                            if let Some(table) = table {
1471                                b.vertex = Some(VertexSource::Table(table));
1472                                changed = true;
1473                            }
1474                        }
1475                    }
1476                }
1477            }
1478        }
1479        if !changed {
1480            break;
1481        }
1482    }
1483
1484    // What is still open: the graph's only table of its kind, or a refusal.
1485    // Edges first: labelling an edge usually tells its nodes too.
1486    for (var, b) in bindings.iter_mut() {
1487        if b.is_edge && b.edge.is_none() {
1488            match graph.edge_tables.as_slice() {
1489                [only] => b.edge = Some(only),
1490                [] => return pattern_err(format!("graph '{}' has no edge tables", graph.name)),
1491                _ => return pattern_err(format!(
1492                    "which edge table {} is cannot be told from the pattern; give it a label, as -[{}:{}]->",
1493                    describe_var(var, true),
1494                    if var.starts_with("__ursa_") { "" } else { var.as_str() },
1495                    graph.edge_tables[0].labels()[0].name
1496                )),
1497            }
1498        }
1499    }
1500    for (var, b) in bindings.iter_mut() {
1501        if !b.is_edge && b.vertex.is_none() {
1502            match graph.vertex_tables.as_slice() {
1503                [only] => b.vertex = Some(VertexSource::Table(only)),
1504                [] if graph.default_pair().is_some() => b.vertex = Some(VertexSource::Nodes),
1505                [] => return pattern_err(format!(
1506                    "graph '{}' has no vertex tables and several edge tables, so its nodes cannot be matched",
1507                    graph.name
1508                )),
1509                _ => return pattern_err(format!(
1510                    "which vertex table {} is cannot be told from the pattern; give it a label, as ({}:{})",
1511                    describe_var(var, false),
1512                    if var.starts_with("__ursa_") { "" } else { var.as_str() },
1513                    graph.vertex_tables[0].labels()[0].name
1514                )),
1515            }
1516        }
1517    }
1518
1519    // An edge binds only between the vertex tables its edge table REFERENCES
1520    // (#410): a node of another table is refused, not joined on key values
1521    // that happen to be equal.
1522    for step in &steps {
1523        let e = bindings[&step.edge].edge.expect("resolved");
1524        let left = vertex_table(&bindings[&step.left]);
1525        let right = vertex_table(&bindings[&step.right]);
1526        if !fits(graph, e, left, right, step.direction) {
1527            return pattern_err(contradiction(graph, e, step, &bindings));
1528        }
1529    }
1530
1531    // The edges searched on the index: quantified edges, and the edge of a
1532    // path with a variable, a selector or a mode.
1533    let mut searched: Vec<(usize, Option<String>, Selector, Mode)> = Vec::new(); // (step, path var, …)
1534    for (i, path) in pattern.paths.iter().enumerate() {
1535        let edges: Vec<usize> = (0..steps.len()).filter(|&s| steps[s].path == i).collect();
1536        let whole = path.var.is_some() || path.selector != Selector::All || path.mode != Mode::Walk;
1537        if let Some(var) = &path.var {
1538            if bindings.contains_key(var)
1539                || pattern.paths[..i]
1540                    .iter()
1541                    .any(|p| p.var.as_ref() == Some(var))
1542            {
1543                return pattern_err(format!(
1544                    "'{var}' names a path and another variable; give the path its own name"
1545                ));
1546            }
1547        }
1548        if whole && edges.len() > 1 {
1549            return pattern_err(
1550                "a path with a path variable, ANY/ALL SHORTEST or a path mode must be one edge between two nodes for now, as p = ANY SHORTEST (a)-[e]->*(b)",
1551            );
1552        }
1553        if whole && edges.is_empty() {
1554            if path.var.is_some() {
1555                return pattern_err(
1556                    "a path variable needs a path with an edge, as p = (a)-[e]->*(b)",
1557                );
1558            }
1559            continue;
1560        }
1561        for s in edges {
1562            if whole {
1563                searched.push((s, path.var.clone(), path.selector, path.mode));
1564            } else if steps[s].quantifier.is_some() {
1565                searched.push((s, None, Selector::All, Mode::Walk));
1566            }
1567        }
1568    }
1569    for (s, _, selector, mode) in &searched {
1570        let step = &steps[*s];
1571        let quantifier = step.quantifier.unwrap_or(Quantifier::ONCE);
1572        let b = &bindings[&step.edge];
1573        let e = b.edge.expect("resolved");
1574        let edge = describe_var(&step.edge, true);
1575        if !b.conditions.is_empty() {
1576            return pattern_err(format!(
1577                "{edge} is quantified or in a searched path, so it stands for several edges; a condition on it is not supported yet"
1578            ));
1579        }
1580        if *selector == Selector::All && *mode == Mode::Walk && quantifier.max.is_none() {
1581            return pattern_err(format!(
1582                "{edge} has no upper bound, so its walks are endless; give it one, as {{1,3}}, keep the shortest with ANY SHORTEST, or use TRAIL, SIMPLE or ACYCLIC"
1583            ));
1584        }
1585        let ends = (
1586            graph.endpoint_vertex(e, true).map(|v| v.name.as_str()),
1587            graph.endpoint_vertex(e, false).map(|v| v.name.as_str()),
1588        );
1589        if ends.0 != ends.1
1590            && (quantifier.min != 1
1591                || quantifier.max != Some(1)
1592                || step.direction == Direction::Any)
1593        {
1594            return pattern_err(format!(
1595                "{edge} joins two vertex tables ({} and {}), so it cannot repeat, be undirected or match no edge; only a quantified edge within one vertex table can",
1596                ends.0.unwrap_or("?"),
1597                ends.1.unwrap_or("?")
1598            ));
1599        }
1600    }
1601    let is_searched = |i: usize| searched.iter().any(|(s, ..)| *s == i);
1602
1603    // Each node variable's columns, and its key's property names.
1604    let mut node_columns: BTreeMap<&str, (TableReference, Columns)> = BTreeMap::new();
1605    for var in &order {
1606        let b = &bindings[var];
1607        if b.is_edge {
1608            continue;
1609        }
1610        let read = match b.vertex.as_ref().expect("resolved") {
1611            VertexSource::Table(v) => (
1612                v.table.clone(),
1613                properties(&v.table, &v.labels(), &[v.key.as_str()], schema_of)?,
1614            ),
1615            VertexSource::Nodes => (
1616                TableReference::partial(graph.name.as_str(), super::schema::NODES),
1617                None,
1618            ),
1619        };
1620        node_columns.insert(var.as_str(), read);
1621    }
1622    let key = |var: &str| -> VarColumn {
1623        match bindings[var].vertex.as_ref().expect("resolved") {
1624            VertexSource::Table(v) => (var.to_string(), v.key.clone()),
1625            VertexSource::Nodes => (var.to_string(), super::schema::ID.to_string()),
1626        }
1627    };
1628    let key_names = |var: &str| -> Vec<String> {
1629        let (_, column) = key(var);
1630        match &node_columns[var].1 {
1631            None => vec![column],
1632            Some(columns) => columns
1633                .iter()
1634                .filter(|(c, _)| *c == column)
1635                .map(|(_, n)| n.clone())
1636                .collect(),
1637        }
1638    };
1639    // Bound: a condition on the node alone names the values of its key.
1640    let is_bound = |var: &str| {
1641        usage
1642            .bound
1643            .get(var)
1644            .is_some_and(|ps| key_names(var).iter().any(|n| ps.contains(n)))
1645    };
1646    let reads_only_its_key = |var: &str| match usage.reads.get(var) {
1647        _ if !usage.enabled => false,
1648        None => true,
1649        Some(None) => false,
1650        Some(Some(ps)) => {
1651            let names = key_names(var);
1652            ps.iter().all(|p| names.contains(p))
1653        }
1654    };
1655    // Whether the index of `e` has the keys of `var`'s table as its nodes.
1656    let known = |e: &EdgeTable, var: &str| match bindings[var].vertex.as_ref().expect("resolved") {
1657        VertexSource::Table(v) => {
1658            graph
1659                .endpoint_vertex(e, true)
1660                .is_some_and(|t| t.name == v.name)
1661                && graph
1662                    .endpoint_vertex(e, false)
1663                    .is_some_and(|t| t.name == v.name)
1664        }
1665        VertexSource::Nodes => graph.vertex_tables.is_empty() && graph.edge_tables.len() == 1,
1666    };
1667    // Whether the index of `e` keeps every edge a join of `e` to `var`'s
1668    // table keeps: it drops edges to values that are no key of its ends'
1669    // tables, so `var` must read one of them.
1670    let in_index = |e: &EdgeTable, var: &str| match (
1671        graph.endpoint_vertex(e, true),
1672        graph.endpoint_vertex(e, false),
1673    ) {
1674        (Some(s), Some(d)) => {
1675            vertex_table(&bindings[var]).is_some_and(|v| v.name == s.name || v.name == d.name)
1676        }
1677        _ => true,
1678    };
1679    let expandable = |i: usize| {
1680        let step = &steps[i];
1681        let b = &bindings[&step.edge];
1682        let e = b.edge.expect("resolved");
1683        !is_searched(i)
1684            && b.conditions.is_empty()
1685            && !usage.reads.contains_key(&step.edge)
1686            && usage.indexed.contains(&e.table)
1687            && in_index(e, &step.left)
1688            && in_index(e, &step.right)
1689    };
1690
1691    // From each bound node, the fixed edges of its path, outward, each from
1692    // the keys the one before reached; and the searched edges on the way,
1693    // from those keys too (see the module docs). (step, reversed, starts)
1694    let mut planned: Vec<(usize, bool, Starts)> = Vec::new();
1695    // Per node, where its keys come from, and the segment count when it
1696    // was reached.
1697    let mut reached: BTreeMap<String, (Starts, usize)> = BTreeMap::new();
1698    for var in &order {
1699        if !bindings[var].is_edge && is_bound(var) {
1700            reached.insert(var.clone(), (Starts::Node, 0));
1701        }
1702    }
1703    let mut done = vec![false; pattern.paths.len()];
1704    loop {
1705        let mut progress = false;
1706        for (i, finished) in done.iter_mut().enumerate() {
1707            if *finished {
1708                continue;
1709            }
1710            let path_steps: Vec<usize> = (0..steps.len()).filter(|&s| steps[s].path == i).collect();
1711            let Some(&first) = path_steps.first() else {
1712                *finished = true;
1713                continue;
1714            };
1715            let mut nodes = vec![steps[first].left.clone()];
1716            nodes.extend(path_steps.iter().map(|&s| steps[s].right.clone()));
1717            let Some(root) = nodes.iter().position(|n| reached.contains_key(n)) else {
1718                continue;
1719            };
1720            *finished = true;
1721            progress = true;
1722            for (j, &s) in path_steps.iter().enumerate().skip(root) {
1723                let Some(&(from, _)) = reached.get(&nodes[j]) else {
1724                    break;
1725                };
1726                if !is_searched(s) && !expandable(s) {
1727                    break;
1728                }
1729                planned.push((s, false, from));
1730                let segment = planned.len() - 1;
1731                reached
1732                    .entry(nodes[j + 1].clone())
1733                    .or_insert((Starts::After { segment, end: true }, planned.len()));
1734            }
1735            for j in (0..root).rev() {
1736                let s = path_steps[j];
1737                let Some(&(from, _)) = reached.get(&nodes[j + 1]) else {
1738                    break;
1739                };
1740                // A search runs from its first node: it cannot be reversed.
1741                if is_searched(s) || !expandable(s) {
1742                    break;
1743                }
1744                planned.push((s, true, from));
1745                let segment = planned.len() - 1;
1746                reached
1747                    .entry(nodes[j].clone())
1748                    .or_insert((Starts::After { segment, end: true }, planned.len()));
1749            }
1750        }
1751        if !progress {
1752            break;
1753        }
1754    }
1755    // The searched edges no bound node reached run from their first node.
1756    for (s, ..) in &searched {
1757        if !planned.iter().any(|(p, ..)| p == s) {
1758            planned.push((*s, false, Starts::Node));
1759        }
1760    }
1761    let is_expanded = |i: usize| planned.iter().any(|(s, ..)| *s == i);
1762
1763    let reverse = |d: Direction| match d {
1764        Direction::Right => Direction::Left,
1765        Direction::Left => Direction::Right,
1766        Direction::Any => Direction::Any,
1767    };
1768    let mut segments: Vec<Segment> = Vec::new();
1769    for &(s, reversed, starts) in &planned {
1770        let step = &steps[s];
1771        let e = bindings[&step.edge].edge.expect("resolved");
1772        let (start, end) = match reversed {
1773            false => (step.left.clone(), step.right.clone()),
1774            true => (step.right.clone(), step.left.clone()),
1775        };
1776        let search = searched.iter().find(|(x, ..)| *x == s);
1777        let (path, selector, mode) = match search {
1778            Some((_, path, selector, mode)) => (path.clone(), *selector, *mode),
1779            None => (None, Selector::All, Mode::Walk),
1780        };
1781        let var = match &path {
1782            Some(p) => p.clone(),
1783            None => {
1784                anonymous += 1;
1785                format!("__ursa_{anonymous}")
1786            }
1787        };
1788        // The keys the last node can have, when they are known by now.
1789        let targets = match reached.get(&end) {
1790            _ if is_bound(&end) => Some(Starts::Node),
1791            Some(&(after @ Starts::After { .. }, when)) if when <= segments.len() => Some(after),
1792            _ => None,
1793        };
1794        segments.push(Segment {
1795            var,
1796            path,
1797            edge: step.edge.clone(),
1798            edges: e.table.clone(),
1799            source: e.source.clone(),
1800            destination: e.destination.clone(),
1801            known_only: known(e, &start),
1802            start_key: key(&start),
1803            start,
1804            end_key: key(&end),
1805            end,
1806            direction: if reversed {
1807                reverse(step.direction)
1808            } else {
1809                step.direction
1810            },
1811            quantifier: step.quantifier.unwrap_or(Quantifier::ONCE),
1812            selector,
1813            mode,
1814            fixed: search.is_none(),
1815            starts,
1816            targets,
1817        });
1818    }
1819
1820    // Nodes the query reads only the key of, at the end of a segment whose
1821    // index's nodes are their table's keys: their key is that segment's column.
1822    let mut aliases: Vec<Alias> = Vec::new();
1823    for var in &order {
1824        if bindings[var].is_edge || !reads_only_its_key(var) {
1825            continue;
1826        }
1827        let at = segments
1828            .iter()
1829            .zip(&planned)
1830            .find_map(|(segment, &(s, ..))| {
1831                let e = bindings[&steps[s].edge].edge.expect("resolved");
1832                if !known(e, var) {
1833                    return None;
1834                }
1835                let column = if &segment.start == var {
1836                    super::path_search::START
1837                } else if &segment.end == var {
1838                    super::path_search::END
1839                } else {
1840                    return None;
1841                };
1842                Some((segment.var.clone(), column.to_string()))
1843            });
1844        if let Some(column) = at {
1845            aliases.push(Alias {
1846                var: var.clone(),
1847                column,
1848            });
1849        }
1850    }
1851    // Where a node's key is read: its table's key column, or a segment's.
1852    let at = |var: &str| -> VarColumn {
1853        match aliases.iter().find(|a| a.var == var) {
1854            Some(a) => a.column.clone(),
1855            None => key(var),
1856        }
1857    };
1858
1859    let undirected: Vec<usize> = steps
1860        .iter()
1861        .enumerate()
1862        .filter(|(i, s)| s.direction == Direction::Any && !is_expanded(*i))
1863        .map(|(i, _)| i)
1864        .collect();
1865    if undirected.len() > MAX_UNDIRECTED {
1866        return pattern_err(format!(
1867            "a pattern may have at most {MAX_UNDIRECTED} undirected edges (-[e]-); give some a direction"
1868        ));
1869    }
1870    let mut sources = Vec::new();
1871    for var in &order {
1872        let b = &bindings[var];
1873        if b.is_edge && planned.iter().any(|(s, ..)| &steps[*s].edge == var) {
1874            continue;
1875        }
1876        let (table, columns) = if b.is_edge {
1877            let e = b.edge.expect("resolved");
1878            let needed = [e.source.as_str(), e.destination.as_str()];
1879            (
1880                e.table.clone(),
1881                properties(&e.table, &e.labels(), &needed, schema_of)?,
1882            )
1883        } else {
1884            node_columns[var.as_str()].clone()
1885        };
1886        sources.push(Source {
1887            var: var.clone(),
1888            table,
1889            columns,
1890            joined: !aliases.iter().any(|a| &a.var == var),
1891            vertex: match b.is_edge {
1892                true => None,
1893                false => vertex_table(b).map(|v| (v.name.clone(), v.key.clone())),
1894            },
1895        });
1896    }
1897
1898    let mut branches = Vec::new();
1899    for mask in 0..(1usize << undirected.len()) {
1900        let mut joins = Vec::new();
1901        for segment in &segments {
1902            let column = |name: &str| (segment.var.clone(), name.to_string());
1903            for (name, var) in [
1904                (super::path_search::START, &segment.start),
1905                (super::path_search::END, &segment.end),
1906            ] {
1907                let (a, b) = (column(name), at(var));
1908                if a != b {
1909                    joins.push(Join::Equal(a, b));
1910                }
1911            }
1912        }
1913        for (i, step) in steps.iter().enumerate() {
1914            if is_expanded(i) {
1915                continue;
1916            }
1917            let e = bindings[&step.edge].edge.expect("resolved");
1918            let src = (step.edge.clone(), e.source.clone());
1919            let dst = (step.edge.clone(), e.destination.clone());
1920            let reversed = match step.direction {
1921                Direction::Right => false,
1922                Direction::Left => true,
1923                Direction::Any => {
1924                    let bit = undirected.iter().position(|&u| u == i).unwrap();
1925                    let reversed = mask & (1 << bit) != 0;
1926                    if reversed {
1927                        // A self-loop matches once, in the forward branch.
1928                        joins.push(Join::NotEqual(src.clone(), dst.clone()));
1929                    }
1930                    reversed
1931                }
1932            };
1933            let (from, to) = if reversed {
1934                (&step.right, &step.left)
1935            } else {
1936                (&step.left, &step.right)
1937            };
1938            joins.push(Join::Equal(src, at(from)));
1939            joins.push(Join::Equal(dst, at(to)));
1940        }
1941        branches.push(joins);
1942    }
1943    let mut conditions: Vec<String> = order
1944        .iter()
1945        .flat_map(|var| bindings[var].conditions.iter().cloned())
1946        .collect();
1947    conditions.extend(pattern.condition.clone());
1948    let union = steps
1949        .iter()
1950        .enumerate()
1951        .any(|(i, s)| s.direction == Direction::Any && !is_searched(i));
1952    // What the result says about its columns (`provenance`): the named
1953    // variables, and the pattern's edges.
1954    let named = |var: &str| (!var.starts_with("__ursa_")).then(|| var.to_string());
1955    let mut variables: Vec<Variable> = order
1956        .iter()
1957        .filter(|var| named(var).is_some())
1958        .map(|var| {
1959            let b = &bindings[var];
1960            let kind = match b.is_edge {
1961                true => VariableKind::Edge {
1962                    label: b.edge.expect("resolved").name.clone(),
1963                },
1964                false => VariableKind::Node {
1965                    label: vertex_table(b).map(|v| v.name.clone()),
1966                    keys: key_names(var),
1967                },
1968            };
1969            Variable {
1970                var: var.clone(),
1971                kind,
1972            }
1973        })
1974        .collect();
1975    for step in &steps {
1976        let Some(path) = &pattern.paths[step.path].var else {
1977            continue;
1978        };
1979        if variables.iter().any(|v| &v.var == path) {
1980            continue;
1981        }
1982        variables.push(Variable {
1983            var: path.clone(),
1984            kind: VariableKind::Path {
1985                edges: bindings[&step.edge].edge.expect("resolved").name.clone(),
1986                vertices: vertex_table(&bindings[&step.left]).map(|v| v.name.clone()),
1987            },
1988        });
1989    }
1990    let edges = steps
1991        .iter()
1992        .map(|step| {
1993            let (from, to) = match step.direction {
1994                Direction::Left => (&step.right, &step.left),
1995                Direction::Right | Direction::Any => (&step.left, &step.right),
1996            };
1997            PatternEdge {
1998                from: named(from),
1999                to: named(to),
2000                directed: step.direction != Direction::Any,
2001                edge: named(&step.edge),
2002                label: bindings[&step.edge].edge.expect("resolved").name.clone(),
2003                quantifier: step.quantifier.map(|q| (q.min, q.max)),
2004                path: pattern.paths[step.path].var.clone(),
2005            }
2006        })
2007        .collect();
2008    Ok(Lowered {
2009        sources,
2010        segments,
2011        aliases,
2012        branches,
2013        union,
2014        conditions,
2015        columns: pattern.columns.clone(),
2016        variables,
2017        edges,
2018    })
2019}
2020
2021/// The vertex table a variable is bound to, if it is bound to one.
2022fn vertex_table<'g>(b: &Binding<'g>) -> Option<&'g VertexTable> {
2023    match b.vertex {
2024        Some(VertexSource::Table(v)) => Some(v),
2025        _ => None,
2026    }
2027}
2028
2029/// Whether edge table `e` can join `left` to `right` in `direction`, as far
2030/// as the vertex tables already known say.
2031fn fits(
2032    graph: &PropertyGraph,
2033    e: &EdgeTable,
2034    left: Option<&VertexTable>,
2035    right: Option<&VertexTable>,
2036    direction: Direction,
2037) -> bool {
2038    let from = graph.endpoint_vertex(e, true).map(|v| v.name.as_str());
2039    let to = graph.endpoint_vertex(e, false).map(|v| v.name.as_str());
2040    let matches = |side: Option<&VertexTable>, end: Option<&str>| match (side, end) {
2041        (Some(side), Some(end)) => side.name == end,
2042        _ => true,
2043    };
2044    let forward = matches(left, from) && matches(right, to);
2045    let backward = matches(left, to) && matches(right, from);
2046    match direction {
2047        Direction::Right => forward,
2048        Direction::Left => backward,
2049        Direction::Any => forward || backward,
2050    }
2051}
2052
2053/// The refusal of `step`, whose edge table `e` does not connect the vertex
2054/// tables its nodes are bound to.
2055fn contradiction(
2056    graph: &PropertyGraph,
2057    e: &EdgeTable,
2058    step: &Step,
2059    bindings: &BTreeMap<String, Binding>,
2060) -> String {
2061    let end = |source: bool| graph.endpoint_vertex(e, source).map(|v| v.name.as_str());
2062    let (from, to) = (end(true).unwrap_or("?"), end(false).unwrap_or("?"));
2063    // A node as written, and the vertex table it is bound to.
2064    let node = |var: &str| {
2065        let b = &bindings[var];
2066        let table = vertex_table(b).map(|v| v.name.as_str()).unwrap_or("?");
2067        let written = match (var.starts_with("__ursa_"), &b.label) {
2068            (true, Some(label)) => format!("(:{label})"),
2069            (true, None) => "()".to_string(),
2070            (false, Some(label)) => format!("({var}:{label})"),
2071            (false, None) => format!("({var})"),
2072        };
2073        (written, table)
2074    };
2075    let (left, left_table) = node(&step.left);
2076    let (right, right_table) = node(&step.right);
2077    let (arrow, written, either) = match step.direction {
2078        Direction::Right => ("->", format!("from '{left_table}' to '{right_table}'"), ""),
2079        Direction::Left => ("<-", format!("from '{right_table}' to '{left_table}'"), ""),
2080        Direction::Any => (
2081            "-",
2082            format!("between '{left_table}' and '{right_table}'"),
2083            " in either direction",
2084        ),
2085    };
2086    format!(
2087        "edge table '{}' of graph '{}' goes from vertex table '{from}' to '{to}', but {} is written {left}{arrow}{right}, {written}; no edge of '{}' connects them{either}, so the pattern can match nothing",
2088        e.name,
2089        graph.name,
2090        describe_var(&step.edge, true),
2091        e.name,
2092    )
2093}
2094
2095/// The columns an element table exposes, as (column, property name): `None`
2096/// when every label exposes every column under its own name; else its
2097/// labels' properties, plus the `needed` key or endpoint columns.
2098fn properties(
2099    table: &TableReference,
2100    labels: &[Label],
2101    needed: &[&str],
2102    schema_of: &dyn Fn(&TableReference) -> Result<SchemaRef>,
2103) -> Result<Option<Vec<(String, String)>>> {
2104    let all = labels
2105        .iter()
2106        .all(|l| matches!(&l.properties, Properties::AllColumns { except } if except.is_empty()));
2107    if all {
2108        return Ok(None);
2109    }
2110    let schema = schema_of(table)?;
2111    let mut items: Vec<(String, String)> = Vec::new(); // (column, property)
2112    for label in labels {
2113        let columns: Vec<(String, String)> = match &label.properties {
2114            Properties::AllColumns { except } => schema
2115                .fields()
2116                .iter()
2117                .map(|f| f.name().clone())
2118                .filter(|c| !except.contains(c))
2119                .map(|c| (c.clone(), c))
2120                .collect(),
2121            Properties::Columns(columns) => columns.clone(),
2122            Properties::None => Vec::new(),
2123        };
2124        for item in columns {
2125            if !items.iter().any(|(_, name)| name == &item.1) {
2126                items.push(item);
2127            }
2128        }
2129    }
2130    for column in needed {
2131        if !items.iter().any(|(_, name)| name == column) {
2132            items.push((column.to_string(), column.to_string()));
2133        }
2134    }
2135    Ok(Some(items))
2136}
2137
2138fn names<'a>(names: impl Iterator<Item = &'a str>) -> String {
2139    let names: Vec<&str> = names.collect();
2140    if names.is_empty() {
2141        "none".to_string()
2142    } else {
2143        names.join(", ")
2144    }
2145}
2146
2147/// A variable as a message names it.
2148fn shown(var: &str) -> String {
2149    if var.starts_with("__ursa_") {
2150        "an unnamed element".to_string()
2151    } else {
2152        var.to_string()
2153    }
2154}
2155
2156fn describe_var(var: &str, edge: bool) -> String {
2157    match (var.starts_with("__ursa_"), edge) {
2158        (true, true) => "an unnamed edge".to_string(),
2159        (true, false) => "an unnamed node".to_string(),
2160        (false, true) => format!("edge '{var}'"),
2161        (false, false) => format!("node '{var}'"),
2162    }
2163}
2164
2165#[cfg(test)]
2166mod tests {
2167    use super::*;
2168
2169    fn spec(var: Option<&str>, label: Option<&str>, condition: Option<&str>) -> Spec {
2170        Spec {
2171            var: var.map(str::to_string),
2172            label: label.map(str::to_string),
2173            condition: condition.map(str::to_string),
2174        }
2175    }
2176
2177    fn edges(path: &PathPattern) -> Vec<(Direction, Option<Quantifier>)> {
2178        path.elements
2179            .iter()
2180            .filter_map(|e| match e {
2181                Element::Edge(_, d, q) => Some((*d, *q)),
2182                _ => None,
2183            })
2184            .collect()
2185    }
2186
2187    #[test]
2188    fn parses_a_pattern() {
2189        let p = parse(
2190            "social MATCH (a:Person WHERE a.age > (1 + 2))-[k:knows WHERE k.since > 2000]->(b IS Person),
2191             (b)<-[w]-(c), (c)-(d)-[x]-(e)->(f)<-(g)
2192             WHERE a.name <> b.name COLUMNS (a.name AS a, concat(b.name, ')') AS b)",
2193        )
2194        .unwrap();
2195        assert_eq!(p.graph, "social");
2196        assert_eq!(p.condition.as_deref(), Some("a.name <> b.name"));
2197        assert_eq!(p.columns, "a.name AS a, concat(b.name, ')') AS b");
2198        assert_eq!(
2199            p.paths[0].elements,
2200            vec![
2201                Element::Node(spec(Some("a"), Some("person"), Some("a.age > (1 + 2)"))),
2202                Element::Edge(
2203                    spec(Some("k"), Some("knows"), Some("k.since > 2000")),
2204                    Direction::Right,
2205                    None
2206                ),
2207                Element::Node(spec(Some("b"), Some("person"), None)),
2208            ]
2209        );
2210        assert_eq!(
2211            p.paths[1].elements,
2212            vec![
2213                Element::Node(spec(Some("b"), None, None)),
2214                Element::Edge(spec(Some("w"), None, None), Direction::Left, None),
2215                Element::Node(spec(Some("c"), None, None)),
2216            ]
2217        );
2218        let directions: Vec<Direction> = edges(&p.paths[2]).into_iter().map(|e| e.0).collect();
2219        assert_eq!(
2220            directions,
2221            vec![
2222                Direction::Any,
2223                Direction::Any,
2224                Direction::Right,
2225                Direction::Left
2226            ]
2227        );
2228        assert_eq!(p.paths[0].selector, Selector::All);
2229        assert_eq!(p.paths[0].mode, Mode::Walk);
2230    }
2231
2232    #[test]
2233    fn parses_quantifiers_selectors_and_modes() {
2234        let q = |min, max| Some(Quantifier { min, max });
2235        for (path, expected) in [
2236            ("(a)-[e]->*(b)", (Direction::Right, q(0, None))),
2237            ("(a)-[e]-> *(b)", (Direction::Right, q(0, None))),
2238            ("(a)-[e]- > *(b)", (Direction::Right, q(0, None))),
2239            ("(a)-[e]->+(b)", (Direction::Right, q(1, None))),
2240            ("(a)<-[e]-?(b)", (Direction::Left, q(0, Some(1)))),
2241            ("(a)-[e]-*(b)", (Direction::Any, q(0, None))),
2242            ("(a)->{2}(b)", (Direction::Right, q(2, Some(2)))),
2243            ("(a)-[e]->{1,3}(b)", (Direction::Right, q(1, Some(3)))),
2244            ("(a)-[e]->{2,}(b)", (Direction::Right, q(2, None))),
2245            ("(a)-[e]->{,3}(b)", (Direction::Right, q(0, Some(3)))),
2246            ("(a)-[e]->{,}(b)", (Direction::Right, q(0, None))),
2247            ("(a)-[e]->(b)", (Direction::Right, None)),
2248        ] {
2249            let p = parse(&format!("g MATCH {path} COLUMNS (a.id)")).unwrap();
2250            assert_eq!(edges(&p.paths[0]), vec![expected], "{path}");
2251        }
2252        for (path, var, selector, mode) in [
2253            (
2254                "p = ANY SHORTEST (a)-[e]->*(b)",
2255                Some("p"),
2256                Selector::Shortest(1),
2257                Mode::Walk,
2258            ),
2259            ("ANY (a)-[e]->*(b)", None, Selector::Shortest(1), Mode::Walk),
2260            (
2261                "ANY 2 TRAIL (a)-[e]->*(b)",
2262                None,
2263                Selector::Shortest(2),
2264                Mode::Trail,
2265            ),
2266            (
2267                "q = SHORTEST 3 PATHS (a)-[e]->*(b)",
2268                Some("q"),
2269                Selector::Shortest(3),
2270                Mode::Walk,
2271            ),
2272            (
2273                "ALL SHORTEST ACYCLIC PATH (a)-[e]->*(b)",
2274                None,
2275                Selector::AllShortest,
2276                Mode::Acyclic,
2277            ),
2278            (
2279                "ALL SIMPLE (a)-[e]->{1,2}(b)",
2280                None,
2281                Selector::All,
2282                Mode::Simple,
2283            ),
2284            (
2285                "p = WALK (a)-[e]->{1,2}(b)",
2286                Some("p"),
2287                Selector::All,
2288                Mode::Walk,
2289            ),
2290        ] {
2291            let p = parse(&format!("g MATCH {path} COLUMNS (a.id)")).unwrap();
2292            let path0 = &p.paths[0];
2293            assert_eq!(
2294                (path0.var.as_deref(), path0.selector, path0.mode),
2295                (var, selector, mode),
2296                "{path}"
2297            );
2298        }
2299    }
2300
2301    #[test]
2302    fn refuses_what_is_not_supported_yet_and_reports_errors() {
2303        for (body, expected) in [
2304            (
2305                "g MATCH ANY SHORTEST 5 (a)-[e]->*(b) COLUMNS (a.id)",
2306                "for several, write SHORTEST k",
2307            ),
2308            (
2309                "g MATCH SHORTEST (a)-[e]->*(b) COLUMNS (a.id)",
2310                "SHORTEST takes a number",
2311            ),
2312            ("g MATCH SHORTEST 0 (a)-[e]->*(b) COLUMNS (a.id)", "above 0"),
2313            (
2314                "g MATCH (a)-[e]->{3,1}(b) COLUMNS (a.id)",
2315                "lower bound 3 is above its upper bound 1",
2316            ),
2317            (
2318                "g MATCH (a)-[e]->{x}(b) COLUMNS (a.id)",
2319                "expected a number or ','",
2320            ),
2321            (
2322                "g MATCH ((a)-[e]->(b))* COLUMNS (a.id)",
2323                "parenthesized path patterns",
2324            ),
2325            ("g MATCH (a:x|y) COLUMNS (a.id)", "label expressions"),
2326            (
2327                "g MATCH ()-[]->()",
2328                "a GRAPH_TABLE without COLUMNS returns the properties of the pattern's named nodes and edges",
2329            ),
2330            (
2331                "g MATCH ()-[]->() COLUMNS (*)",
2332                "COLUMNS (*) returns the properties of the pattern's named nodes and edges, and it names none",
2333            ),
2334            (
2335                "g (a) COLUMNS (a.id)",
2336                "expected MATCH after the graph's name, found '('",
2337            ),
2338            (
2339                "g MATCH (a)-[e]=>(b) COLUMNS (a.id)",
2340                "expected '->' or '-' after ']'",
2341            ),
2342            (
2343                "g MATCH (a b c) COLUMNS (a.id)",
2344                "expected a variable, ':label', WHERE or ')'",
2345            ),
2346            ("g MATCH (a) COLUMNS (a.id) extra", "unexpected 'extra'"),
2347            ("g MATCH (a) COLUMNS ()", "COLUMNS (…) lists nothing"),
2348        ] {
2349            let message = parse(body).unwrap_err().to_string();
2350            assert!(message.contains(expected), "{body}\n{message}");
2351        }
2352    }
2353
2354    #[test]
2355    fn columns_left_out_or_star_are_every_named_element() {
2356        for body in [
2357            "g MATCH (a:x)-[k:y]->(b), (b)-[]->(\"C\")",
2358            "g MATCH (a:x)-[k:y]->(b), (b)-[]->(\"C\") COLUMNS (*)",
2359            "g MATCH (a:x)-[k:y]->(b), (b)-[]->(\"C\") COLUMNS ( * )",
2360        ] {
2361            assert_eq!(
2362                parse(body).unwrap().columns,
2363                r#""a".*, "k".*, "b".*, "C".*"#,
2364                "{body}"
2365            );
2366        }
2367        // An edge that stands for several edges has no properties to return.
2368        assert_eq!(
2369            parse("g MATCH (a)-[k]->{1,2}(b), p = (b)-[f]->(c)")
2370                .unwrap()
2371                .columns,
2372            r#""a".*, "b".*, "c".*"#
2373        );
2374        // Other uses of * are left to the planner.
2375        assert_eq!(
2376            parse("g MATCH (a) COLUMNS (*, a.id)").unwrap().columns,
2377            "*, a.id"
2378        );
2379    }
2380
2381    #[test]
2382    fn either_direction_edges_and_tilde_edges() {
2383        for path in ["(a)<-[e]->(b)", "(a)<-[e]- >(b)", "(a)<->(b)", "(a)<- >(b)"] {
2384            let p = parse(&format!("g MATCH {path} COLUMNS (a.id)")).unwrap();
2385            assert_eq!(edges(&p.paths[0]), vec![(Direction::Any, None)], "{path}");
2386        }
2387        let p = parse("g MATCH (a)<-[e]->{1,3}(b) COLUMNS (a.id)").unwrap();
2388        assert_eq!(
2389            edges(&p.paths[0]),
2390            vec![(
2391                Direction::Any,
2392                Some(Quantifier {
2393                    min: 1,
2394                    max: Some(3)
2395                })
2396            )]
2397        );
2398        for path in [
2399            "(a)~[e]~(b)",
2400            "(a)<~[e]~(b)",
2401            "(a)~[e]~>(b)",
2402            "(a)~(b)",
2403            "(a)<~(b)",
2404            "(a)-[e]~(b)",
2405            "(a)<-[e]~(b)",
2406        ] {
2407            let message = parse(&format!("g MATCH {path} COLUMNS (a.id)"))
2408                .unwrap_err()
2409                .to_string();
2410            assert!(
2411                message.contains("Ursa's edges are directed; use -[e]- to follow them either way"),
2412                "{path}\n{message}"
2413            );
2414        }
2415    }
2416
2417    #[test]
2418    fn keep_and_one_row_per_match() {
2419        let path = |body: &str| {
2420            let p = parse(body).unwrap();
2421            (p.paths[0].selector, p.paths[0].mode, p.condition)
2422        };
2423        assert_eq!(
2424            path("g MATCH (a)-[e]->*(b) KEEP ANY SHORTEST COLUMNS (a.id)"),
2425            (Selector::Shortest(1), Mode::Walk, None)
2426        );
2427        assert_eq!(
2428            path("g MATCH (a)-[e]->*(b) KEEP SHORTEST 2 TRAIL PATHS WHERE a.id = 1 COLUMNS (a.id)"),
2429            (
2430                Selector::Shortest(2),
2431                Mode::Trail,
2432                Some("a.id = 1".to_string())
2433            )
2434        );
2435        // After WHERE too, as #409 found it written.
2436        assert_eq!(
2437            path("g MATCH (a)-[e]->*(b) WHERE a.id = 1 KEEP ACYCLIC COLUMNS (a.id)"),
2438            (Selector::All, Mode::Acyclic, Some("a.id = 1".to_string()))
2439        );
2440        // A mode before the path and a selector in KEEP.
2441        assert_eq!(
2442            path("g MATCH TRAIL (a)-[e]->*(b) KEEP ALL SHORTEST COLUMNS (a.id)"),
2443            (Selector::AllShortest, Mode::Trail, None)
2444        );
2445        // ONE ROW PER MATCH is the default; a property named keep is not KEEP.
2446        assert_eq!(
2447            path("g MATCH (a)-[e]->(b) WHERE a.keep = 1 ONE ROW PER MATCH COLUMNS (a.id)"),
2448            (Selector::All, Mode::Walk, Some("a.keep = 1".to_string()))
2449        );
2450        assert_eq!(
2451            path("g MATCH (a)-[e]->(b) ONE ROW PER MATCH"),
2452            (Selector::All, Mode::Walk, None)
2453        );
2454        for (body, expected) in [
2455            (
2456                "g MATCH (a)-[e]->*(b), (b)-[f]->*(c) KEEP ANY SHORTEST COLUMNS (a.id)",
2457                "KEEP over several path patterns is not supported yet",
2458            ),
2459            (
2460                "g MATCH ANY SHORTEST (a)-[e]->*(b) KEEP ANY SHORTEST COLUMNS (a.id)",
2461                "both before it and in KEEP",
2462            ),
2463            (
2464                "g MATCH (a)-[e]->*(b) KEEP COLUMNS (a.id)",
2465                "KEEP takes a path selector or path mode",
2466            ),
2467            (
2468                "g MATCH (a)-[e]->*(b) ONE ROW PER STEP (v1, e, v2) COLUMNS (a.id)",
2469                "ONE ROW PER VERTEX and ONE ROW PER STEP are not supported yet; return vertices(p) or edges(p)",
2470            ),
2471            (
2472                "g MATCH (a)-[e]->*(b) ONE ROW PER VERTEX (v) COLUMNS (a.id)",
2473                "ONE ROW PER VERTEX and ONE ROW PER STEP are not supported yet",
2474            ),
2475            (
2476                "g MATCH (a WHERE a.id = 1 KEEP TRAIL)-[e]->*(b) COLUMNS (a.id)",
2477                "KEEP goes after the whole pattern",
2478            ),
2479        ] {
2480            let message = parse(body).unwrap_err().to_string();
2481            assert!(message.contains(expected), "{body}\n{message}");
2482        }
2483    }
2484
2485    #[test]
2486    fn graph_predicates_are_rewritten_to_calls() {
2487        let p = parse(
2488            "g MATCH (a)-[k]->(b) WHERE k IS LABELED \"studyAt\" AND a IS NOT LABELED Person \
2489             AND a IS SOURCE OF k AND NOT b IS NOT DESTINATION OF k AND a.name IS NOT NULL \
2490             COLUMNS (a IS LABELED x AS l)",
2491        )
2492        .unwrap();
2493        assert_eq!(
2494            p.condition.as_deref(),
2495            Some(
2496                "__ursa_is_labeled(k, 'studyAt') AND (NOT __ursa_is_labeled(a, 'person')) \
2497                 AND __ursa_is_source(a, k) AND NOT (NOT __ursa_is_destination(b, k)) \
2498                 AND a.name IS NOT NULL"
2499            )
2500        );
2501        assert_eq!(p.columns, "__ursa_is_labeled(a, 'x') AS l");
2502        let message = parse("g MATCH (a) WHERE a IS LABELED x|y COLUMNS (a.id)")
2503            .unwrap_err()
2504            .to_string();
2505        assert!(message.contains("(#412)"), "{message}");
2506    }
2507
2508    #[test]
2509    fn cypher_habits_are_refused_with_the_sql_pgq_form() {
2510        for (body, expected) in [
2511            (
2512                "g MATCH (a:Person {name: 'Daniel'}) COLUMNS (a.id)",
2513                "property maps ({…}) are Cypher; write the condition with WHERE, as (a:Person WHERE a.name = 'Daniel')",
2514            ),
2515            (
2516                "g MATCH (:Person {name: 'Daniel', age: f(1, 2)}) COLUMNS (a.id)",
2517                "as (a:Person WHERE a.name = 'Daniel' AND a.age = f(1, 2))",
2518            ),
2519            (
2520                "g MATCH (a)-[k:knows {since: 2020}]->(b) COLUMNS (a.id)",
2521                "as [k:knows WHERE k.since = 2020]",
2522            ),
2523            (
2524                "g MATCH (a)-[k:knows*1..3]->(b) COLUMNS (a.id)",
2525                "*1..3 inside an edge's brackets is Cypher's range; in SQL/PGQ the quantifier follows the edge: write -[k:knows]->{1,3}",
2526            ),
2527            ("g MATCH (a)-[k*]->(b) COLUMNS (a.id)", "write -[k]->+"),
2528            ("g MATCH (a)-[:knows*2]-(b) COLUMNS (a.id)", "write -[:knows]-{2}"),
2529            ("g MATCH (a)<-[k*..4]-(b) COLUMNS (a.id)", "write <-[k]-{1,4}"),
2530            ("g MATCH (a)-[k * 2..]->(b) COLUMNS (a.id)", "write -[k]->{2,}"),
2531        ] {
2532            let message = parse(body).unwrap_err().to_string();
2533            assert!(message.contains(expected), "{body}\n{message}");
2534        }
2535    }
2536}