Skip to main content

ursa_engine/graph/view/
rules.rs

1//! The result → graph rules (design §3, #433): which rule draws a result,
2//! and from which of its columns.
3//!
4//! [`read`] says what each column is, **by provenance first, names second**,
5//! and then takes the first rule that matches:
6//!
7//! 1. a path column (`vertices(p)`, with `edges(p)` or `element_id(p)`), or
8//!    the steps of `shortest_path()`: **paths**;
9//! 2. `seed`, `id` and `distance` (a `hop` result): **rings**;
10//! 3. two endpoint columns: **edges**, a row an edge;
11//! 4. three or more node variables of `GRAPH_TABLE`: **pattern matches**;
12//! 5. one node key: **nodes**, with the graph's edges among them;
13//! 6. none of these: not a graph, and the message says what would be.
14//!
15//! Provenance is the `ursa.*` field metadata the graph functions and
16//! `GRAPH_TABLE` put on their output ([`crate::graph::provenance`]). A column
17//! without it is read by its name and type: `src`/`dst`, `source`/`target`
18//! and `from`/`to` are endpoints, `id` or `node` a node key, `seed`, `id`
19//! and `distance` together a hop result, a list of ids a path, and, last,
20//! the first two columns when both are ids of one kind, as before #433.
21//!
22//! A node key or an endpoint is an integer, a string or a date
23//! ([`id_kind`]): a float or a list is never a node id.
24//!
25//! A property graph named to `.graph` is drawn whole ([`Rule::Graph`]).
26//!
27//! An `AS …` clause is rule 0 ([`read_as`], #434): it names the shape and
28//! the columns, and nothing is inferred. Its columns must still be what the
29//! shape needs (ids, lists of ids, whole numbers), and a column that is not
30//! is an error that names it and lists the result's columns.
31
32use datafusion::arrow::datatypes::{DataType, Field, Schema};
33use datafusion::error::Result;
34use ursa_core::catalog::OutputKind;
35
36use super::clauses::{As, Name};
37use super::plan_err;
38use super::style::per_node_algorithm;
39use crate::graph::functions;
40use crate::graph::provenance as meta;
41
42/// The rule that drew a result. A result's provenance names it
43/// ([`Rule::name`]), for the pane's status line.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum Rule {
46    /// `.graph NAME`: a property graph's vertices and edges.
47    Graph,
48    /// Rows that are paths, or the steps of one (rule 1).
49    Path,
50    /// A `hop` result: seeds, the nodes reached and their distances (rule 2).
51    Rings,
52    /// Rows drawn as edges, one a row (rule 3).
53    Edges,
54    /// The matches of a `GRAPH_TABLE` pattern of three node variables or
55    /// more (rule 4).
56    Matches,
57    /// Rows that are nodes, with the graph's edges among them (rule 5).
58    Nodes,
59}
60
61impl Rule {
62    /// The rule's name in a result's provenance.
63    pub fn name(self) -> &'static str {
64        match self {
65            Rule::Graph => "graph",
66            Rule::Path => "path",
67            Rule::Rings => "rings",
68            Rule::Edges => "edges",
69            Rule::Matches => "pattern",
70            Rule::Nodes => "nodes",
71        }
72    }
73}
74
75/// One edge of a pattern, between two of the node variables in `COLUMNS`.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub(crate) struct MatchEdge {
78    /// The key columns of its two ends, as indexes into [`Shape::Matches`]'s
79    /// `keys`.
80    pub from: usize,
81    pub to: usize,
82    pub directed: bool,
83    /// The edge table.
84    pub label: String,
85}
86
87/// What a result's rows are, by the rule that matched: the columns to read.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub(crate) enum Shape {
90    /// Each row is an edge between the ids in columns `src` and `dst`.
91    Edges { src: usize, dst: usize },
92    /// Each row is a path: its nodes in a list column, or its nodes and
93    /// edges alternating in `elements`; `edges` is its edges' rows.
94    Path {
95        nodes: Option<usize>,
96        edges: Option<usize>,
97        elements: Option<usize>,
98    },
99    /// Each row is a step of a path (`shortest_path()`): an edge, and its
100    /// position.
101    Steps { src: usize, dst: usize, step: usize },
102    /// Each row is a node reached from a seed, and how far.
103    Hop {
104        seed: usize,
105        id: usize,
106        distance: usize,
107    },
108    /// Each row is a match of a pattern: the key column of each node
109    /// variable, and the pattern's edges between them.
110    Matches {
111        keys: Vec<usize>,
112        edges: Vec<MatchEdge>,
113    },
114    /// Each row is a node.
115    Nodes { id: usize },
116}
117
118impl Shape {
119    pub(crate) fn rule(&self) -> Rule {
120        match self {
121            Shape::Edges { .. } => Rule::Edges,
122            Shape::Path { .. } | Shape::Steps { .. } => Rule::Path,
123            Shape::Hop { .. } => Rule::Rings,
124            Shape::Matches { .. } => Rule::Matches,
125            Shape::Nodes { .. } => Rule::Nodes,
126        }
127    }
128}
129
130/// A result as the rules read it.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub(crate) struct Reading {
133    pub shape: Shape,
134    /// The property graph the node columns say they are from (`ursa.graph`).
135    pub graph: Option<String>,
136    /// Whether the columns were read by their metadata (else by name).
137    pub marked: bool,
138    /// The vertex table of each key column the shape reads: (column, table).
139    pub labels: Vec<(usize, String)>,
140    /// The edge table of the edges, if the result says.
141    pub edge_label: Option<String>,
142    /// Columns that become edge columns: numbers, one per row.
143    pub attributes: Vec<usize>,
144    /// Columns that describe nodes: (column, the key column of its nodes).
145    pub properties: Vec<(usize, usize)>,
146    /// Rule 5's defaults: the column that sizes the nodes and the one that
147    /// colours them.
148    pub size: Option<usize>,
149    pub color: Option<usize>,
150    /// Each column the drawing reads, and what as: (name, role).
151    pub roles: Vec<(String, String)>,
152    /// What the status line adds: what was left out, and other readings.
153    pub notes: Vec<String>,
154}
155
156impl Reading {
157    fn of(shape: Shape) -> Reading {
158        Reading {
159            shape,
160            graph: None,
161            marked: false,
162            labels: Vec::new(),
163            edge_label: None,
164            attributes: Vec::new(),
165            properties: Vec::new(),
166            size: None,
167            color: None,
168            roles: Vec::new(),
169            notes: Vec::new(),
170        }
171    }
172
173    /// The vertex table of key column `column`, if the result says.
174    pub(crate) fn label_of(&self, column: usize) -> Option<&str> {
175        self.labels
176            .iter()
177            .find(|(c, _)| *c == column)
178            .map(|(_, l)| l.as_str())
179    }
180}
181
182/// The most columns carried as edge columns or node properties.
183const MAX_CARRIED: usize = 8;
184
185/// The first rule that matches a result of `schema`, or why none does.
186#[cfg(test)]
187pub(crate) fn shape_of(schema: &Schema) -> Result<Shape> {
188    Ok(read(schema)?.shape)
189}
190
191/// A column's metadata.
192struct Col<'a> {
193    i: usize,
194    field: &'a Field,
195    role: Option<&'a str>,
196    graph: Option<&'a str>,
197    label: Option<&'a str>,
198    var: Option<&'a str>,
199}
200
201impl Col<'_> {
202    fn name(&self) -> &str {
203        self.field.name()
204    }
205    fn is(&self, role: &str) -> bool {
206        self.role == Some(role)
207    }
208    fn is_id(&self) -> bool {
209        id_kind(self.field.data_type()).is_some()
210    }
211}
212
213/// The type of a list column's elements.
214fn list_of(t: &DataType) -> Option<&DataType> {
215    match t {
216        DataType::List(f)
217        | DataType::LargeList(f)
218        | DataType::FixedSizeList(f, _)
219        | DataType::ListView(f)
220        | DataType::LargeListView(f) => Some(f.data_type()),
221        _ => None,
222    }
223}
224
225fn is_id_list(t: &DataType) -> bool {
226    list_of(t).is_some_and(|e| id_kind(e).is_some())
227}
228
229/// What a column named `name` holds per node, if it is named after an
230/// algorithm or, for a category, is one of the usual names for a group.
231fn kind_by_name(name: &str, t: &DataType) -> Option<OutputKind> {
232    let name = name.to_ascii_lowercase();
233    if let Some(kind) = functions::lookup(&name)
234        .filter(|s| functions::is_per_node(s))
235        .and_then(|s| s.output_kind())
236    {
237        return match kind {
238            OutputKind::Metric if !t.is_numeric() => None,
239            kind => Some(kind),
240        };
241    }
242    matches!(
243        name.as_str(),
244        "community" | "component" | "cluster" | "label" | "group"
245    )
246    .then_some(OutputKind::Category)
247}
248
249/// What the rules make of a result of `schema`: the first rule that matches,
250/// or why none does (rule 6).
251pub(crate) fn read(schema: &Schema) -> Result<Reading> {
252    let cols: Vec<Col> = schema
253        .fields()
254        .iter()
255        .enumerate()
256        .map(|(i, f)| {
257            let get = |key: &str| f.metadata().get(key).map(String::as_str);
258            Col {
259                i,
260                field: f.as_ref(),
261                role: get(meta::ROLE),
262                graph: get(meta::GRAPH),
263                label: get(meta::LABEL),
264                var: get(meta::VAR),
265            }
266        })
267        .collect();
268    if cols.iter().any(|c| c.role.is_some()) {
269        if let Some(reading) = read_marked(schema, &cols)? {
270            return Ok(reading);
271        }
272    }
273    read_named(schema, &cols)
274}
275
276/// The result's columns and their types, for a message.
277fn columns_of(schema: &Schema) -> String {
278    let columns: Vec<String> = schema
279        .fields()
280        .iter()
281        .map(|f| format!("{} ({})", f.name(), f.data_type()))
282        .collect();
283    match columns.len() {
284        0 => "The result has no columns".to_string(),
285        1 => format!("The result's one column is {}", columns[0]),
286        _ => format!("The result's columns are {}", columns.join(", ")),
287    }
288}
289
290/// Rule 0: a result read as its `AS …` clause says. The clause names the
291/// columns; a column that is missing, or is not what the shape needs, is an
292/// error that names it, lists the result's columns and says what to write.
293///
294/// What the columns say of themselves still counts where the clause says
295/// nothing: their vertex and edge tables, and their graph (`ursa.graph`)
296/// unless `ON graph` names one (`on`).
297pub(crate) fn read_as(schema: &Schema, clause: &As, on: bool) -> Result<Reading> {
298    let written = clause.shown();
299    let columns = columns_of(schema);
300    // The column a name names: as written, or else, unquoted, in any case.
301    let find = |name: &Name| -> Result<usize> {
302        let fields = schema.fields();
303        let exact = fields.iter().position(|f| f.name() == &name.ident);
304        let quoted = name.shown.starts_with('"');
305        let found = exact.or_else(|| {
306            let mut any = fields
307                .iter()
308                .enumerate()
309                .filter(|(_, f)| !quoted && f.name().eq_ignore_ascii_case(&name.ident));
310            match (any.next(), any.next()) {
311                (Some((i, _)), None) => Some(i),
312                _ => None,
313            }
314        });
315        match found {
316            Some(i) => Ok(i),
317            None => plan_err(format!(
318                "{written}: the result has no column {}. {columns}; name one of them",
319                name.shown
320            )),
321        }
322    };
323    let get = |i: usize, key: &str| schema.field(i).metadata().get(key).cloned();
324    let wrong = |i: usize, needs: &str| -> Result<usize> {
325        let f = schema.field(i);
326        plan_err(format!(
327            "{written}: column {} is {} ({}), and {needs}. {columns}",
328            f.name(),
329            what_is(f.data_type()),
330            f.data_type()
331        ))
332    };
333    // A column that holds node ids.
334    let id = |name: &Name, what: &str| -> Result<usize> {
335        let i = find(name)?;
336        match id_kind(schema.field(i).data_type()) {
337            Some(_) => Ok(i),
338            None => wrong(
339                i,
340                &format!("{what} is an id: an integer, a string or a date"),
341            ),
342        }
343    };
344    let role = |i: usize, role: &str| (schema.field(i).name().to_string(), role.to_string());
345    let mut r = match clause {
346        As::Edges { src, dst, weight } => {
347            let (s, d) = (id(src, "an edge's end")?, id(dst, "an edge's end")?);
348            if s == d {
349                return plan_err(format!(
350                    "{written}: both ends are the column {}, so every edge would join a node \
351                     to itself. Name the two columns of an edge's ends. {columns}",
352                    schema.field(s).name()
353                ));
354            }
355            let mut r = Reading::of(Shape::Edges { src: s, dst: d });
356            r.roles = vec![role(s, meta::ROLE_SRC), role(d, meta::ROLE_DST)];
357            if let Some(weight) = weight {
358                let w = find(weight)?;
359                if !schema.field(w).data_type().is_numeric() {
360                    wrong(w, "an edge's weight is a number")?;
361                }
362                r.attributes.push(w);
363                r.roles.push(role(w, "weight"));
364            }
365            r.edge_label = schema
366                .fields()
367                .iter()
368                .find(|f| f.metadata().get(meta::ROLE).map(String::as_str) == Some(meta::ROLE_EDGE))
369                .and_then(|f| f.metadata().get(meta::LABEL).cloned());
370            r
371        }
372        As::Nodes { id: key } => {
373            let k = id(key, "a node's id")?;
374            let mut r = Reading::of(Shape::Nodes { id: k });
375            r.roles.push(role(k, meta::ROLE_NODE));
376            // The defaults of rule 5: the first metric sizes the nodes and
377            // the first category colours them.
378            let kind = |f: &Field| match f.metadata().get(meta::ROLE).map(String::as_str) {
379                Some(meta::ROLE_METRIC) => Some(OutputKind::Metric),
380                Some(meta::ROLE_CATEGORY) => Some(OutputKind::Category),
381                Some(_) => None,
382                None => kind_by_name(f.name(), f.data_type()),
383            };
384            let others = || {
385                schema
386                    .fields()
387                    .iter()
388                    .enumerate()
389                    .filter(|(i, _)| *i != k)
390                    .map(|(i, f)| (i, f.as_ref()))
391            };
392            if let Some((i, _)) = others()
393                .find(|(_, f)| kind(f) == Some(OutputKind::Metric) && f.data_type().is_numeric())
394            {
395                r.size = Some(i);
396                r.roles.push(role(i, meta::ROLE_METRIC));
397            }
398            if let Some((i, _)) = others().find(|(_, f)| kind(f) == Some(OutputKind::Category)) {
399                r.color = Some(i);
400                r.roles.push(role(i, meta::ROLE_CATEGORY));
401            }
402            r
403        }
404        As::Path { nodes, edges } => {
405            let n = find(nodes)?;
406            if !is_id_list(schema.field(n).data_type()) {
407                wrong(
408                    n,
409                    "a path's nodes are a list of ids (integers, strings or dates), as \
410                     vertices(p) gives",
411                )?;
412            }
413            let e = match edges {
414                None => None,
415                Some(edges) => {
416                    let e = find(edges)?;
417                    if !list_of(schema.field(e).data_type()).is_some_and(DataType::is_integer) {
418                        wrong(
419                            e,
420                            "a path's edges are a list of the edges' row numbers, as edges(p) \
421                             gives; leave it out to draw the nodes alone, AS path(nodes)",
422                        )?;
423                    }
424                    Some(e)
425                }
426            };
427            // element_id(p) is nodes and edges alternating.
428            let elements = get(n, meta::ROLE).as_deref() == Some(meta::ROLE_PATH_ELEMENTS);
429            let mut r = Reading::of(Shape::Path {
430                nodes: (!elements).then_some(n),
431                edges: e.filter(|_| !elements),
432                elements: elements.then_some(n),
433            });
434            r.roles.push(role(
435                n,
436                if elements {
437                    meta::ROLE_PATH_ELEMENTS
438                } else {
439                    meta::ROLE_PATH_NODES
440                },
441            ));
442            if let Some(e) = e.filter(|_| !elements) {
443                r.roles.push(role(e, meta::ROLE_PATH_EDGES));
444                r.edge_label = get(e, meta::LABEL);
445            }
446            r
447        }
448        As::Hops {
449            seed,
450            id: key,
451            distance,
452        } => {
453            let (s, k) = (id(seed, "a seed")?, id(key, "a node reached")?);
454            let d = find(distance)?;
455            if !schema.field(d).data_type().is_integer() {
456                wrong(
457                    d,
458                    "a distance is a whole number of steps (CAST it to INTEGER if it is one)",
459                )?;
460            }
461            let mut r = Reading::of(Shape::Hop {
462                seed: s,
463                id: k,
464                distance: d,
465            });
466            r.roles = vec![
467                role(s, meta::ROLE_SEED),
468                role(k, meta::ROLE_NODE),
469                role(d, meta::ROLE_DISTANCE),
470            ];
471            r
472        }
473    };
474    // What the key columns say of themselves: their graph and their tables.
475    let keys: Vec<usize> = match &r.shape {
476        Shape::Edges { src, dst } => vec![*src, *dst],
477        Shape::Nodes { id } => vec![*id],
478        Shape::Path {
479            nodes, elements, ..
480        } => nodes.iter().chain(elements).copied().collect(),
481        Shape::Hop { seed, id, .. } => vec![*seed, *id],
482        Shape::Steps { .. } | Shape::Matches { .. } => Vec::new(),
483    };
484    for &k in &keys {
485        if let Some(label) = get(k, meta::LABEL) {
486            r.labels.push((k, label));
487            r.marked = true;
488        }
489        if let Some(graph) = get(k, meta::GRAPH).filter(|_| !on) {
490            match &r.graph {
491                Some(other) if *other != graph => {
492                    return plan_err(format!(
493                        "{written}: the columns come from the graphs {other} and {graph}, and \
494                         ids of two graphs do not meet. Name columns of one graph, or say \
495                         which graph the ids belong to: ON {other}"
496                    ))
497                }
498                _ => r.graph = Some(graph),
499            }
500        }
501    }
502    Ok(r)
503}
504
505/// The roles a node's key has.
506const KEY_ROLES: [&str; 6] = [
507    meta::ROLE_NODE,
508    meta::ROLE_SRC,
509    meta::ROLE_DST,
510    meta::ROLE_SEED,
511    meta::ROLE_PATH_NODES,
512    meta::ROLE_PATH_ELEMENTS,
513];
514
515/// The reading of a result some of whose columns say what they are, or
516/// `None` if they are not enough for a rule.
517fn read_marked(schema: &Schema, cols: &[Col]) -> Result<Option<Reading>> {
518    let first = |role: &str| cols.iter().find(|c| c.is(role));
519    let key = |role: &str| cols.iter().find(|c| c.is(role) && c.is_id());
520    let done = |mut r: Reading, used: &[&Col]| -> Result<Option<Reading>> {
521        r.marked = true;
522        // The graph of the columns the drawing reads; ids of two graphs do
523        // not meet.
524        let mut graphs: Vec<&str> = Vec::new();
525        for c in used {
526            if let Some(g) = c
527                .graph
528                .filter(|_| c.role.is_some_and(|r| KEY_ROLES.contains(&r)))
529            {
530                if !graphs.contains(&g) {
531                    graphs.push(g);
532                }
533            }
534            r.roles
535                .push((c.name().to_string(), c.role.unwrap_or("").to_string()));
536            if let (Some(label), true) = (c.label, c.role.is_some_and(|r| KEY_ROLES.contains(&r))) {
537                r.labels.push((c.i, label.to_string()));
538            }
539        }
540        if graphs.len() > 1 {
541            return plan_err(format!(
542                "cannot draw this result as one graph: its node columns come from the graphs \
543                 {}, and ids of two graphs do not meet. Draw one graph's columns: .graph SELECT \
544                 … FROM …",
545                graphs.join(" and ")
546            ));
547        }
548        r.graph = graphs.first().map(|g| g.to_string());
549        Ok(Some(r))
550    };
551    let numbers = |skip: &[usize]| -> Vec<usize> {
552        cols.iter()
553            .filter(|c| !skip.contains(&c.i) && c.field.data_type().is_numeric())
554            .map(|c| c.i)
555            .take(MAX_CARRIED)
556            .collect()
557    };
558    let endpoints = (key(meta::ROLE_SRC), key(meta::ROLE_DST));
559
560    // Rule 1: a path column.
561    let path_nodes = cols
562        .iter()
563        .find(|c| c.is(meta::ROLE_PATH_NODES) && is_id_list(c.field.data_type()));
564    let path_elements = cols
565        .iter()
566        .find(|c| c.is(meta::ROLE_PATH_ELEMENTS) && is_id_list(c.field.data_type()));
567    if let Some(anchor) = path_nodes.or(path_elements) {
568        // The edges of the same path variable.
569        let edges = cols.iter().find(|c| {
570            c.is(meta::ROLE_PATH_EDGES)
571                && c.var == anchor.var
572                && list_of(c.field.data_type()).is_some_and(DataType::is_integer)
573        });
574        let elements = path_elements.filter(|c| c.var == anchor.var && path_nodes.is_none());
575        let mut r = Reading::of(Shape::Path {
576            nodes: path_nodes.map(|c| c.i),
577            edges: edges.filter(|_| path_nodes.is_some()).map(|c| c.i),
578            elements: elements.map(|c| c.i),
579        });
580        r.edge_label = edges.and_then(|c| c.label).map(str::to_string);
581        if let (Some(s), Some(d)) = endpoints {
582            r.notes.push(format!(
583                "also edges ({}, {}): .graph AS edges({}, {})",
584                s.name(),
585                d.name(),
586                s.name(),
587                d.name()
588            ));
589        }
590        let mut used = vec![anchor];
591        used.extend(edges.filter(|_| path_nodes.is_some()));
592        return done(r, &used);
593    }
594    // Rule 1 too: the steps of shortest_path(), in order.
595    if let (Some(s), Some(d), Some(step)) = (
596        endpoints.0,
597        endpoints.1,
598        first(meta::ROLE_STEP).filter(|c| c.field.data_type().is_integer()),
599    ) {
600        let mut r = Reading::of(Shape::Steps {
601            src: s.i,
602            dst: d.i,
603            step: step.i,
604        });
605        r.attributes = numbers(&[s.i, d.i, step.i]);
606        return done(r, &[s, d, step]);
607    }
608    // Rule 2: a hop result.
609    let seed = key(meta::ROLE_SEED);
610    let nodes: Vec<&Col> = cols
611        .iter()
612        .filter(|c| c.is(meta::ROLE_NODE) && c.is_id())
613        .collect();
614    if let (Some(seed), [id], Some(distance)) = (
615        seed,
616        nodes.as_slice(),
617        first(meta::ROLE_DISTANCE).filter(|c| c.field.data_type().is_integer()),
618    ) {
619        let r = Reading::of(Shape::Hop {
620            seed: seed.i,
621            id: id.i,
622            distance: distance.i,
623        });
624        return done(r, &[seed, id, distance]);
625    }
626    // Rule 3: endpoints by role.
627    if let (Some(s), Some(d)) = endpoints {
628        let mut r = Reading::of(Shape::Edges { src: s.i, dst: d.i });
629        r.attributes = numbers(&[s.i, d.i]);
630        r.edge_label = first(meta::ROLE_EDGE)
631            .and_then(|c| c.label)
632            .map(str::to_string);
633        return done(r, &[s, d]);
634    }
635    // A hop result without its distance: two keys are two ends.
636    if let (Some(seed), [id]) = (seed, nodes.as_slice()) {
637        let mut r = Reading::of(Shape::Edges {
638            src: seed.i,
639            dst: id.i,
640        });
641        r.notes.push(format!(
642            "no distance column, so no rings: each row is an edge {}–{}",
643            seed.name(),
644            id.name()
645        ));
646        return done(r, &[seed, id]);
647    }
648    // The columns that describe a key column's nodes: the properties of its
649    // pattern variable.
650    let properties = |keys: &[&Col]| -> Vec<(usize, usize)> {
651        cols.iter()
652            .filter(|c| c.is(meta::ROLE_PROPERTY) && c.var.is_some())
653            .filter_map(|c| {
654                let key = keys.iter().find(|k| k.var == c.var)?;
655                Some((c.i, key.i))
656            })
657            .take(MAX_CARRIED)
658            .collect()
659    };
660    match nodes.as_slice() {
661        [] => Ok(None),
662        // Rule 5: one node key.
663        [id] => {
664            let mut r = Reading::of(Shape::Nodes { id: id.i });
665            let kind = |c: &Col| match c.role {
666                Some(meta::ROLE_METRIC) => Some(OutputKind::Metric),
667                Some(meta::ROLE_CATEGORY) => Some(OutputKind::Category),
668                Some(_) => None,
669                None => kind_by_name(c.name(), c.field.data_type()),
670            };
671            let others = || cols.iter().filter(|c| c.i != id.i);
672            let size = others()
673                .find(|c| kind(c) == Some(OutputKind::Metric) && c.field.data_type().is_numeric());
674            let color = others().find(|c| kind(c) == Some(OutputKind::Category));
675            r.size = size.map(|c| c.i);
676            r.color = color.map(|c| c.i);
677            let mut used = vec![*id];
678            used.extend(size);
679            used.extend(color);
680            let mut r = done(r, &used)?.expect("a reading");
681            // A column read by its name says so.
682            for c in size.into_iter().chain(color) {
683                if c.role.is_none() {
684                    let role = if Some(c.i) == r.size {
685                        meta::ROLE_METRIC
686                    } else {
687                        meta::ROLE_CATEGORY
688                    };
689                    if let Some(entry) = r.roles.iter_mut().find(|(n, _)| n == c.name()) {
690                        entry.1 = role.to_string();
691                    }
692                }
693            }
694            Ok(Some(r))
695        }
696        // Rule 3: two node keys are two ends (two variables of a pattern, or
697        // a self-join).
698        [a, b] => {
699            let mut r = Reading::of(Shape::Edges { src: a.i, dst: b.i });
700            r.properties = properties(&[a, b]);
701            let carried: Vec<usize> = r.properties.iter().map(|p| p.0).collect();
702            r.attributes = numbers(&[a.i, b.i])
703                .into_iter()
704                .filter(|i| !carried.contains(i))
705                .collect();
706            let pattern = pattern_of(schema);
707            r.edge_label = pattern
708                .iter()
709                .find(|e| {
710                    let ends = (e.from.as_deref(), e.to.as_deref());
711                    a.var.is_some() && (ends == (a.var, b.var) || ends == (b.var, a.var))
712                })
713                .map(|e| e.label.clone());
714            done(r, &[a, b])
715        }
716        // Rule 4: three node variables or more.
717        keys => {
718            let pattern = pattern_of(schema);
719            let at = |var: &Option<String>| {
720                let var = var.as_deref()?;
721                keys.iter().position(|k| k.var == Some(var))
722            };
723            let mut edges: Vec<MatchEdge> = Vec::new();
724            for e in &pattern {
725                if let (Some(from), Some(to)) = (at(&e.from), at(&e.to)) {
726                    edges.push(MatchEdge {
727                        from,
728                        to,
729                        directed: e.directed,
730                        label: e.label.clone(),
731                    });
732                }
733            }
734            if edges.is_empty() {
735                return Ok(None);
736            }
737            let mut r = Reading::of(Shape::Matches {
738                keys: keys.iter().map(|k| k.i).collect(),
739                edges,
740            });
741            r.properties = properties(keys);
742            done(r, keys)
743        }
744    }
745}
746
747/// The edges of the `GRAPH_TABLE` pattern a result of `schema` matched
748/// (`ursa.pattern`), or none.
749fn pattern_of(schema: &Schema) -> Vec<meta::PatternEdge> {
750    let Some(text) = schema.metadata().get(meta::PATTERN) else {
751        return Vec::new();
752    };
753    let Ok(serde_json::Value::Array(edges)) = serde_json::from_str(text) else {
754        return Vec::new();
755    };
756    edges
757        .iter()
758        .filter_map(|e| {
759            let text = |key: &str| e.get(key).and_then(|v| v.as_str()).map(str::to_string);
760            Some(meta::PatternEdge {
761                from: text("from"),
762                to: text("to"),
763                directed: e.get("directed")?.as_bool()?,
764                edge: text("edge"),
765                label: text("label")?,
766                quantifier: None,
767                path: text("path"),
768            })
769        })
770        .collect()
771}
772
773/// The reading of a result by its columns' names and types.
774fn read_named(schema: &Schema, cols: &[Col]) -> Result<Reading> {
775    let find = |name: &str| cols.iter().find(|c| c.name().eq_ignore_ascii_case(name));
776    let id = |name: &str| find(name).filter(|c| c.is_id());
777    let role = |c: &Col, role: &str| (c.name().to_string(), role.to_string());
778    let weight = |r: &mut Reading| {
779        r.attributes = find("weight")
780            .filter(|c| c.field.data_type().is_numeric())
781            .map(|c| c.i)
782            .into_iter()
783            .collect();
784    };
785    // Rule 3: endpoints by name. `src` and `dst` that are not ids are an
786    // error, not another shape: the names say what was meant.
787    if find("src").is_some() && find("dst").is_some() {
788        let (s, d) = endpoint_columns(schema)?;
789        let mut r = Reading::of(Shape::Edges { src: s, dst: d });
790        r.roles = vec![
791            role(&cols[s], meta::ROLE_SRC),
792            role(&cols[d], meta::ROLE_DST),
793        ];
794        weight(&mut r);
795        return Ok(r);
796    }
797    for (s, d) in [("source", "target"), ("from", "to")] {
798        if let (Some(s), Some(d)) = (id(s), id(d)) {
799            let mut r = Reading::of(Shape::Edges { src: s.i, dst: d.i });
800            r.roles = vec![role(s, meta::ROLE_SRC), role(d, meta::ROLE_DST)];
801            weight(&mut r);
802            return Ok(r);
803        }
804    }
805    // Rule 2: seed, id and distance together.
806    let key = id("id").or_else(|| id("node"));
807    if let (Some(seed), Some(key)) = (id("seed"), key) {
808        let distance = find("distance").filter(|c| c.field.data_type().is_integer());
809        let mut r = match distance {
810            Some(distance) => {
811                let mut r = Reading::of(Shape::Hop {
812                    seed: seed.i,
813                    id: key.i,
814                    distance: distance.i,
815                });
816                r.roles.push(role(distance, meta::ROLE_DISTANCE));
817                r
818            }
819            None => {
820                let mut r = Reading::of(Shape::Edges {
821                    src: seed.i,
822                    dst: key.i,
823                });
824                r.notes.push(format!(
825                    "no distance column, so no rings: each row is an edge {}–{}",
826                    seed.name(),
827                    key.name()
828                ));
829                r
830            }
831        };
832        r.roles.insert(0, role(key, meta::ROLE_NODE));
833        r.roles.insert(0, role(seed, meta::ROLE_SEED));
834        return Ok(r);
835    }
836    // Rule 5: a node key by name.
837    if let Some(key) = key {
838        let mut r = Reading::of(Shape::Nodes { id: key.i });
839        r.roles.push(role(key, meta::ROLE_NODE));
840        let others = || cols.iter().filter(|c| c.i != key.i);
841        let kind = |c: &Col| kind_by_name(c.name(), c.field.data_type());
842        if let Some(c) = others().find(|c| kind(c) == Some(OutputKind::Metric)) {
843            r.size = Some(c.i);
844            r.roles.push(role(c, meta::ROLE_METRIC));
845        }
846        if let Some(c) = others().find(|c| kind(c) == Some(OutputKind::Category)) {
847            r.color = Some(c.i);
848            r.roles.push(role(c, meta::ROLE_CATEGORY));
849        }
850        if let Some(path) = others().find(|c| is_id_list(c.field.data_type())) {
851            r.notes.push(format!(
852                "also a path ({}): .graph AS path({})",
853                path.name(),
854                path.name()
855            ));
856        }
857        return Ok(r);
858    }
859    // The first two columns, when both are ids of one kind, as ever.
860    let path = cols.iter().find(|c| is_id_list(c.field.data_type()));
861    if cols.len() >= 2 {
862        match (endpoint_columns(schema), path) {
863            (Ok((s, d)), _) => {
864                let mut r = Reading::of(Shape::Edges { src: s, dst: d });
865                r.roles = vec![
866                    role(&cols[s], meta::ROLE_SRC),
867                    role(&cols[d], meta::ROLE_DST),
868                ];
869                weight(&mut r);
870                if let Some(path) = path {
871                    r.notes.push(format!(
872                        "also a path ({}): .graph AS path({})",
873                        path.name(),
874                        path.name()
875                    ));
876                }
877                return Ok(r);
878            }
879            (Err(_), _) => {}
880        }
881    }
882    // Rule 1: a list of ids is a path.
883    if let Some(path) = path {
884        let mut r = Reading::of(Shape::Path {
885            nodes: Some(path.i),
886            edges: None,
887            elements: None,
888        });
889        r.roles.push(role(path, meta::ROLE_PATH_NODES));
890        return Ok(r);
891    }
892    Err(not_a_graph(schema))
893}
894
895/// Rule 6: a result that is not a graph. The message names the columns and
896/// their types, and the `AS` clause that would draw them.
897fn not_a_graph(schema: &Schema) -> datafusion::error::DataFusionError {
898    let columns: Vec<String> = schema
899        .fields()
900        .iter()
901        .map(|f| format!("{}: {}", f.name(), f.data_type()))
902        .collect();
903    let ids: Vec<&str> = schema
904        .fields()
905        .iter()
906        .filter(|f| id_kind(f.data_type()).is_some())
907        .map(|f| f.name().as_str())
908        .collect();
909    let lists: Vec<&str> = schema
910        .fields()
911        .iter()
912        .filter(|f| is_id_list(f.data_type()))
913        .map(|f| f.name().as_str())
914        .collect();
915    let mut says = Vec::new();
916    match ids.as_slice() {
917        [] => {}
918        [a] => says.push(format!("if {a} is a node's id: .graph AS nodes({a})")),
919        [a, b, ..] => {
920            says.push(format!(
921                "if {a} and {b} are the two ends of an edge: .graph AS edges({a}, {b})"
922            ));
923            says.push(format!("if {a} is a node's id: .graph AS nodes({a})"));
924        }
925    }
926    if let Some(l) = lists.first() {
927        says.push(format!("if {l} is a path's nodes: .graph AS path({l})"));
928    }
929    let says = if says.is_empty() {
930        "None of its columns can be a node's id (an integer, a string or a date). Draw a \
931         property graph by name (.graph NAME), or a query whose rows are edges: .graph SELECT … \
932         AS src, … AS dst FROM …"
933            .to_string()
934    } else {
935        format!(
936            "Say what its columns are: {}. Or name the ends in a query: .graph SELECT … AS src, \
937             … AS dst FROM …",
938            says.join("; ")
939        )
940    };
941    let n = schema.fields().len();
942    let detail = format!(
943        "cannot draw this result as a graph: it has {n} {} ({}), which {} not edges (columns \
944         src and dst, or two columns of ids), nodes (a column id), a hop result (seed, id, \
945         distance) or paths (a list of ids). {says}",
946        if n == 1 { "column" } else { "columns" },
947        columns.join(", "),
948        if n == 1 { "is" } else { "are" },
949    );
950    datafusion::error::DataFusionError::Plan(detail)
951}
952
953/// The kind of id a column of type `t` holds, if it can be a node's id: an
954/// integer, a string or a date. A float, a boolean, a list or a struct is a
955/// value, not an id (a score, a flag, a path), and drawing it as a node is
956/// nonsense.
957fn id_kind(t: &DataType) -> Option<&'static str> {
958    match t {
959        DataType::Dictionary(_, values) => id_kind(values),
960        DataType::Decimal128(_, 0) | DataType::Decimal256(_, 0) => Some("integer"),
961        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Some("string"),
962        DataType::Date32 | DataType::Date64 | DataType::Timestamp(_, _) => Some("date"),
963        t if t.is_integer() => Some("integer"),
964        _ => None,
965    }
966}
967
968/// What a column of type `t` holds, in a word, for the message.
969fn what_is(t: &DataType) -> String {
970    if let Some(element) = list_of(t) {
971        return match id_kind(element) {
972            Some(kind) => format!("a list of {kind}s"),
973            None => "a list".to_string(),
974        };
975    }
976    match id_kind(t) {
977        Some("integer") => "an integer".to_string(),
978        Some(kind) => format!("a {kind}"),
979        None => match value_kind(t) {
980            "not an id" => "a value that is no id or number".to_string(),
981            kind => kind.to_string(),
982        },
983    }
984}
985
986/// What a column that is no id is, in a word, for the message.
987fn value_kind(t: &DataType) -> &'static str {
988    match t {
989        DataType::Boolean => "a boolean",
990        DataType::Struct(_) => "a struct",
991        DataType::Map(_, _) => "a map",
992        DataType::List(_)
993        | DataType::LargeList(_)
994        | DataType::FixedSizeList(_, _)
995        | DataType::ListView(_)
996        | DataType::LargeListView(_) => "a list",
997        t if t.is_floating()
998            || matches!(t, DataType::Decimal128(_, _) | DataType::Decimal256(_, _)) =>
999        {
1000            "a number that is not whole"
1001        }
1002        _ => "not an id",
1003    }
1004}
1005
1006/// The columns that hold each edge's endpoints: `src` and `dst` (in any
1007/// case), or else the first two. Either way both must hold ids: an integer, a
1008/// string or a date. The first two columns must also be ids of one kind, since
1009/// nothing but their position says they are a pair.
1010pub fn endpoint_columns(schema: &Schema) -> Result<(usize, usize)> {
1011    let n = schema.fields().len();
1012    if n < 2 {
1013        return plan_err(format!(
1014            "the result has {n} column{}; a graph needs two, each edge's source and destination \
1015             (columns named src and dst, or else the first two)",
1016            if n == 1 { "" } else { "s" }
1017        ));
1018    }
1019    let find = |name: &str| {
1020        schema
1021            .fields()
1022            .iter()
1023            .position(|f| f.name().eq_ignore_ascii_case(name))
1024    };
1025    let (s, d, named) = match (find("src"), find("dst")) {
1026        (Some(s), Some(d)) => (s, d, true),
1027        _ => (0, 1, false),
1028    };
1029    let (source, destination) = (schema.field(s), schema.field(d));
1030    let kinds = (
1031        id_kind(source.data_type()),
1032        id_kind(destination.data_type()),
1033    );
1034    let what = match kinds {
1035        (Some(a), Some(b)) if named || a == b => return Ok((s, d)),
1036        (Some(a), Some(b)) => format!(
1037            "'{}' holds {a} ids and '{}' holds {b} ids, so they are not the two ends of an edge",
1038            source.name(),
1039            destination.name()
1040        ),
1041        _ => [(source, kinds.0), (destination, kinds.1)]
1042            .iter()
1043            .filter(|(_, kind)| kind.is_none())
1044            .map(|(f, _)| {
1045                format!(
1046                    "'{}' is {} ({})",
1047                    f.name(),
1048                    value_kind(f.data_type()),
1049                    f.data_type()
1050                )
1051            })
1052            .collect::<Vec<_>>()
1053            .join(" and "),
1054    };
1055    // A column named after a per-node algorithm is that algorithm's result.
1056    let metric = schema
1057        .fields()
1058        .iter()
1059        .find_map(|f| per_node_algorithm(&f.name().to_ascii_lowercase()))
1060        .unwrap_or("pagerank");
1061    plan_err(format!(
1062        "cannot draw {} as edges: {what}. An edge's ends are node ids (integers, strings or \
1063         dates, both of one kind). To draw an algorithm's result, draw the graph and size or \
1064         colour it: .graph NAME SIZE BY {metric}. To draw other rows, name the ends: \
1065         .graph SELECT … AS src, … AS dst FROM …",
1066        if named {
1067            "columns src and dst".to_string()
1068        } else {
1069            format!(
1070                "the first two columns ({}: {}, {}: {})",
1071                source.name(),
1072                source.data_type(),
1073                destination.name(),
1074                destination.data_type()
1075            )
1076        }
1077    ))
1078}