Skip to main content

ursa_engine/graph/view/
clauses.rs

1//! `.graph`'s text (design §3, #434):
2//!
3//! ```text
4//! [SOURCE] [ON graph]
5//!          [AS edges(src, dst [, weight]) | nodes(id) | path(nodes [, edges]) | hops(seed, id, distance)]
6//!          [NODES (query)] [SIZE BY x] [COLOR BY y] [LAYOUT force|rings|layers]
7//!          [POSITIONS (query)]
8//! ```
9//!
10//! [`parse`] splits it into the source and a [`Style`]; [`identifier`] says
11//! whether a source is one name.
12
13use datafusion::error::Result;
14use ursa_viz::model::Layout;
15
16use super::plan_err;
17
18/// What `.graph` text asks for besides its source.
19#[derive(Debug, Clone, Default, PartialEq)]
20pub struct Style {
21    /// `NODES (query)`: the query.
22    pub nodes: Option<String>,
23    pub size: Option<Name>,
24    pub color: Option<Name>,
25    /// `AS …`: what the result's rows are and the columns to read. It is
26    /// rule 0: with it, nothing is inferred.
27    pub shape: Option<As>,
28    /// `ON graph`: the property graph the result's ids belong to.
29    pub on: Option<Name>,
30    /// `LAYOUT …`: the layout, whatever the rule chose.
31    pub layout: Option<Layout>,
32    /// `POSITIONS (query)`: the query that says where each node is (#502).
33    /// With it, no layout runs.
34    pub positions: Option<String>,
35}
36
37/// An `AS …` clause: the shape of a result's rows, and its columns by name.
38#[derive(Debug, Clone, PartialEq)]
39pub enum As {
40    /// `AS edges(src, dst [, weight])`: a row is an edge.
41    Edges {
42        src: Name,
43        dst: Name,
44        weight: Option<Name>,
45    },
46    /// `AS nodes(id)`: a row is a node.
47    Nodes { id: Name },
48    /// `AS path(nodes [, edges])`: a row is a path, its nodes in a list
49    /// column and its edges' rows in another.
50    Path { nodes: Name, edges: Option<Name> },
51    /// `AS hops(seed, id, distance)`: a row is a node reached from a seed.
52    Hops {
53        seed: Name,
54        id: Name,
55        distance: Name,
56    },
57}
58
59impl As {
60    /// The clause as it is written, for a message.
61    pub fn shown(&self) -> String {
62        let join = |names: &[Option<&Name>]| {
63            names
64                .iter()
65                .flatten()
66                .map(|n| n.shown.as_str())
67                .collect::<Vec<_>>()
68                .join(", ")
69        };
70        match self {
71            As::Edges { src, dst, weight } => {
72                format!(
73                    "AS edges({})",
74                    join(&[Some(src), Some(dst), weight.as_ref()])
75                )
76            }
77            As::Nodes { id } => format!("AS nodes({})", id.shown),
78            As::Path { nodes, edges } => {
79                format!("AS path({})", join(&[Some(nodes), edges.as_ref()]))
80            }
81            As::Hops { seed, id, distance } => {
82                format!("AS hops({})", join(&[Some(seed), Some(id), Some(distance)]))
83            }
84        }
85    }
86}
87
88/// A name in a clause (`SIZE BY x`, `AS nodes(x)`, `ON g`): as SQL reads it (lower-cased unless
89/// quoted), and as typed.
90#[derive(Debug, Clone, PartialEq)]
91pub struct Name {
92    pub ident: String,
93    pub shown: String,
94}
95
96#[derive(Debug, Clone, Copy, PartialEq)]
97enum Tok {
98    Word,
99    Quoted,
100    Str,
101    Open,
102    Close,
103    Other,
104}
105
106/// `text` as tokens (kind, start, end), SQL's strings, quoted names and
107/// comments kept whole, so a word in them is never read as a clause.
108fn tokens(text: &str) -> Vec<(Tok, usize, usize)> {
109    let b = text.as_bytes();
110    let mut out = Vec::new();
111    let mut i = 0;
112    while i < b.len() {
113        let c = b[i];
114        let start = i;
115        if c.is_ascii_whitespace() {
116            i += 1;
117            continue;
118        }
119        if c == b'-' && b.get(i + 1) == Some(&b'-') {
120            while i < b.len() && b[i] != b'\n' {
121                i += 1;
122            }
123            continue;
124        }
125        if c == b'/' && b.get(i + 1) == Some(&b'*') {
126            i += 2;
127            while i < b.len() && !(b[i] == b'*' && b.get(i + 1) == Some(&b'/')) {
128                i += 1;
129            }
130            i = (i + 2).min(b.len());
131            continue;
132        }
133        let kind = if c == b'\'' || c == b'"' {
134            // To the closing quote; a doubled quote is one quote.
135            i += 1;
136            loop {
137                if i >= b.len() {
138                    break;
139                }
140                if b[i] == c {
141                    if b.get(i + 1) == Some(&c) {
142                        i += 2;
143                        continue;
144                    }
145                    i += 1;
146                    break;
147                }
148                i += 1;
149            }
150            if c == b'"' {
151                Tok::Quoted
152            } else {
153                Tok::Str
154            }
155        } else if c == b'(' {
156            i += 1;
157            Tok::Open
158        } else if c == b')' {
159            i += 1;
160            Tok::Close
161        } else if c.is_ascii_alphanumeric() || c == b'_' || c >= 0x80 {
162            while i < b.len()
163                && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'$' || b[i] >= 0x80)
164            {
165                i += 1;
166            }
167            Tok::Word
168        } else {
169            i += 1;
170            Tok::Other
171        };
172        out.push((kind, start, i));
173    }
174    out
175}
176
177/// `.graph`'s clauses, as a message that goes wrong shows them.
178pub const USAGE: &str = ".graph [SOURCE] [ON graph] [AS edges(src, dst [, weight]) | nodes(id) | \
179                         path(nodes [, edges]) | hops(seed, id, distance)] [NODES (SELECT id, … \
180                         FROM …)] [SIZE BY x] [COLOR BY y] [LAYOUT force|rings|layers] \
181                         [POSITIONS (SELECT id, x, y FROM …)]";
182
183/// The words a statement begins with: a source that begins with one is a
184/// query, not a name with clauses after it.
185const STATEMENTS: [&str; 22] = [
186    "SELECT",
187    "FROM",
188    "WITH",
189    "VALUES",
190    "TABLE",
191    "SHOW",
192    "DESCRIBE",
193    "DESC",
194    "EXPLAIN",
195    "SUMMARIZE",
196    "PIVOT",
197    "UNPIVOT",
198    "CREATE",
199    "DROP",
200    "INSERT",
201    "UPDATE",
202    "DELETE",
203    "COPY",
204    "SET",
205    "CALL",
206    "ALTER",
207    "MATCH",
208];
209
210/// The four forms of `AS …`, as a message shows them.
211const FORMS: &str =
212    "AS edges(src, dst [, weight]), AS nodes(id), AS path(nodes [, edges]) or AS hops(seed, id, \
213     distance)";
214
215/// The name a token is, if it is one: a word, lower-cased as SQL lower-cases
216/// names, or a quoted name, kept.
217fn name_of(text: &str, tok: Option<&(Tok, usize, usize)>) -> Option<Name> {
218    match tok {
219        Some(&(Tok::Word, s, e)) => Some(Name {
220            ident: text[s..e].to_lowercase(),
221            shown: text[s..e].to_string(),
222        }),
223        Some(&(Tok::Quoted, s, e)) if e - s > 2 && text[s..e].ends_with('"') => Some(Name {
224            ident: text[s + 1..e - 1].replace("\"\"", "\""),
225            shown: text[s..e].to_string(),
226        }),
227        _ => None,
228    }
229}
230
231/// The layout `word` names.
232fn layout_of(word: &str) -> Option<Layout> {
233    match word {
234        "FORCE" => Some(Layout::Force),
235        "RINGS" => Some(Layout::Rings),
236        "LAYERS" => Some(Layout::Layers),
237        _ => None,
238    }
239}
240
241/// Split `.graph`'s text into its source (empty for the last result) and
242/// the clauses after it: `ON graph`, `AS shape(columns)`, `NODES (query)`,
243/// `SIZE BY x`, `COLOR BY y`, `LAYOUT l` and `POSITIONS (query)`, in any
244/// order, each at most once. The clauses start at the first of these outside parentheses,
245/// strings and comments:
246///
247/// - `SIZE BY`, `COLOR BY` (or `COLOUR BY`), `NODES (`, `POSITIONS (`;
248/// - `AS edges(`, `AS nodes(`, `AS path(` or `AS hops(`. (SQL's own
249///   `FROM t AS edges(a, b)`, a table alias with column names, is read as the
250///   clause: give such an alias another name.)
251/// - `LAYOUT force`, `LAYOUT rings` or `LAYOUT layers`;
252/// - `ON name` followed by nothing or by another clause, unless it is the
253///   `ON` of a `JOIN`.
254///
255/// Text that begins with `AS`, `ON` or `LAYOUT` is clauses, with no source,
256/// and so is everything after a source that is one name (`karate LAYOUT
257/// spiral`): there a word that is no clause is an error that lists them. In
258/// a query, `AS edge(`, `AS node(`, `AS paths(` and `AS hop(` are read as the
259/// clause they were meant to be, for the same reason.
260pub fn parse(text: &str) -> Result<(String, Style)> {
261    let text = text.trim().trim_end_matches(';').trim_end();
262    let toks = tokens(text);
263    let word = |i: usize| -> Option<String> {
264        toks.get(i)
265            .filter(|t| t.0 == Tok::Word)
266            .map(|t| text[t.1..t.2].to_ascii_uppercase())
267    };
268    let kind = |i: usize| toks.get(i).map(|t| t.0);
269    // Whether a clause starts at token `i` of `n`. `ON name` is one only
270    // before the end or another clause.
271    fn starts(
272        i: usize,
273        word: &dyn Fn(usize) -> Option<String>,
274        kind: &dyn Fn(usize) -> Option<Tok>,
275        n: usize,
276    ) -> bool {
277        match word(i).as_deref() {
278            Some("SIZE" | "COLOR" | "COLOUR") => word(i + 1).as_deref() == Some("BY"),
279            Some("NODES" | "POSITIONS") => kind(i + 1) == Some(Tok::Open),
280            Some("AS") => {
281                i == 0
282                    || (matches!(
283                        word(i + 1).as_deref(),
284                        // The forms, and what is typed for them by mistake.
285                        Some(
286                            "EDGES" | "NODES" | "PATH" | "HOPS" | "EDGE" | "NODE" | "PATHS" | "HOP"
287                        )
288                    ) && kind(i + 2) == Some(Tok::Open))
289            }
290            Some("LAYOUT") => i == 0 || word(i + 1).as_deref().and_then(layout_of).is_some(),
291            Some("ON") => {
292                i == 0
293                    || (matches!(kind(i + 1), Some(Tok::Word | Tok::Quoted))
294                        && (i + 2 >= n || starts(i + 2, word, kind, n)))
295            }
296            _ => false,
297        }
298    }
299    let is_clause = |i: usize| starts(i, &word, &kind, toks.len());
300    let mut depth = 0i32;
301    // After a source that is one name (`karate`, not a statement), whatever
302    // follows is clauses: a word that is none is told so, not handed to SQL.
303    let named = !is_clause(0)
304        && match (toks.first(), kind(1)) {
305            (Some((Tok::Quoted, _, _)), Some(Tok::Word)) => true,
306            (Some((Tok::Word, _, _)), Some(Tok::Word)) => {
307                !STATEMENTS.contains(&word(0).unwrap_or_default().as_str())
308            }
309            _ => false,
310        };
311    let mut first = named.then_some(1);
312    // JOINs still waiting for their ON or USING: that ON is SQL's.
313    let mut joins = 0u32;
314    for (i, t) in toks.iter().enumerate() {
315        if first.is_some() {
316            break;
317        }
318        match t.0 {
319            Tok::Open => depth += 1,
320            Tok::Close => depth -= 1,
321            Tok::Word if depth == 0 => {
322                let w = word(i).unwrap_or_default();
323                match w.as_str() {
324                    "JOIN"
325                        if !matches!(
326                            i.checked_sub(1).and_then(&word).as_deref(),
327                            Some("CROSS" | "NATURAL")
328                        ) =>
329                    {
330                        joins += 1
331                    }
332                    "ON" | "USING" if joins > 0 => joins -= 1,
333                    _ if is_clause(i) => {
334                        first = Some(i);
335                        break;
336                    }
337                    _ => {}
338                }
339            }
340            _ => {}
341        }
342    }
343    let Some(mut i) = first else {
344        return Ok((text.to_string(), Style::default()));
345    };
346    let source = text[..toks[i].1].trim().to_string();
347    let mut style = Style::default();
348    // The token that closes the parenthesis opened at token `open`.
349    let closing = |open: usize| -> Option<usize> {
350        let mut depth = 0;
351        for (j, t) in toks.iter().enumerate().skip(open) {
352            match t.0 {
353                Tok::Open => depth += 1,
354                Tok::Close => {
355                    depth -= 1;
356                    if depth == 0 {
357                        return Some(j);
358                    }
359                }
360                _ => {}
361            }
362        }
363        None
364    };
365    while i < toks.len() {
366        let t = toks[i];
367        let shown = &text[t.1..t.2];
368        let keyword = word(i).unwrap_or_default();
369        match keyword.as_str() {
370            "NODES" if kind(i + 1) == Some(Tok::Open) => {
371                if style.nodes.is_some() {
372                    return plan_err(format!("NODES is given twice; give it once: {USAGE}"));
373                }
374                let open = toks[i + 1];
375                let Some(close) = closing(i + 1) else {
376                    return plan_err("NODES ( is not closed: NODES (SELECT id, … FROM …)");
377                };
378                let query = text[open.2..toks[close].1].trim();
379                if query.is_empty() {
380                    return plan_err("NODES () is empty: NODES (SELECT id, … FROM …)");
381                }
382                style.nodes = Some(query.to_string());
383                i = close + 1;
384            }
385            "POSITIONS" if kind(i + 1) == Some(Tok::Open) => {
386                const FORM: &str = "POSITIONS (SELECT id, x, y FROM …)";
387                if style.positions.is_some() {
388                    return plan_err(format!("POSITIONS is given twice; give it once: {USAGE}"));
389                }
390                let open = toks[i + 1];
391                let Some(close) = closing(i + 1) else {
392                    return plan_err(format!("POSITIONS ( is not closed: {FORM}"));
393                };
394                let query = text[open.2..toks[close].1].trim();
395                if query.is_empty() {
396                    return plan_err(format!(
397                        "POSITIONS () is empty; give the query that places the nodes: {FORM}"
398                    ));
399                }
400                style.positions = Some(query.to_string());
401                i = close + 1;
402            }
403            "POSITIONS" => {
404                return plan_err(
405                    "POSITIONS needs the query that places the nodes, in parentheses: POSITIONS \
406                     (SELECT id, x, y FROM …), as POSITIONS (SELECT * FROM 'pos.parquet')",
407                );
408            }
409            "SIZE" | "COLOR" | "COLOUR" if word(i + 1).as_deref() == Some("BY") => {
410                let clause = if keyword == "SIZE" {
411                    "SIZE BY"
412                } else {
413                    "COLOR BY"
414                };
415                let Some(name) = name_of(text, toks.get(i + 2)) else {
416                    let what = if keyword == "SIZE" {
417                        "a numeric column or an algorithm, as SIZE BY pagerank"
418                    } else {
419                        "a column of categories or an algorithm, as COLOR BY louvain"
420                    };
421                    return plan_err(format!("{clause} needs {what}"));
422                };
423                let slot = if keyword == "SIZE" {
424                    &mut style.size
425                } else {
426                    &mut style.color
427                };
428                if slot.is_some() {
429                    return plan_err(format!("{clause} is given twice; give it once: {USAGE}"));
430                }
431                *slot = Some(name);
432                i += 3;
433            }
434            "AS" => {
435                if style.shape.is_some() {
436                    return plan_err(format!(
437                        "AS is given twice; a result is drawn one way, so give one of {FORMS}"
438                    ));
439                }
440                let Some(form) = word(i + 1) else {
441                    return plan_err(format!(
442                        "AS needs what the result's rows are and the columns to read: {FORMS}"
443                    ));
444                };
445                let form_shown = &text[toks[i + 1].1..toks[i + 1].2];
446                let usage = match form.as_str() {
447                    "EDGES" => "AS edges(src, dst [, weight])",
448                    "NODES" => "AS nodes(id)",
449                    "PATH" => "AS path(nodes [, edges])",
450                    "HOPS" => "AS hops(seed, id, distance)",
451                    // What was probably meant.
452                    "EDGE" => {
453                        return plan_err(format!(
454                            "AS {form_shown} is not a form; write AS edges(src, dst [, weight]). \
455                             The forms are {FORMS}"
456                        ))
457                    }
458                    "NODE" => {
459                        return plan_err(format!(
460                            "AS {form_shown} is not a form; write AS nodes(id). The forms are \
461                             {FORMS}"
462                        ))
463                    }
464                    "PATHS" => {
465                        return plan_err(format!(
466                            "AS {form_shown} is not a form; write AS path(nodes [, edges]). The \
467                             forms are {FORMS}"
468                        ))
469                    }
470                    "HOP" | "RINGS" => {
471                        return plan_err(format!(
472                            "AS {form_shown} is not a form; write AS hops(seed, id, distance). \
473                             The forms are {FORMS}"
474                        ))
475                    }
476                    _ => {
477                        return plan_err(format!(
478                            "AS {form_shown} is not a form; write one of {FORMS}"
479                        ))
480                    }
481                };
482                if kind(i + 2) != Some(Tok::Open) {
483                    return plan_err(format!(
484                        "AS {form_shown} needs its columns in parentheses: {usage}"
485                    ));
486                }
487                let Some(close) = closing(i + 2) else {
488                    return plan_err(format!("AS {form_shown}( is not closed: {usage}"));
489                };
490                // Names, with a comma between each two.
491                let mut names = Vec::new();
492                let mut j = i + 3;
493                while j < close {
494                    let Some(name) = name_of(text, toks.get(j)) else {
495                        return plan_err(format!(
496                            "AS {form_shown}(…) takes the result's column names, with commas \
497                             between them, and '{}' is not one: {usage}",
498                            &text[toks[j].1..toks[j].2]
499                        ));
500                    };
501                    names.push(name);
502                    j += 1;
503                    if j < close {
504                        let comma = toks[j].0 == Tok::Other && &text[toks[j].1..toks[j].2] == ",";
505                        if !comma || j + 1 == close {
506                            return plan_err(format!(
507                                "AS {form_shown}(…) takes the result's column names, with \
508                                 commas between them: {usage}"
509                            ));
510                        }
511                        j += 1;
512                    }
513                }
514                let given = names.len();
515                let mut names = names.into_iter();
516                let mut next = || names.next().expect("counted");
517                let wrong = |takes: &str| -> Result<(String, Style)> {
518                    plan_err(format!(
519                        "AS {form_shown}(…) takes {takes}, and was given {given}: {usage}"
520                    ))
521                };
522                style.shape = Some(match (form.as_str(), given) {
523                    ("EDGES", 2 | 3) => As::Edges {
524                        src: next(),
525                        dst: next(),
526                        weight: names.next(),
527                    },
528                    ("EDGES", _) => {
529                        return wrong("the columns of an edge's two ends, and then its weight's")
530                    }
531                    ("NODES", 1) => As::Nodes { id: next() },
532                    ("NODES", _) => return wrong("one column, the node's id"),
533                    ("PATH", 1 | 2) => As::Path {
534                        nodes: next(),
535                        edges: names.next(),
536                    },
537                    ("PATH", _) => {
538                        return wrong(
539                            "the column of each path's nodes, and then the column of its edges",
540                        )
541                    }
542                    ("HOPS", 3) => As::Hops {
543                        seed: next(),
544                        id: next(),
545                        distance: next(),
546                    },
547                    _ => {
548                        return wrong("three columns: the seed, the node reached and its distance")
549                    }
550                });
551                i = close + 1;
552            }
553            "ON" => {
554                if style.on.is_some() {
555                    return plan_err(format!(
556                        "ON is given twice; a result's ids belong to one graph, so give it once: \
557                         {USAGE}"
558                    ));
559                }
560                let Some(name) = name_of(text, toks.get(i + 1)) else {
561                    return plan_err(
562                        "ON needs the name of the property graph the result's ids belong to, as \
563                         ON karate; .graphs lists the graphs",
564                    );
565                };
566                style.on = Some(name);
567                i += 2;
568            }
569            "LAYOUT" => {
570                if style.layout.is_some() {
571                    return plan_err(format!("LAYOUT is given twice; give it once: {USAGE}"));
572                }
573                let Some(layout) = word(i + 1).as_deref().and_then(layout_of) else {
574                    let given = match toks.get(i + 1) {
575                        Some(t) => format!(", and '{}' is none of them", &text[t.1..t.2]),
576                        None => String::new(),
577                    };
578                    return plan_err(format!(
579                        "LAYOUT needs force, rings or layers{given}: LAYOUT force lets the edges \
580                         pull the nodes into place, LAYOUT rings puts a hop result's nodes on \
581                         circles by distance, and LAYOUT layers puts them in rows"
582                    ));
583                };
584                style.layout = Some(layout);
585                i += 2;
586            }
587            _ => {
588                return plan_err(format!(
589                    "unexpected '{shown}' after the graph's source; the clauses are ON graph, \
590                     AS …, NODES (…), SIZE BY x, COLOR BY y, LAYOUT l and POSITIONS (…): {USAGE}"
591                ));
592            }
593        }
594    }
595    Ok((source, style))
596}
597
598/// What `.graph NAME` names, if NAME is one identifier: unquoted, it is
599/// lower-cased as SQL lower-cases names; quoted, it is kept.
600pub fn identifier(text: &str) -> Option<String> {
601    let text = text.trim();
602    if let Some(quoted) = text.strip_prefix('"').and_then(|t| t.strip_suffix('"')) {
603        if quoted.is_empty() || quoted.replace("\"\"", "").contains('"') {
604            return None;
605        }
606        return Some(quoted.replace("\"\"", "\""));
607    }
608    let mut chars = text.chars();
609    let first = chars.next()?;
610    if !(first.is_alphabetic() || first == '_')
611        || !chars.all(|c| c.is_alphanumeric() || c == '_' || c == '$')
612    {
613        return None;
614    }
615    Some(text.to_lowercase())
616}