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