use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::error::Result;
use ursa_core::catalog::OutputKind;
use super::clauses::{As, Name};
use super::plan_err;
use super::style::per_node_algorithm;
use crate::graph::functions;
use crate::graph::provenance as meta;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Rule {
Graph,
Path,
Rings,
Edges,
Matches,
Nodes,
}
impl Rule {
pub fn name(self) -> &'static str {
match self {
Rule::Graph => "graph",
Rule::Path => "path",
Rule::Rings => "rings",
Rule::Edges => "edges",
Rule::Matches => "pattern",
Rule::Nodes => "nodes",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MatchEdge {
pub from: usize,
pub to: usize,
pub directed: bool,
pub label: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Shape {
Edges { src: usize, dst: usize },
Path {
nodes: Option<usize>,
edges: Option<usize>,
elements: Option<usize>,
},
Steps { src: usize, dst: usize, step: usize },
Hop {
seed: usize,
id: usize,
distance: usize,
},
Matches {
keys: Vec<usize>,
edges: Vec<MatchEdge>,
},
Nodes { id: usize },
}
impl Shape {
pub(crate) fn rule(&self) -> Rule {
match self {
Shape::Edges { .. } => Rule::Edges,
Shape::Path { .. } | Shape::Steps { .. } => Rule::Path,
Shape::Hop { .. } => Rule::Rings,
Shape::Matches { .. } => Rule::Matches,
Shape::Nodes { .. } => Rule::Nodes,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Reading {
pub shape: Shape,
pub graph: Option<String>,
pub marked: bool,
pub labels: Vec<(usize, String)>,
pub edge_label: Option<String>,
pub attributes: Vec<usize>,
pub properties: Vec<(usize, usize)>,
pub size: Option<usize>,
pub color: Option<usize>,
pub roles: Vec<(String, String)>,
pub notes: Vec<String>,
}
impl Reading {
fn of(shape: Shape) -> Reading {
Reading {
shape,
graph: None,
marked: false,
labels: Vec::new(),
edge_label: None,
attributes: Vec::new(),
properties: Vec::new(),
size: None,
color: None,
roles: Vec::new(),
notes: Vec::new(),
}
}
pub(crate) fn label_of(&self, column: usize) -> Option<&str> {
self.labels
.iter()
.find(|(c, _)| *c == column)
.map(|(_, l)| l.as_str())
}
}
const MAX_CARRIED: usize = 8;
#[cfg(test)]
pub(crate) fn shape_of(schema: &Schema) -> Result<Shape> {
Ok(read(schema)?.shape)
}
struct Col<'a> {
i: usize,
field: &'a Field,
role: Option<&'a str>,
graph: Option<&'a str>,
label: Option<&'a str>,
var: Option<&'a str>,
}
impl Col<'_> {
fn name(&self) -> &str {
self.field.name()
}
fn is(&self, role: &str) -> bool {
self.role == Some(role)
}
fn is_id(&self) -> bool {
id_kind(self.field.data_type()).is_some()
}
}
fn list_of(t: &DataType) -> Option<&DataType> {
match t {
DataType::List(f)
| DataType::LargeList(f)
| DataType::FixedSizeList(f, _)
| DataType::ListView(f)
| DataType::LargeListView(f) => Some(f.data_type()),
_ => None,
}
}
fn is_id_list(t: &DataType) -> bool {
list_of(t).is_some_and(|e| id_kind(e).is_some())
}
fn kind_by_name(name: &str, t: &DataType) -> Option<OutputKind> {
let name = name.to_ascii_lowercase();
if let Some(kind) = functions::lookup(&name)
.filter(|s| functions::is_per_node(s))
.and_then(|s| s.output_kind())
{
return match kind {
OutputKind::Metric if !t.is_numeric() => None,
kind => Some(kind),
};
}
matches!(
name.as_str(),
"community" | "component" | "cluster" | "label" | "group"
)
.then_some(OutputKind::Category)
}
pub(crate) fn read(schema: &Schema) -> Result<Reading> {
let cols: Vec<Col> = schema
.fields()
.iter()
.enumerate()
.map(|(i, f)| {
let get = |key: &str| f.metadata().get(key).map(String::as_str);
Col {
i,
field: f.as_ref(),
role: get(meta::ROLE),
graph: get(meta::GRAPH),
label: get(meta::LABEL),
var: get(meta::VAR),
}
})
.collect();
if cols.iter().any(|c| c.role.is_some()) {
if let Some(reading) = read_marked(schema, &cols)? {
return Ok(reading);
}
}
read_named(schema, &cols)
}
fn columns_of(schema: &Schema) -> String {
let columns: Vec<String> = schema
.fields()
.iter()
.map(|f| format!("{} ({})", f.name(), f.data_type()))
.collect();
match columns.len() {
0 => "The result has no columns".to_string(),
1 => format!("The result's one column is {}", columns[0]),
_ => format!("The result's columns are {}", columns.join(", ")),
}
}
pub(crate) fn read_as(schema: &Schema, clause: &As, on: bool) -> Result<Reading> {
let written = clause.shown();
let columns = columns_of(schema);
let find = |name: &Name| -> Result<usize> {
let fields = schema.fields();
let exact = fields.iter().position(|f| f.name() == &name.ident);
let quoted = name.shown.starts_with('"');
let found = exact.or_else(|| {
let mut any = fields
.iter()
.enumerate()
.filter(|(_, f)| !quoted && f.name().eq_ignore_ascii_case(&name.ident));
match (any.next(), any.next()) {
(Some((i, _)), None) => Some(i),
_ => None,
}
});
match found {
Some(i) => Ok(i),
None => plan_err(format!(
"{written}: the result has no column {}. {columns}; name one of them",
name.shown
)),
}
};
let get = |i: usize, key: &str| schema.field(i).metadata().get(key).cloned();
let wrong = |i: usize, needs: &str| -> Result<usize> {
let f = schema.field(i);
plan_err(format!(
"{written}: column {} is {} ({}), and {needs}. {columns}",
f.name(),
what_is(f.data_type()),
f.data_type()
))
};
let id = |name: &Name, what: &str| -> Result<usize> {
let i = find(name)?;
match id_kind(schema.field(i).data_type()) {
Some(_) => Ok(i),
None => wrong(
i,
&format!("{what} is an id: an integer, a string or a date"),
),
}
};
let role = |i: usize, role: &str| (schema.field(i).name().to_string(), role.to_string());
let mut r = match clause {
As::Edges { src, dst, weight } => {
let (s, d) = (id(src, "an edge's end")?, id(dst, "an edge's end")?);
if s == d {
return plan_err(format!(
"{written}: both ends are the column {}, so every edge would join a node \
to itself. Name the two columns of an edge's ends. {columns}",
schema.field(s).name()
));
}
let mut r = Reading::of(Shape::Edges { src: s, dst: d });
r.roles = vec![role(s, meta::ROLE_SRC), role(d, meta::ROLE_DST)];
if let Some(weight) = weight {
let w = find(weight)?;
if !schema.field(w).data_type().is_numeric() {
wrong(w, "an edge's weight is a number")?;
}
r.attributes.push(w);
r.roles.push(role(w, "weight"));
}
r.edge_label = schema
.fields()
.iter()
.find(|f| f.metadata().get(meta::ROLE).map(String::as_str) == Some(meta::ROLE_EDGE))
.and_then(|f| f.metadata().get(meta::LABEL).cloned());
r
}
As::Nodes { id: key } => {
let k = id(key, "a node's id")?;
let mut r = Reading::of(Shape::Nodes { id: k });
r.roles.push(role(k, meta::ROLE_NODE));
let kind = |f: &Field| match f.metadata().get(meta::ROLE).map(String::as_str) {
Some(meta::ROLE_METRIC) => Some(OutputKind::Metric),
Some(meta::ROLE_CATEGORY) => Some(OutputKind::Category),
Some(_) => None,
None => kind_by_name(f.name(), f.data_type()),
};
let others = || {
schema
.fields()
.iter()
.enumerate()
.filter(|(i, _)| *i != k)
.map(|(i, f)| (i, f.as_ref()))
};
if let Some((i, _)) = others()
.find(|(_, f)| kind(f) == Some(OutputKind::Metric) && f.data_type().is_numeric())
{
r.size = Some(i);
r.roles.push(role(i, meta::ROLE_METRIC));
}
if let Some((i, _)) = others().find(|(_, f)| kind(f) == Some(OutputKind::Category)) {
r.color = Some(i);
r.roles.push(role(i, meta::ROLE_CATEGORY));
}
r
}
As::Path { nodes, edges } => {
let n = find(nodes)?;
if !is_id_list(schema.field(n).data_type()) {
wrong(
n,
"a path's nodes are a list of ids (integers, strings or dates), as \
vertices(p) gives",
)?;
}
let e = match edges {
None => None,
Some(edges) => {
let e = find(edges)?;
if !list_of(schema.field(e).data_type()).is_some_and(DataType::is_integer) {
wrong(
e,
"a path's edges are a list of the edges' row numbers, as edges(p) \
gives; leave it out to draw the nodes alone, AS path(nodes)",
)?;
}
Some(e)
}
};
let elements = get(n, meta::ROLE).as_deref() == Some(meta::ROLE_PATH_ELEMENTS);
let mut r = Reading::of(Shape::Path {
nodes: (!elements).then_some(n),
edges: e.filter(|_| !elements),
elements: elements.then_some(n),
});
r.roles.push(role(
n,
if elements {
meta::ROLE_PATH_ELEMENTS
} else {
meta::ROLE_PATH_NODES
},
));
if let Some(e) = e.filter(|_| !elements) {
r.roles.push(role(e, meta::ROLE_PATH_EDGES));
r.edge_label = get(e, meta::LABEL);
}
r
}
As::Hops {
seed,
id: key,
distance,
} => {
let (s, k) = (id(seed, "a seed")?, id(key, "a node reached")?);
let d = find(distance)?;
if !schema.field(d).data_type().is_integer() {
wrong(
d,
"a distance is a whole number of steps (CAST it to INTEGER if it is one)",
)?;
}
let mut r = Reading::of(Shape::Hop {
seed: s,
id: k,
distance: d,
});
r.roles = vec![
role(s, meta::ROLE_SEED),
role(k, meta::ROLE_NODE),
role(d, meta::ROLE_DISTANCE),
];
r
}
};
let keys: Vec<usize> = match &r.shape {
Shape::Edges { src, dst } => vec![*src, *dst],
Shape::Nodes { id } => vec![*id],
Shape::Path {
nodes, elements, ..
} => nodes.iter().chain(elements).copied().collect(),
Shape::Hop { seed, id, .. } => vec![*seed, *id],
Shape::Steps { .. } | Shape::Matches { .. } => Vec::new(),
};
for &k in &keys {
if let Some(label) = get(k, meta::LABEL) {
r.labels.push((k, label));
r.marked = true;
}
if let Some(graph) = get(k, meta::GRAPH).filter(|_| !on) {
match &r.graph {
Some(other) if *other != graph => {
return plan_err(format!(
"{written}: the columns come from the graphs {other} and {graph}, and \
ids of two graphs do not meet. Name columns of one graph, or say \
which graph the ids belong to: ON {other}"
))
}
_ => r.graph = Some(graph),
}
}
}
Ok(r)
}
const KEY_ROLES: [&str; 6] = [
meta::ROLE_NODE,
meta::ROLE_SRC,
meta::ROLE_DST,
meta::ROLE_SEED,
meta::ROLE_PATH_NODES,
meta::ROLE_PATH_ELEMENTS,
];
fn read_marked(schema: &Schema, cols: &[Col]) -> Result<Option<Reading>> {
let first = |role: &str| cols.iter().find(|c| c.is(role));
let key = |role: &str| cols.iter().find(|c| c.is(role) && c.is_id());
let done = |mut r: Reading, used: &[&Col]| -> Result<Option<Reading>> {
r.marked = true;
let mut graphs: Vec<&str> = Vec::new();
for c in used {
if let Some(g) = c
.graph
.filter(|_| c.role.is_some_and(|r| KEY_ROLES.contains(&r)))
{
if !graphs.contains(&g) {
graphs.push(g);
}
}
r.roles
.push((c.name().to_string(), c.role.unwrap_or("").to_string()));
if let (Some(label), true) = (c.label, c.role.is_some_and(|r| KEY_ROLES.contains(&r))) {
r.labels.push((c.i, label.to_string()));
}
}
if graphs.len() > 1 {
return plan_err(format!(
"cannot draw this result as one graph: its node columns come from the graphs \
{}, and ids of two graphs do not meet. Draw one graph's columns: .graph SELECT \
… FROM …",
graphs.join(" and ")
));
}
r.graph = graphs.first().map(|g| g.to_string());
Ok(Some(r))
};
let numbers = |skip: &[usize]| -> Vec<usize> {
cols.iter()
.filter(|c| !skip.contains(&c.i) && c.field.data_type().is_numeric())
.map(|c| c.i)
.take(MAX_CARRIED)
.collect()
};
let endpoints = (key(meta::ROLE_SRC), key(meta::ROLE_DST));
let path_nodes = cols
.iter()
.find(|c| c.is(meta::ROLE_PATH_NODES) && is_id_list(c.field.data_type()));
let path_elements = cols
.iter()
.find(|c| c.is(meta::ROLE_PATH_ELEMENTS) && is_id_list(c.field.data_type()));
if let Some(anchor) = path_nodes.or(path_elements) {
let edges = cols.iter().find(|c| {
c.is(meta::ROLE_PATH_EDGES)
&& c.var == anchor.var
&& list_of(c.field.data_type()).is_some_and(DataType::is_integer)
});
let elements = path_elements.filter(|c| c.var == anchor.var && path_nodes.is_none());
let mut r = Reading::of(Shape::Path {
nodes: path_nodes.map(|c| c.i),
edges: edges.filter(|_| path_nodes.is_some()).map(|c| c.i),
elements: elements.map(|c| c.i),
});
r.edge_label = edges.and_then(|c| c.label).map(str::to_string);
if let (Some(s), Some(d)) = endpoints {
r.notes.push(format!(
"also edges ({}, {}): .graph AS edges({}, {})",
s.name(),
d.name(),
s.name(),
d.name()
));
}
let mut used = vec![anchor];
used.extend(edges.filter(|_| path_nodes.is_some()));
return done(r, &used);
}
if let (Some(s), Some(d), Some(step)) = (
endpoints.0,
endpoints.1,
first(meta::ROLE_STEP).filter(|c| c.field.data_type().is_integer()),
) {
let mut r = Reading::of(Shape::Steps {
src: s.i,
dst: d.i,
step: step.i,
});
r.attributes = numbers(&[s.i, d.i, step.i]);
return done(r, &[s, d, step]);
}
let seed = key(meta::ROLE_SEED);
let nodes: Vec<&Col> = cols
.iter()
.filter(|c| c.is(meta::ROLE_NODE) && c.is_id())
.collect();
if let (Some(seed), [id], Some(distance)) = (
seed,
nodes.as_slice(),
first(meta::ROLE_DISTANCE).filter(|c| c.field.data_type().is_integer()),
) {
let r = Reading::of(Shape::Hop {
seed: seed.i,
id: id.i,
distance: distance.i,
});
return done(r, &[seed, id, distance]);
}
if let (Some(s), Some(d)) = endpoints {
let mut r = Reading::of(Shape::Edges { src: s.i, dst: d.i });
r.attributes = numbers(&[s.i, d.i]);
r.edge_label = first(meta::ROLE_EDGE)
.and_then(|c| c.label)
.map(str::to_string);
return done(r, &[s, d]);
}
if let (Some(seed), [id]) = (seed, nodes.as_slice()) {
let mut r = Reading::of(Shape::Edges {
src: seed.i,
dst: id.i,
});
r.notes.push(format!(
"no distance column, so no rings: each row is an edge {}–{}",
seed.name(),
id.name()
));
return done(r, &[seed, id]);
}
let properties = |keys: &[&Col]| -> Vec<(usize, usize)> {
cols.iter()
.filter(|c| c.is(meta::ROLE_PROPERTY) && c.var.is_some())
.filter_map(|c| {
let key = keys.iter().find(|k| k.var == c.var)?;
Some((c.i, key.i))
})
.take(MAX_CARRIED)
.collect()
};
match nodes.as_slice() {
[] => Ok(None),
[id] => {
let mut r = Reading::of(Shape::Nodes { id: id.i });
let kind = |c: &Col| match c.role {
Some(meta::ROLE_METRIC) => Some(OutputKind::Metric),
Some(meta::ROLE_CATEGORY) => Some(OutputKind::Category),
Some(_) => None,
None => kind_by_name(c.name(), c.field.data_type()),
};
let others = || cols.iter().filter(|c| c.i != id.i);
let size = others()
.find(|c| kind(c) == Some(OutputKind::Metric) && c.field.data_type().is_numeric());
let color = others().find(|c| kind(c) == Some(OutputKind::Category));
r.size = size.map(|c| c.i);
r.color = color.map(|c| c.i);
let mut used = vec![*id];
used.extend(size);
used.extend(color);
let mut r = done(r, &used)?.expect("a reading");
for c in size.into_iter().chain(color) {
if c.role.is_none() {
let role = if Some(c.i) == r.size {
meta::ROLE_METRIC
} else {
meta::ROLE_CATEGORY
};
if let Some(entry) = r.roles.iter_mut().find(|(n, _)| n == c.name()) {
entry.1 = role.to_string();
}
}
}
Ok(Some(r))
}
[a, b] => {
let mut r = Reading::of(Shape::Edges { src: a.i, dst: b.i });
r.properties = properties(&[a, b]);
let carried: Vec<usize> = r.properties.iter().map(|p| p.0).collect();
r.attributes = numbers(&[a.i, b.i])
.into_iter()
.filter(|i| !carried.contains(i))
.collect();
let pattern = pattern_of(schema);
r.edge_label = pattern
.iter()
.find(|e| {
let ends = (e.from.as_deref(), e.to.as_deref());
a.var.is_some() && (ends == (a.var, b.var) || ends == (b.var, a.var))
})
.map(|e| e.label.clone());
done(r, &[a, b])
}
keys => {
let pattern = pattern_of(schema);
let at = |var: &Option<String>| {
let var = var.as_deref()?;
keys.iter().position(|k| k.var == Some(var))
};
let mut edges: Vec<MatchEdge> = Vec::new();
for e in &pattern {
if let (Some(from), Some(to)) = (at(&e.from), at(&e.to)) {
edges.push(MatchEdge {
from,
to,
directed: e.directed,
label: e.label.clone(),
});
}
}
if edges.is_empty() {
return Ok(None);
}
let mut r = Reading::of(Shape::Matches {
keys: keys.iter().map(|k| k.i).collect(),
edges,
});
r.properties = properties(keys);
done(r, keys)
}
}
}
fn pattern_of(schema: &Schema) -> Vec<meta::PatternEdge> {
let Some(text) = schema.metadata().get(meta::PATTERN) else {
return Vec::new();
};
let Ok(serde_json::Value::Array(edges)) = serde_json::from_str(text) else {
return Vec::new();
};
edges
.iter()
.filter_map(|e| {
let text = |key: &str| e.get(key).and_then(|v| v.as_str()).map(str::to_string);
Some(meta::PatternEdge {
from: text("from"),
to: text("to"),
directed: e.get("directed")?.as_bool()?,
edge: text("edge"),
label: text("label")?,
quantifier: None,
path: text("path"),
})
})
.collect()
}
fn read_named(schema: &Schema, cols: &[Col]) -> Result<Reading> {
let find = |name: &str| cols.iter().find(|c| c.name().eq_ignore_ascii_case(name));
let id = |name: &str| find(name).filter(|c| c.is_id());
let role = |c: &Col, role: &str| (c.name().to_string(), role.to_string());
let weight = |r: &mut Reading| {
r.attributes = find("weight")
.filter(|c| c.field.data_type().is_numeric())
.map(|c| c.i)
.into_iter()
.collect();
};
if find("src").is_some() && find("dst").is_some() {
let (s, d) = endpoint_columns(schema)?;
let mut r = Reading::of(Shape::Edges { src: s, dst: d });
r.roles = vec![
role(&cols[s], meta::ROLE_SRC),
role(&cols[d], meta::ROLE_DST),
];
weight(&mut r);
return Ok(r);
}
for (s, d) in [("source", "target"), ("from", "to")] {
if let (Some(s), Some(d)) = (id(s), id(d)) {
let mut r = Reading::of(Shape::Edges { src: s.i, dst: d.i });
r.roles = vec![role(s, meta::ROLE_SRC), role(d, meta::ROLE_DST)];
weight(&mut r);
return Ok(r);
}
}
let key = id("id").or_else(|| id("node"));
if let (Some(seed), Some(key)) = (id("seed"), key) {
let distance = find("distance").filter(|c| c.field.data_type().is_integer());
let mut r = match distance {
Some(distance) => {
let mut r = Reading::of(Shape::Hop {
seed: seed.i,
id: key.i,
distance: distance.i,
});
r.roles.push(role(distance, meta::ROLE_DISTANCE));
r
}
None => {
let mut r = Reading::of(Shape::Edges {
src: seed.i,
dst: key.i,
});
r.notes.push(format!(
"no distance column, so no rings: each row is an edge {}–{}",
seed.name(),
key.name()
));
r
}
};
r.roles.insert(0, role(key, meta::ROLE_NODE));
r.roles.insert(0, role(seed, meta::ROLE_SEED));
return Ok(r);
}
if let Some(key) = key {
let mut r = Reading::of(Shape::Nodes { id: key.i });
r.roles.push(role(key, meta::ROLE_NODE));
let others = || cols.iter().filter(|c| c.i != key.i);
let kind = |c: &Col| kind_by_name(c.name(), c.field.data_type());
if let Some(c) = others().find(|c| kind(c) == Some(OutputKind::Metric)) {
r.size = Some(c.i);
r.roles.push(role(c, meta::ROLE_METRIC));
}
if let Some(c) = others().find(|c| kind(c) == Some(OutputKind::Category)) {
r.color = Some(c.i);
r.roles.push(role(c, meta::ROLE_CATEGORY));
}
if let Some(path) = others().find(|c| is_id_list(c.field.data_type())) {
r.notes.push(format!(
"also a path ({}): .graph AS path({})",
path.name(),
path.name()
));
}
return Ok(r);
}
let path = cols.iter().find(|c| is_id_list(c.field.data_type()));
if cols.len() >= 2 {
match (endpoint_columns(schema), path) {
(Ok((s, d)), _) => {
let mut r = Reading::of(Shape::Edges { src: s, dst: d });
r.roles = vec![
role(&cols[s], meta::ROLE_SRC),
role(&cols[d], meta::ROLE_DST),
];
weight(&mut r);
if let Some(path) = path {
r.notes.push(format!(
"also a path ({}): .graph AS path({})",
path.name(),
path.name()
));
}
return Ok(r);
}
(Err(_), _) => {}
}
}
if let Some(path) = path {
let mut r = Reading::of(Shape::Path {
nodes: Some(path.i),
edges: None,
elements: None,
});
r.roles.push(role(path, meta::ROLE_PATH_NODES));
return Ok(r);
}
Err(not_a_graph(schema))
}
fn not_a_graph(schema: &Schema) -> datafusion::error::DataFusionError {
let columns: Vec<String> = schema
.fields()
.iter()
.map(|f| format!("{}: {}", f.name(), f.data_type()))
.collect();
let ids: Vec<&str> = schema
.fields()
.iter()
.filter(|f| id_kind(f.data_type()).is_some())
.map(|f| f.name().as_str())
.collect();
let lists: Vec<&str> = schema
.fields()
.iter()
.filter(|f| is_id_list(f.data_type()))
.map(|f| f.name().as_str())
.collect();
let mut says = Vec::new();
match ids.as_slice() {
[] => {}
[a] => says.push(format!("if {a} is a node's id: .graph AS nodes({a})")),
[a, b, ..] => {
says.push(format!(
"if {a} and {b} are the two ends of an edge: .graph AS edges({a}, {b})"
));
says.push(format!("if {a} is a node's id: .graph AS nodes({a})"));
}
}
if let Some(l) = lists.first() {
says.push(format!("if {l} is a path's nodes: .graph AS path({l})"));
}
let says = if says.is_empty() {
"None of its columns can be a node's id (an integer, a string or a date). Draw a \
property graph by name (.graph NAME), or a query whose rows are edges: .graph SELECT … \
AS src, … AS dst FROM …"
.to_string()
} else {
format!(
"Say what its columns are: {}. Or name the ends in a query: .graph SELECT … AS src, \
… AS dst FROM …",
says.join("; ")
)
};
let n = schema.fields().len();
let detail = format!(
"cannot draw this result as a graph: it has {n} {} ({}), which {} not edges (columns \
src and dst, or two columns of ids), nodes (a column id), a hop result (seed, id, \
distance) or paths (a list of ids). {says}",
if n == 1 { "column" } else { "columns" },
columns.join(", "),
if n == 1 { "is" } else { "are" },
);
datafusion::error::DataFusionError::Plan(detail)
}
fn id_kind(t: &DataType) -> Option<&'static str> {
match t {
DataType::Dictionary(_, values) => id_kind(values),
DataType::Decimal128(_, 0) | DataType::Decimal256(_, 0) => Some("integer"),
DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Some("string"),
DataType::Date32 | DataType::Date64 | DataType::Timestamp(_, _) => Some("date"),
t if t.is_integer() => Some("integer"),
_ => None,
}
}
fn what_is(t: &DataType) -> String {
if let Some(element) = list_of(t) {
return match id_kind(element) {
Some(kind) => format!("a list of {kind}s"),
None => "a list".to_string(),
};
}
match id_kind(t) {
Some("integer") => "an integer".to_string(),
Some(kind) => format!("a {kind}"),
None => match value_kind(t) {
"not an id" => "a value that is no id or number".to_string(),
kind => kind.to_string(),
},
}
}
fn value_kind(t: &DataType) -> &'static str {
match t {
DataType::Boolean => "a boolean",
DataType::Struct(_) => "a struct",
DataType::Map(_, _) => "a map",
DataType::List(_)
| DataType::LargeList(_)
| DataType::FixedSizeList(_, _)
| DataType::ListView(_)
| DataType::LargeListView(_) => "a list",
t if t.is_floating()
|| matches!(t, DataType::Decimal128(_, _) | DataType::Decimal256(_, _)) =>
{
"a number that is not whole"
}
_ => "not an id",
}
}
pub fn endpoint_columns(schema: &Schema) -> Result<(usize, usize)> {
let n = schema.fields().len();
if n < 2 {
return plan_err(format!(
"the result has {n} column{}; a graph needs two, each edge's source and destination \
(columns named src and dst, or else the first two)",
if n == 1 { "" } else { "s" }
));
}
let find = |name: &str| {
schema
.fields()
.iter()
.position(|f| f.name().eq_ignore_ascii_case(name))
};
let (s, d, named) = match (find("src"), find("dst")) {
(Some(s), Some(d)) => (s, d, true),
_ => (0, 1, false),
};
let (source, destination) = (schema.field(s), schema.field(d));
let kinds = (
id_kind(source.data_type()),
id_kind(destination.data_type()),
);
let what = match kinds {
(Some(a), Some(b)) if named || a == b => return Ok((s, d)),
(Some(a), Some(b)) => format!(
"'{}' holds {a} ids and '{}' holds {b} ids, so they are not the two ends of an edge",
source.name(),
destination.name()
),
_ => [(source, kinds.0), (destination, kinds.1)]
.iter()
.filter(|(_, kind)| kind.is_none())
.map(|(f, _)| {
format!(
"'{}' is {} ({})",
f.name(),
value_kind(f.data_type()),
f.data_type()
)
})
.collect::<Vec<_>>()
.join(" and "),
};
let metric = schema
.fields()
.iter()
.find_map(|f| per_node_algorithm(&f.name().to_ascii_lowercase()))
.unwrap_or("pagerank");
plan_err(format!(
"cannot draw {} as edges: {what}. An edge's ends are node ids (integers, strings or \
dates, both of one kind). To draw an algorithm's result, draw the graph and size or \
colour it: .graph NAME SIZE BY {metric}. To draw other rows, name the ends: \
.graph SELECT … AS src, … AS dst FROM …",
if named {
"columns src and dst".to_string()
} else {
format!(
"the first two columns ({}: {}, {}: {})",
source.name(),
source.data_type(),
destination.name(),
destination.data_type()
)
}
))
}