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