1use 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
36const INFORMATION_SCHEMA: &str = "information_schema";
38
39#[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct EdgeSpec {
60 pub edge: EdgeTable,
61 pub source_column: Option<String>,
63 pub destination_column: Option<String>,
65}
66
67impl 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
92pub 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 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 if has_tables {
186 for table in [NODES, EDGES] {
187 schema.table(table).await?;
188 }
189 }
190 Ok(())
191}
192
193fn 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 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
268fn 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 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 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
340fn 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
359fn 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
370async 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
394async 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
417pub 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
433pub 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 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
469pub 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
483pub 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
514pub 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
570fn 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
586fn 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
596fn 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
606fn 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
614pub 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 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
638pub 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 let _ = catalog.register_schema(name, schema);
657 }
658 }
659}
660
661pub 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
676fn 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
683fn validate(def: &PropertyGraph, schema_of: &dyn Fn(&TableReference) -> SchemaRef) -> Result<()> {
688 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 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
756fn 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#[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
797async 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
817async 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
870fn 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
879fn 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}