Skip to main content

ursa_engine/graph/
define.rs

1//! Defining and dropping graphs: what `CREATE PROPERTY GRAPH` and
2//! `DROP PROPERTY GRAPH` do once parsed.
3//!
4//! A definition is checked when it is created: its tables exist, element
5//! names are unique, every vertex table has a key (written, or inferred from a
6//! primary key or the edges' `REFERENCES`, as DuckPGQ does), the named columns
7//! and properties exist, each edge table's endpoints have one node id type (an
8//! integer of any width, or a string), and each vertex key's type is
9//! compatible with the endpoints that refer to it. A table given as a file
10//! path is opened then (see the [module docs](super)).
11//!
12//! The tables are read afresh by every query. [`check_ddl`] keeps them from
13//! being dropped, or replaced by ones the definition no longer fits, by SQL
14//! while a graph uses them.
15
16use std::sync::Arc;
17
18use datafusion::arrow::datatypes::{DataType, Schema, SchemaRef};
19use datafusion::catalog::{CatalogProvider, TableProvider};
20use datafusion::common::utils::datafusion_strsim::levenshtein;
21use datafusion::common::Constraint;
22use datafusion::common::{ResolvedTableReference, SchemaReference, TableReference};
23use datafusion::error::{DataFusionError, Result};
24use datafusion::execution::context::SessionState;
25use datafusion::logical_expr::{DdlStatement, LogicalPlan};
26use datafusion::prelude::SessionContext;
27
28use super::schema::{graph_table, lookup_table, GraphSchema, EDGES, ID, NODES};
29use super::{
30    registry, EdgeTable, FileTable, GraphRegistry, Label, Properties, PropertyGraph, VertexTable,
31};
32use crate::database::check_available;
33use crate::file_table::open_file_table;
34use crate::paths::looks_like_location;
35
36/// The schema DataFusion reserves for `information_schema` views.
37const INFORMATION_SCHEMA: &str = "information_schema";
38
39/// A graph as `CREATE PROPERTY GRAPH` wrote it, its identifiers normalized,
40/// before [`create_graph`] resolves its vertex keys.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct GraphSpec {
43    pub name: String,
44    pub vertex_tables: Vec<VertexSpec>,
45    pub edge_tables: Vec<EdgeSpec>,
46}
47
48/// A vertex table as written: its `KEY` may be left out.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct VertexSpec {
51    pub name: String,
52    pub table: TableReference,
53    pub key: Option<String>,
54    pub labels: Vec<Label>,
55}
56
57/// An edge table as written, with the key column each `REFERENCES` names.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct EdgeSpec {
60    pub edge: EdgeTable,
61    /// `SOURCE KEY (…) REFERENCES vertex (column)`: the column.
62    pub source_column: Option<String>,
63    /// `DESTINATION KEY (…) REFERENCES vertex (column)`: the column.
64    pub destination_column: Option<String>,
65}
66
67/// A graph of one edge table and at most one vertex table, as a spec: what
68/// every graph was before #295, and what tests build.
69impl From<super::GraphDef> for GraphSpec {
70    fn from(def: super::GraphDef) -> Self {
71        GraphSpec {
72            name: def.name,
73            vertex_tables: def
74                .vertices
75                .into_iter()
76                .map(|v| VertexSpec {
77                    name: v.name,
78                    table: v.table,
79                    key: Some(v.key),
80                    labels: v.labels,
81                })
82                .collect(),
83            edge_tables: vec![EdgeSpec {
84                edge: def.edges,
85                source_column: None,
86                destination_column: None,
87            }],
88        }
89    }
90}
91
92/// Define `spec` in `ctx`, as `CREATE [OR REPLACE] PROPERTY GRAPH [IF NOT EXISTS]`
93/// does. Follows DataFusion's `CREATE TABLE`: an existing graph is an error,
94/// unless `or_replace` (replace it) or `if_not_exists` (keep it, do nothing).
95pub async fn create_graph(
96    ctx: &SessionContext,
97    spec: impl Into<GraphSpec>,
98    or_replace: bool,
99    if_not_exists: bool,
100) -> Result<()> {
101    let spec = spec.into();
102    if or_replace && if_not_exists {
103        return plan_err("'IF NOT EXISTS' cannot coexist with 'REPLACE'");
104    }
105    let state = ctx.state();
106    let graphs = registry(&state);
107    if let Some(why) = graphs.unavailable(&spec.name) {
108        // The database's graph that could not be defined when it was opened
109        // exists: it is kept, or replaced.
110        if if_not_exists {
111            return Ok(());
112        }
113        if !or_replace {
114            return plan_err(format!(
115                "graph '{}' already exists ({why}); replace it with CREATE OR REPLACE \
116                 PROPERTY GRAPH",
117                spec.name
118            ));
119        }
120    }
121    if graphs.get(&spec.name).is_some() {
122        if if_not_exists {
123            return Ok(());
124        }
125        if !or_replace {
126            return plan_err(format!("graph '{}' already exists", spec.name));
127        }
128    } else if spec.name == INFORMATION_SCHEMA
129        || default_catalog(&state)?.schema(&spec.name).is_some()
130    {
131        return plan_err(format!(
132            "cannot name a graph '{}': a schema of that name already exists, and a graph's \
133             name is the name of the schema holding its nodes and edges tables",
134            spec.name
135        ));
136    }
137    check_element_names(&spec)?;
138
139    let mut files = Vec::new();
140    let mut vertex_providers = Vec::new();
141    for v in &spec.vertex_tables {
142        vertex_providers.push(open_table(&state, &v.table, &mut files).await?);
143    }
144    let mut edge_schemas = Vec::new();
145    for e in &spec.edge_tables {
146        edge_schemas.push(
147            open_table(&state, &e.edge.table, &mut files)
148                .await?
149                .schema(),
150        );
151    }
152    let def = resolve_keys(&spec, &vertex_providers)?;
153    let mut schemas: Vec<(TableReference, SchemaRef)> = Vec::new();
154    for (v, provider) in def.vertex_tables.iter().zip(&vertex_providers) {
155        schemas.push((v.table.clone(), provider.schema()));
156    }
157    for (e, schema) in def.edge_tables.iter().zip(edge_schemas) {
158        schemas.push((e.table.clone(), schema));
159    }
160    validate(&def, &|t| {
161        schemas
162            .iter()
163            .find(|(table, _)| table == t)
164            .map(|(_, s)| Arc::clone(s))
165            .expect("every table of the graph was opened")
166    })?;
167
168    let name = def.name.clone();
169    let has_tables = def.default_pair().is_some();
170    graphs.put_with_files(def, files);
171    graphs.clear_unavailable(&name);
172    let catalog = default_catalog_inner(&state)?;
173    let schema = match catalog.schema(&name) {
174        Some(schema) => schema,
175        None => {
176            let schema = Arc::new(GraphSchema::new(name.clone(), ctx.state_weak_ref()));
177            catalog.register_schema(&name, Arc::clone(&schema) as _)?;
178            schema
179        }
180    };
181    // Plan both tables once, so their columns are known to listings even if a
182    // table under the graph later disappears.
183    if has_tables {
184        for table in [NODES, EDGES] {
185            schema.table(table).await?;
186        }
187    }
188    Ok(())
189}
190
191/// Element names (an `AS` name, or else the table's name) are unique across
192/// a graph's vertex and edge tables, as SQL/PGQ requires; `REFERENCES` names
193/// a vertex table by its element name.
194fn check_element_names(spec: &GraphSpec) -> Result<()> {
195    let names: Vec<&str> = spec
196        .vertex_tables
197        .iter()
198        .map(|v| v.name.as_str())
199        .chain(spec.edge_tables.iter().map(|e| e.edge.name.as_str()))
200        .collect();
201    for (i, name) in names.iter().enumerate() {
202        if names[..i].iter().any(|n| n.eq_ignore_ascii_case(name)) {
203            return plan_err(format!(
204                "graph '{}' has two element tables named '{name}'; give one a different name \
205                 with AS",
206                spec.name
207            ));
208        }
209    }
210    for e in &spec.edge_tables {
211        for (side, key, vertex, column) in endpoints(e) {
212            let (Some(vertex), Some(column)) = (vertex, column) else {
213                continue;
214            };
215            if spec.vertex_tables.iter().any(|v| &v.name == vertex) {
216                continue;
217            }
218            return plan_err(match spec.vertex_tables.as_slice() {
219                [] => format!(
220                    "{side} KEY ({key}) REFERENCES {vertex}, but the graph has no VERTEX \
221                     TABLES; add VERTEX TABLES ({vertex} KEY ({column})) or drop the \
222                     REFERENCES clause"
223                ),
224                [only] => format!(
225                    "{side} KEY ({key}) REFERENCES {vertex} ({column}), but the vertex table is \
226                     {} KEY ({}); REFERENCES must name the vertex table and its key",
227                    only.table,
228                    only.key.as_deref().unwrap_or("…")
229                ),
230                several => {
231                    let names: Vec<&str> = several.iter().map(|v| v.name.as_str()).collect();
232                    format!(
233                        "{side} KEY ({key}) of edge table '{}' REFERENCES {vertex}, which is not \
234                         a vertex table of the graph; its vertex tables are {}",
235                        e.edge.name,
236                        names.join(", ")
237                    )
238                }
239            });
240        }
241        if spec.vertex_tables.len() > 1
242            && (e.edge.source_vertex.is_none() || e.edge.destination_vertex.is_none())
243        {
244            let side = if e.edge.source_vertex.is_none() {
245                "SOURCE"
246            } else {
247                "DESTINATION"
248            };
249            return plan_err(format!(
250                "the {side} of edge table '{}' needs REFERENCES: graph '{}' has several vertex \
251                 tables, so say which one it refers to",
252                e.edge.name, spec.name
253            ));
254        }
255    }
256    Ok(())
257}
258
259/// The graph with every vertex key resolved: `KEY (column)` as written, else
260/// the table's primary key, else the column the edges' `REFERENCES` name (as
261/// DuckPGQ infers it). A `REFERENCES` column must be the key.
262fn resolve_keys(spec: &GraphSpec, providers: &[Arc<dyn TableProvider>]) -> Result<PropertyGraph> {
263    let mut vertex_tables = Vec::new();
264    for (v, provider) in spec.vertex_tables.iter().zip(providers) {
265        // (side, endpoint column, referenced column) of each endpoint that
266        // REFERENCES this vertex table.
267        let referenced: Vec<(&str, &str, &str)> = spec
268            .edge_tables
269            .iter()
270            .flat_map(endpoints)
271            .filter_map(|(side, key, vertex, column)| match (vertex, column) {
272                (Some(vertex), Some(column)) if vertex == &v.name => {
273                    Some((side, key, column.as_str()))
274                }
275                _ => None,
276            })
277            .collect();
278        let key = match &v.key {
279            Some(key) => key.clone(),
280            None => match primary_key(provider.as_ref()) {
281                Some(key) => key,
282                None => match referenced.first() {
283                    Some((_, _, column)) => column.to_string(),
284                    None => {
285                        return plan_err(format!(
286                            "vertex table '{}' needs a key: write KEY (column), declare a \
287                             primary key, or have an edge table REFERENCES it",
288                            v.name
289                        ))
290                    }
291                },
292            },
293        };
294        if let Some((side, endpoint, column)) = referenced.iter().find(|(_, _, c)| *c != key) {
295            return plan_err(format!(
296                "{side} KEY ({endpoint}) REFERENCES {} ({column}), but the vertex table is {} \
297                 KEY ({key}); REFERENCES must name the vertex table and its key",
298                v.name, v.table
299            ));
300        }
301        vertex_tables.push(VertexTable {
302            name: v.name.clone(),
303            table: v.table.clone(),
304            key,
305            labels: v.labels.clone(),
306        });
307    }
308    Ok(PropertyGraph {
309        name: spec.name.clone(),
310        vertex_tables,
311        edge_tables: spec.edge_tables.iter().map(|e| e.edge.clone()).collect(),
312    })
313}
314
315/// An edge table's two endpoints: (side, column, referenced vertex, referenced
316/// column).
317fn endpoints(e: &EdgeSpec) -> [(&'static str, &str, Option<&String>, Option<&String>); 2] {
318    [
319        (
320            "SOURCE",
321            e.edge.source.as_str(),
322            e.edge.source_vertex.as_ref(),
323            e.source_column.as_ref(),
324        ),
325        (
326            "DESTINATION",
327            e.edge.destination.as_str(),
328            e.edge.destination_vertex.as_ref(),
329            e.destination_column.as_ref(),
330        ),
331    ]
332}
333
334/// The table's declared single-column primary key, if it has one.
335fn primary_key(provider: &dyn TableProvider) -> Option<String> {
336    let schema = provider.schema();
337    provider.constraints()?.iter().find_map(|c| match c {
338        Constraint::PrimaryKey(columns) if columns.len() == 1 => {
339            Some(schema.field(columns[0]).name().clone())
340        }
341        _ => None,
342    })
343}
344
345/// The table `table` names: a table or view in the session, or else, when it
346/// looks like a file path or URL, that file opened as a listing table (added
347/// to `files`).
348async fn open_table(
349    state: &SessionState,
350    table: &TableReference,
351    files: &mut Vec<FileTable>,
352) -> Result<Arc<dyn TableProvider>> {
353    if let Some(provider) = session_table(state, table).await? {
354        return Ok(provider);
355    }
356    if let TableReference::Bare { table: location } = table {
357        if looks_like_location(location) {
358            let provider = open_file_table(state, location).await?;
359            files.push(FileTable {
360                table: table.clone(),
361                provider: Arc::clone(&provider),
362            });
363            return Ok(provider);
364        }
365    }
366    find_table(state, table).await
367}
368
369/// The table or view `table` names in the session's catalogs, not opening
370/// files.
371async fn session_table(
372    state: &SessionState,
373    table: &TableReference,
374) -> Result<Option<Arc<dyn TableProvider>>> {
375    let Some(catalogs) = registry(state).catalogs().cloned() else {
376        return lookup_table(state, table).await;
377    };
378    let resolved = resolve(state, table);
379    let provider = match catalogs
380        .catalog(&resolved.catalog)
381        .and_then(|c| c.schema(&resolved.schema))
382    {
383        Some(schema) => schema.table(&resolved.table).await?,
384        None => None,
385    };
386    if let Some(provider) = &provider {
387        check_available(provider.as_ref())?;
388    }
389    Ok(provider)
390}
391
392/// The error for a graph that does not exist, with a suggestion.
393pub fn unknown_graph(name: &str, graphs: &GraphRegistry) -> DataFusionError {
394    if let Some(why) = graphs.unavailable(name) {
395        return DataFusionError::Plan(why);
396    }
397    let names = graphs.names();
398    let hint = match closest_name(name, names.iter().map(String::as_str)) {
399        Some(s) => format!("; did you mean '{s}'?"),
400        None if names.is_empty() => {
401            "; no graphs are defined (define one with CREATE PROPERTY GRAPH)".to_string()
402        }
403        None => format!(". The graphs are: {}", names.join(", ")),
404    };
405    DataFusionError::Plan(format!("graph '{name}' does not exist{hint}"))
406}
407
408/// Refuse a DDL statement, planned as `plan`, that would break a graph:
409///
410/// - `DROP TABLE` or `DROP VIEW` of a table a graph uses;
411/// - `DROP SCHEMA` of a graph's schema, or of a schema holding a table a graph
412///   uses;
413/// - `CREATE OR REPLACE` of a table a graph uses, by one whose columns the
414///   graph's definition no longer fits (see [`check_replace`]).
415///
416/// Every other plan passes.
417pub async fn check_ddl(state: &SessionState, plan: &LogicalPlan) -> Result<()> {
418    let LogicalPlan::Ddl(ddl) = plan else {
419        return Ok(());
420    };
421    match ddl {
422        DdlStatement::DropTable(drop) => check_drop(state, "table", &drop.name),
423        DdlStatement::DropView(drop) => check_drop(state, "view", &drop.name),
424        DdlStatement::DropCatalogSchema(drop) => check_drop_schema(state, &drop.name),
425        DdlStatement::CreateView(create) if create.or_replace => {
426            let schema = create.input.schema().as_arrow();
427            check_replace(state, "view", &create.name, Some(schema)).await
428        }
429        DdlStatement::CreateMemoryTable(create) if create.or_replace => {
430            let schema = create.input.schema().as_arrow();
431            check_replace(state, "table", &create.name, Some(schema)).await
432        }
433        DdlStatement::CreateExternalTable(create) if create.or_replace => {
434            // An empty schema is inferred from the files when the statement
435            // runs, so it cannot be checked here.
436            let schema = create.schema.as_arrow();
437            let known = (!schema.fields().is_empty()).then_some(schema);
438            check_replace(state, "table", &create.name, known).await
439        }
440        _ => Ok(()),
441    }
442}
443
444/// Refuse to drop `table` (a `kind`: "table" or "view") while a graph uses it.
445pub fn check_drop(state: &SessionState, kind: &str, table: &TableReference) -> Result<()> {
446    let dropped = resolve(state, table);
447    let users = graphs_using(state, |t| t == &dropped);
448    if users.is_empty() {
449        return Ok(());
450    }
451    plan_err(format!(
452        "cannot drop {kind} '{table}': {}; drop {} first",
453        used_by(&users),
454        drop_statements(&users)
455    ))
456}
457
458/// Refuse to drop the schema `schema` while it is a graph's, or holds a table
459/// a graph uses.
460pub fn check_drop_schema(state: &SessionState, schema: &SchemaReference) -> Result<()> {
461    let options = &state.config_options().catalog;
462    let (catalog, name) = match schema {
463        SchemaReference::Bare { schema } => (options.default_catalog.as_str(), schema.as_ref()),
464        SchemaReference::Full { schema, catalog } => (catalog.as_ref(), schema.as_ref()),
465    };
466    if catalog == options.default_catalog && registry(state).get(name).is_some() {
467        return plan_err(format!(
468            "cannot drop schema '{name}': it holds the tables of graph '{name}'; drop the \
469             graph with DROP PROPERTY GRAPH {name}"
470        ));
471    }
472    let users = graphs_using(state, |t| {
473        t.catalog.as_ref() == catalog && t.schema.as_ref() == name
474    });
475    if users.is_empty() {
476        return Ok(());
477    }
478    plan_err(format!(
479        "cannot drop schema '{name}': {} a table in it; drop {} first",
480        if users.len() == 1 {
481            format!("graph '{}' uses", users[0].name)
482        } else {
483            used_by(&users).replace(" use it", " use")
484        },
485        drop_statements(&users)
486    ))
487}
488
489/// Refuse to replace `table` (a `kind`) by one with the columns `schema`
490/// while a graph uses it and its definition does not fit those columns.
491/// `None`: the new columns are not known yet, so the replacement is refused
492/// whenever a graph uses the table.
493pub async fn check_replace(
494    state: &SessionState,
495    kind: &str,
496    table: &TableReference,
497    schema: Option<&Schema>,
498) -> Result<()> {
499    let replaced = resolve(state, table);
500    let users = graphs_using(state, |t| t == &replaced);
501    if users.is_empty() {
502        return Ok(());
503    }
504    let Some(schema) = schema else {
505        return plan_err(format!(
506            "cannot replace {kind} '{table}' by one whose columns are not known yet: {}; \
507             drop {} first",
508            used_by(&users),
509            drop_statements(&users)
510        ));
511    };
512    let graphs = registry(state);
513    for def in &users {
514        let mut schemas: Vec<(TableReference, SchemaRef)> = Vec::new();
515        for t in def.tables() {
516            let schema =
517                if graphs.file_table(&def.name, t).is_none() && resolve(state, t) == replaced {
518                    Arc::new(schema.clone())
519                } else {
520                    graph_table(state, &def.name, t).await?.schema()
521                };
522            schemas.push((t.clone(), schema));
523        }
524        let schema_of = |t: &TableReference| {
525            schemas
526                .iter()
527                .find(|(table, _)| table == t)
528                .map(|(_, s)| Arc::clone(s))
529                .expect("every table of the graph was looked up")
530        };
531        if let Err(e) = validate(def, &schema_of) {
532            return plan_err(format!(
533                "cannot replace {kind} '{table}': graph '{}' uses it, and the new {kind} does \
534                 not fit its definition ({}). Keep the columns the graph uses, or drop \
535                 property graph {} first",
536                def.name,
537                crate::user_message(&e),
538                def.name
539            ));
540        }
541    }
542    Ok(())
543}
544
545/// The graphs with a session table (not a file path) for which `uses` holds.
546fn graphs_using(
547    state: &SessionState,
548    uses: impl Fn(&ResolvedTableReference) -> bool,
549) -> Vec<Arc<PropertyGraph>> {
550    let graphs = registry(state);
551    graphs
552        .all()
553        .into_iter()
554        .filter(|def| {
555            def.tables()
556                .any(|t| graphs.file_table(&def.name, t).is_none() && uses(&resolve(state, t)))
557        })
558        .collect()
559}
560
561/// "graph 'g' uses it" or "graphs 'g', 'h' use it".
562fn used_by(graphs: &[Arc<PropertyGraph>]) -> String {
563    let names: Vec<String> = graphs.iter().map(|g| format!("'{}'", g.name)).collect();
564    if names.len() == 1 {
565        format!("graph {} uses it", names[0])
566    } else {
567        format!("graphs {} use it", names.join(", "))
568    }
569}
570
571/// "property graph g" or "property graphs g, h".
572fn drop_statements(graphs: &[Arc<PropertyGraph>]) -> String {
573    let names: Vec<&str> = graphs.iter().map(|g| g.name.as_str()).collect();
574    if names.len() == 1 {
575        format!("property graph {}", names[0])
576    } else {
577        format!("property graphs {}", names.join(", "))
578    }
579}
580
581/// `table` with the session's default catalog and schema filled in.
582fn resolve(state: &SessionState, table: &TableReference) -> ResolvedTableReference {
583    let options = &state.config_options().catalog;
584    table
585        .clone()
586        .resolve(&options.default_catalog, &options.default_schema)
587}
588
589/// Drop the graph called `name` and its schema, as `DROP PROPERTY GRAPH
590/// [IF EXISTS]` does.
591pub fn drop_graph(ctx: &SessionContext, name: &str, if_exists: bool) -> Result<()> {
592    let state = ctx.state();
593    let graphs = registry(&state);
594    if graphs.remove(name).is_none() {
595        if graphs.clear_unavailable(name) || if_exists {
596            return Ok(());
597        }
598        return Err(unknown_graph(name, &graphs));
599    }
600    let catalog = default_catalog_inner(&state)?;
601    if catalog
602        .schema(name)
603        .is_some_and(|schema| schema.is::<GraphSchema>())
604    {
605        catalog.deregister_schema(name, true)?;
606    }
607    Ok(())
608}
609
610/// The closest of `candidates` to `name` by edit distance, if any is close
611/// enough to be a likely typo: for "did you mean" suggestions.
612pub fn closest_name<'a>(
613    name: &str,
614    candidates: impl IntoIterator<Item = &'a str>,
615) -> Option<&'a str> {
616    let limit = (name.chars().count() / 3).max(2);
617    candidates
618        .into_iter()
619        .map(|c| (levenshtein(name, c), c))
620        .filter(|(d, _)| *d <= limit)
621        .min_by_key(|(d, c)| (*d, *c))
622        .map(|(_, c)| c)
623}
624
625/// "; did you mean 'x'?" for the closest candidate, or nothing.
626fn did_you_mean<'a>(name: &str, candidates: impl IntoIterator<Item = &'a str>) -> String {
627    closest_name(name, candidates)
628        .map(|c| format!("; did you mean '{c}'?"))
629        .unwrap_or_default()
630}
631
632/// Check `def` against its tables' columns (`schema_of`): every named column
633/// and property exists, each edge table's endpoints have one node id type,
634/// and each vertex key is a node id type compatible with the endpoints that
635/// refer to it.
636fn validate(def: &PropertyGraph, schema_of: &dyn Fn(&TableReference) -> SchemaRef) -> Result<()> {
637    // Edge tables first, then what is left of the vertex tables: the order a
638    // one-pair graph's checks have always run in, so its errors are unchanged.
639    for e in &def.edge_tables {
640        let edges = schema_of(&e.table);
641        let table = &e.table;
642        let source = column_type(&edges, table, &e.source, "SOURCE KEY")?;
643        let destination = column_type(&edges, table, &e.destination, "DESTINATION KEY")?;
644        if source != destination {
645            return plan_err(format!(
646                "the source and destination columns of edge table '{table}' must have the same \
647                 type, but {} is {source} and {} is {destination}",
648                e.source, e.destination
649            ));
650        }
651        let Some(family) = IdFamily::of(&source) else {
652            return plan_err(format!(
653                "the endpoints of edge table '{table}' ({} and {}) are {source}; node ids must \
654                 be integers or strings",
655                e.source, e.destination
656            ));
657        };
658        for v in [def.endpoint_vertex(e, true), def.endpoint_vertex(e, false)]
659            .into_iter()
660            .flatten()
661        {
662            let key = column_type(&schema_of(&v.table), &v.table, &v.key, "KEY")?;
663            match IdFamily::of(&key) {
664                None => return not_an_id_type(v, &key),
665                Some(f) if f != family => {
666                    return plan_err(format!(
667                        "the key of vertex table '{}' ({}) is {key}, but the endpoints of edge \
668                         table '{table}' are {source}; both must be integers or both strings",
669                        v.table, v.key
670                    ))
671                }
672                Some(_) => {}
673            }
674        }
675        check_properties(&e.labels, &edges, table)?;
676    }
677    for v in &def.vertex_tables {
678        let vertices = schema_of(&v.table);
679        let key = column_type(&vertices, &v.table, &v.key, "KEY")?;
680        if IdFamily::of(&key).is_none() {
681            return not_an_id_type(v, &key);
682        }
683        if v.key != ID && vertices.field_with_name(ID).is_ok() {
684            return plan_err(format!(
685                "vertex table '{}' has a column named '{ID}' that is not its key ({}); \
686                 {}.nodes names the key '{ID}', so rename that column (in a view) first",
687                v.table, v.key, def.name
688            ));
689        }
690        check_properties(&v.labels, &vertices, &v.table)?;
691    }
692    Ok(())
693}
694
695fn not_an_id_type<T>(v: &VertexTable, key: &DataType) -> Result<T> {
696    plan_err(format!(
697        "the key of vertex table '{}' ({}) is {key}; node ids must be integers or strings",
698        v.table, v.key
699    ))
700}
701
702/// Every column a label's properties name exists in the table.
703fn check_properties(labels: &[Label], schema: &Schema, table: &TableReference) -> Result<()> {
704    for label in labels {
705        let columns: Vec<&String> = match &label.properties {
706            Properties::AllColumns { except } => except.iter().collect(),
707            Properties::Columns(columns) => columns.iter().map(|(c, _)| c).collect(),
708            Properties::None => Vec::new(),
709        };
710        for column in columns {
711            column_type(
712                schema,
713                table,
714                column,
715                &format!("label {} property", label.name),
716            )?;
717        }
718    }
719    Ok(())
720}
721
722/// Node ids are integers of any width, or strings.
723#[derive(Debug, PartialEq, Eq, Clone, Copy)]
724enum IdFamily {
725    Integer,
726    String,
727}
728
729impl IdFamily {
730    fn of(data_type: &DataType) -> Option<Self> {
731        match data_type {
732            t if t.is_integer() => Some(Self::Integer),
733            DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Some(Self::String),
734            DataType::Dictionary(_, value) => match Self::of(value) {
735                Some(Self::String) => Some(Self::String),
736                _ => None,
737            },
738            _ => None,
739        }
740    }
741}
742
743/// The table `table` names, or an error with a suggestion.
744async fn find_table(
745    state: &SessionState,
746    table: &TableReference,
747) -> Result<Arc<dyn TableProvider>> {
748    match lookup_table(state, table).await? {
749        Some(provider) => {
750            check_available(provider.as_ref())?;
751            Ok(provider)
752        }
753        None => {
754            let names = table_names(state).await;
755            plan_err(format!(
756                "table '{table}' not found{}",
757                did_you_mean(&table.to_string(), names.iter().map(String::as_str))
758            ))
759        }
760    }
761}
762
763/// Every table in the session, named as a query in the default schema would
764/// name it.
765async fn table_names(state: &SessionState) -> Vec<String> {
766    let options = &state.config_options().catalog;
767    let catalogs = state.catalog_list();
768    let mut names = Vec::new();
769    for catalog_name in catalogs.catalog_names() {
770        let Some(catalog) = catalogs.catalog(&catalog_name) else {
771            continue;
772        };
773        for schema_name in catalog.schema_names() {
774            if schema_name == INFORMATION_SCHEMA {
775                continue;
776            }
777            let Some(schema) = catalog.schema(&schema_name) else {
778                continue;
779            };
780            for table in schema.table_names() {
781                let reference = if catalog_name != options.default_catalog {
782                    TableReference::full(catalog_name.as_str(), schema_name.as_str(), table)
783                } else if schema_name != options.default_schema {
784                    TableReference::partial(schema_name.as_str(), table)
785                } else {
786                    TableReference::bare(table)
787                };
788                names.push(reference.to_string());
789            }
790        }
791    }
792    names
793}
794
795fn column_type(
796    schema: &Schema,
797    table: &TableReference,
798    column: &str,
799    clause: &str,
800) -> Result<DataType> {
801    match schema.field_with_name(column) {
802        Ok(field) => Ok(field.data_type().clone()),
803        Err(_) => {
804            let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
805            let hint = match closest_name(column, columns.iter().copied()) {
806                Some(c) => format!("did you mean '{c}'?"),
807                None => format!("its columns are {}", columns.join(", ")),
808            };
809            plan_err(format!(
810                "{clause} column '{column}' not found in table '{table}'; {hint}"
811            ))
812        }
813    }
814}
815
816/// The default catalog, as queries see it.
817fn default_catalog(state: &SessionState) -> Result<Arc<dyn CatalogProvider>> {
818    let name = &state.config_options().catalog.default_catalog;
819    state
820        .catalog_list()
821        .catalog(name)
822        .ok_or_else(|| DataFusionError::Plan(format!("the default catalog '{name}' is missing")))
823}
824
825/// The default catalog without the file-table wrapper (which cannot
826/// deregister a schema), when the session was built by `new_session`.
827fn default_catalog_inner(state: &SessionState) -> Result<Arc<dyn CatalogProvider>> {
828    let name = &state.config_options().catalog.default_catalog;
829    match registry(state).catalogs() {
830        Some(catalogs) => catalogs.catalog(name).ok_or_else(|| {
831            DataFusionError::Plan(format!("the default catalog '{name}' is missing"))
832        }),
833        None => default_catalog(state),
834    }
835}
836
837fn plan_err<T>(message: impl Into<String>) -> Result<T> {
838    Err(DataFusionError::Plan(message.into()))
839}