1use std::sync::Arc;
6
7use async_trait::async_trait;
8use datafusion_common::{HashMap, TableReference, error::Result, not_impl_err};
9use datafusion_execution::config::SessionConfig;
10
11use crate::{CatalogProvider, CatalogProviderList, SchemaProvider, TableProvider};
12
13#[derive(Debug)]
17struct ResolvedSchemaProvider {
18 owner_name: Option<String>,
19 cached_tables: HashMap<String, Arc<dyn TableProvider>>,
20}
21#[async_trait]
22impl SchemaProvider for ResolvedSchemaProvider {
23 fn owner_name(&self) -> Option<&str> {
24 self.owner_name.as_deref()
25 }
26
27 fn table_names(&self) -> Vec<String> {
28 self.cached_tables.keys().cloned().collect()
29 }
30
31 async fn table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
32 Ok(self.cached_tables.get(name).cloned())
33 }
34
35 fn register_table(
36 &self,
37 name: String,
38 _table: Arc<dyn TableProvider>,
39 ) -> Result<Option<Arc<dyn TableProvider>>> {
40 not_impl_err!(
41 "Attempt to register table '{name}' with ResolvedSchemaProvider which is not supported"
42 )
43 }
44
45 fn deregister_table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
46 not_impl_err!(
47 "Attempt to deregister table '{name}' with ResolvedSchemaProvider which is not supported"
48 )
49 }
50
51 fn table_exist(&self, name: &str) -> bool {
52 self.cached_tables.contains_key(name)
53 }
54}
55
56struct ResolvedSchemaProviderBuilder {
58 owner_name: String,
59 async_provider: Arc<dyn AsyncSchemaProvider>,
60 cached_tables: HashMap<String, Option<Arc<dyn TableProvider>>>,
61}
62impl ResolvedSchemaProviderBuilder {
63 fn new(owner_name: String, async_provider: Arc<dyn AsyncSchemaProvider>) -> Self {
64 Self {
65 owner_name,
66 async_provider,
67 cached_tables: HashMap::new(),
68 }
69 }
70
71 async fn resolve_table(&mut self, table_name: &str) -> Result<()> {
72 if !self.cached_tables.contains_key(table_name) {
73 let resolved_table = self.async_provider.table(table_name).await?;
74 self.cached_tables
75 .insert(table_name.to_string(), resolved_table);
76 }
77 Ok(())
78 }
79
80 fn finish(self) -> Arc<dyn SchemaProvider> {
81 let cached_tables = self
82 .cached_tables
83 .into_iter()
84 .filter_map(|(key, maybe_value)| maybe_value.map(|value| (key, value)))
85 .collect();
86 Arc::new(ResolvedSchemaProvider {
87 owner_name: Some(self.owner_name),
88 cached_tables,
89 })
90 }
91}
92
93#[derive(Debug)]
97struct ResolvedCatalogProvider {
98 cached_schemas: HashMap<String, Arc<dyn SchemaProvider>>,
99}
100impl CatalogProvider for ResolvedCatalogProvider {
101 fn schema_names(&self) -> Vec<String> {
102 self.cached_schemas.keys().cloned().collect()
103 }
104
105 fn schema(&self, name: &str) -> Option<Arc<dyn SchemaProvider>> {
106 self.cached_schemas.get(name).cloned()
107 }
108}
109
110struct ResolvedCatalogProviderBuilder {
112 cached_schemas: HashMap<String, Option<ResolvedSchemaProviderBuilder>>,
113 async_provider: Arc<dyn AsyncCatalogProvider>,
114}
115impl ResolvedCatalogProviderBuilder {
116 fn new(async_provider: Arc<dyn AsyncCatalogProvider>) -> Self {
117 Self {
118 cached_schemas: HashMap::new(),
119 async_provider,
120 }
121 }
122 fn finish(self) -> Arc<dyn CatalogProvider> {
123 let cached_schemas = self
124 .cached_schemas
125 .into_iter()
126 .filter_map(|(key, maybe_value)| {
127 maybe_value.map(|value| (key, value.finish()))
128 })
129 .collect();
130 Arc::new(ResolvedCatalogProvider { cached_schemas })
131 }
132}
133
134#[derive(Debug)]
138struct ResolvedCatalogProviderList {
139 cached_catalogs: HashMap<String, Arc<dyn CatalogProvider>>,
140}
141impl CatalogProviderList for ResolvedCatalogProviderList {
142 fn register_catalog(
143 &self,
144 _name: String,
145 _catalog: Arc<dyn CatalogProvider>,
146 ) -> Option<Arc<dyn CatalogProvider>> {
147 unimplemented!("resolved providers cannot handle registration APIs")
148 }
149
150 fn catalog_names(&self) -> Vec<String> {
151 self.cached_catalogs.keys().cloned().collect()
152 }
153
154 fn catalog(&self, name: &str) -> Option<Arc<dyn CatalogProvider>> {
155 self.cached_catalogs.get(name).cloned()
156 }
157}
158
159#[async_trait]
175pub trait AsyncSchemaProvider: Send + Sync {
176 async fn table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>>;
178 async fn resolve(
189 &self,
190 references: &[TableReference],
191 config: &SessionConfig,
192 catalog_name: &str,
193 schema_name: &str,
194 ) -> Result<Arc<dyn SchemaProvider>> {
195 let mut cached_tables = HashMap::<String, Option<Arc<dyn TableProvider>>>::new();
196
197 for reference in references {
198 let ref_catalog_name = reference
199 .catalog()
200 .unwrap_or(&config.options().catalog.default_catalog);
201
202 if ref_catalog_name != catalog_name {
204 continue;
205 }
206
207 let ref_schema_name = reference
208 .schema()
209 .unwrap_or(&config.options().catalog.default_schema);
210
211 if ref_schema_name != schema_name {
212 continue;
213 }
214
215 if !cached_tables.contains_key(reference.table()) {
216 let resolved_table = self.table(reference.table()).await?;
217 cached_tables.insert(reference.table().to_string(), resolved_table);
218 }
219 }
220
221 let cached_tables = cached_tables
222 .into_iter()
223 .filter_map(|(key, maybe_value)| maybe_value.map(|value| (key, value)))
224 .collect();
225
226 Ok(Arc::new(ResolvedSchemaProvider {
227 cached_tables,
228 owner_name: Some(catalog_name.to_string()),
229 }))
230 }
231}
232
233#[async_trait]
240pub trait AsyncCatalogProvider: Send + Sync {
241 async fn schema(&self, name: &str) -> Result<Option<Arc<dyn AsyncSchemaProvider>>>;
243
244 async fn resolve(
254 &self,
255 references: &[TableReference],
256 config: &SessionConfig,
257 catalog_name: &str,
258 ) -> Result<Arc<dyn CatalogProvider>> {
259 let mut cached_schemas =
260 HashMap::<String, Option<ResolvedSchemaProviderBuilder>>::new();
261
262 for reference in references {
263 let ref_catalog_name = reference
264 .catalog()
265 .unwrap_or(&config.options().catalog.default_catalog);
266
267 if ref_catalog_name != catalog_name {
269 continue;
270 }
271
272 let schema_name = reference
273 .schema()
274 .unwrap_or(&config.options().catalog.default_schema);
275
276 let schema = if let Some(schema) = cached_schemas.get_mut(schema_name) {
277 schema
278 } else {
279 let resolved_schema = self.schema(schema_name).await?;
280 let resolved_schema = resolved_schema.map(|resolved_schema| {
281 ResolvedSchemaProviderBuilder::new(
282 catalog_name.to_string(),
283 resolved_schema,
284 )
285 });
286 cached_schemas.insert(schema_name.to_string(), resolved_schema);
287 cached_schemas.get_mut(schema_name).unwrap()
288 };
289
290 let Some(schema) = schema else { continue };
292
293 schema.resolve_table(reference.table()).await?;
294 }
295
296 let cached_schemas = cached_schemas
297 .into_iter()
298 .filter_map(|(key, maybe_builder)| {
299 maybe_builder.map(|schema_builder| (key, schema_builder.finish()))
300 })
301 .collect::<HashMap<_, _>>();
302
303 Ok(Arc::new(ResolvedCatalogProvider { cached_schemas }))
304 }
305}
306
307#[async_trait]
313pub trait AsyncCatalogProviderList: Send + Sync {
314 async fn catalog(&self, name: &str) -> Result<Option<Arc<dyn AsyncCatalogProvider>>>;
316
317 async fn resolve(
327 &self,
328 references: &[TableReference],
329 config: &SessionConfig,
330 ) -> Result<Arc<dyn CatalogProviderList>> {
331 let mut cached_catalogs =
332 HashMap::<String, Option<ResolvedCatalogProviderBuilder>>::new();
333
334 for reference in references {
335 let catalog_name = reference
336 .catalog()
337 .unwrap_or(&config.options().catalog.default_catalog);
338
339 let catalog = if let Some(catalog) = cached_catalogs.get_mut(catalog_name) {
349 catalog
350 } else {
351 let resolved_catalog = self.catalog(catalog_name).await?;
352 let resolved_catalog =
353 resolved_catalog.map(ResolvedCatalogProviderBuilder::new);
354 cached_catalogs.insert(catalog_name.to_string(), resolved_catalog);
355 cached_catalogs.get_mut(catalog_name).unwrap()
356 };
357
358 let Some(catalog) = catalog else { continue };
360
361 let schema_name = reference
362 .schema()
363 .unwrap_or(&config.options().catalog.default_schema);
364
365 let schema = if let Some(schema) = catalog.cached_schemas.get_mut(schema_name)
366 {
367 schema
368 } else {
369 let resolved_schema = catalog.async_provider.schema(schema_name).await?;
370 let resolved_schema = resolved_schema.map(|async_schema| {
371 ResolvedSchemaProviderBuilder::new(
372 catalog_name.to_string(),
373 async_schema,
374 )
375 });
376 catalog
377 .cached_schemas
378 .insert(schema_name.to_string(), resolved_schema);
379 catalog.cached_schemas.get_mut(schema_name).unwrap()
380 };
381
382 let Some(schema) = schema else { continue };
384
385 schema.resolve_table(reference.table()).await?;
386 }
387
388 let cached_catalogs = cached_catalogs
390 .into_iter()
391 .filter_map(|(key, maybe_builder)| {
392 maybe_builder.map(|catalog_builder| (key, catalog_builder.finish()))
393 })
394 .collect::<HashMap<_, _>>();
395
396 Ok(Arc::new(ResolvedCatalogProviderList { cached_catalogs }))
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use std::sync::{
403 Arc,
404 atomic::{AtomicU32, Ordering},
405 };
406
407 use arrow::datatypes::SchemaRef;
408 use async_trait::async_trait;
409 use datafusion_common::{Statistics, TableReference, error::Result};
410 use datafusion_execution::config::SessionConfig;
411 use datafusion_expr::{Expr, TableType};
412 use datafusion_physical_plan::ExecutionPlan;
413
414 use crate::{Session, TableProvider};
415
416 use super::{AsyncCatalogProvider, AsyncCatalogProviderList, AsyncSchemaProvider};
417
418 #[derive(Debug)]
419 struct MockTableProvider {}
420 #[async_trait]
421 impl TableProvider for MockTableProvider {
422 fn schema(&self) -> SchemaRef {
424 unimplemented!()
425 }
426
427 fn table_type(&self) -> TableType {
428 unimplemented!()
429 }
430
431 async fn scan(
432 &self,
433 _state: &dyn Session,
434 _projection: Option<&[usize]>,
435 _filters: &[Expr],
436 _limit: Option<usize>,
437 ) -> Result<Arc<dyn ExecutionPlan>> {
438 unimplemented!()
439 }
440
441 fn statistics(&self) -> Option<Statistics> {
442 unimplemented!()
443 }
444 }
445
446 #[derive(Default)]
447 struct MockAsyncSchemaProvider {
448 lookup_count: AtomicU32,
449 }
450
451 const MOCK_CATALOG: &str = "mock_catalog";
452 const MOCK_SCHEMA: &str = "mock_schema";
453 const MOCK_TABLE: &str = "mock_table";
454
455 #[async_trait]
456 impl AsyncSchemaProvider for MockAsyncSchemaProvider {
457 async fn table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
458 self.lookup_count.fetch_add(1, Ordering::Release);
459 if name == MOCK_TABLE {
460 Ok(Some(Arc::new(MockTableProvider {})))
461 } else {
462 Ok(None)
463 }
464 }
465 }
466
467 fn test_config() -> SessionConfig {
468 let mut config = SessionConfig::default();
469 config.options_mut().catalog.default_catalog = MOCK_CATALOG.to_string();
470 config.options_mut().catalog.default_schema = MOCK_SCHEMA.to_string();
471 config
472 }
473
474 #[tokio::test]
475 async fn test_async_schema_provider_resolve() {
476 async fn check(
477 refs: Vec<TableReference>,
478 expected_lookup_count: u32,
479 found_tables: &[&str],
480 not_found_tables: &[&str],
481 ) {
482 let async_provider = MockAsyncSchemaProvider::default();
483 let cached_provider = async_provider
484 .resolve(&refs, &test_config(), MOCK_CATALOG, MOCK_SCHEMA)
485 .await
486 .unwrap();
487
488 assert_eq!(
489 async_provider.lookup_count.load(Ordering::Acquire),
490 expected_lookup_count
491 );
492
493 for table_ref in found_tables {
494 let table = cached_provider.table(table_ref).await.unwrap();
495 assert!(table.is_some());
496 }
497
498 for table_ref in not_found_tables {
499 assert!(cached_provider.table(table_ref).await.unwrap().is_none());
500 }
501 }
502
503 check(
505 vec![
506 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, MOCK_TABLE),
507 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, "not_exists"),
508 ],
509 2,
510 &[MOCK_TABLE],
511 &["not_exists"],
512 )
513 .await;
514
515 check(
517 vec![
518 TableReference::full(MOCK_CATALOG, "foo", MOCK_TABLE),
519 TableReference::full("foo", MOCK_SCHEMA, MOCK_TABLE),
520 ],
521 0,
522 &[],
523 &[MOCK_TABLE],
524 )
525 .await;
526
527 check(
529 vec![
530 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, MOCK_TABLE),
531 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, MOCK_TABLE),
532 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, "not_exists"),
533 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, "not_exists"),
534 ],
535 2,
536 &[MOCK_TABLE],
537 &["not_exists"],
538 )
539 .await;
540 }
541
542 #[derive(Default)]
543 struct MockAsyncCatalogProvider {
544 lookup_count: AtomicU32,
545 }
546
547 #[async_trait]
548 impl AsyncCatalogProvider for MockAsyncCatalogProvider {
549 async fn schema(
550 &self,
551 name: &str,
552 ) -> Result<Option<Arc<dyn AsyncSchemaProvider>>> {
553 self.lookup_count.fetch_add(1, Ordering::Release);
554 if name == MOCK_SCHEMA {
555 Ok(Some(Arc::new(MockAsyncSchemaProvider::default())))
556 } else {
557 Ok(None)
558 }
559 }
560 }
561
562 #[tokio::test]
563 async fn test_async_catalog_provider_resolve() {
564 async fn check(
565 refs: Vec<TableReference>,
566 expected_lookup_count: u32,
567 found_schemas: &[&str],
568 not_found_schemas: &[&str],
569 ) {
570 let async_provider = MockAsyncCatalogProvider::default();
571 let cached_provider = async_provider
572 .resolve(&refs, &test_config(), MOCK_CATALOG)
573 .await
574 .unwrap();
575
576 assert_eq!(
577 async_provider.lookup_count.load(Ordering::Acquire),
578 expected_lookup_count
579 );
580
581 for schema_ref in found_schemas {
582 let schema = cached_provider.schema(schema_ref);
583 assert!(schema.is_some());
584 }
585
586 for schema_ref in not_found_schemas {
587 assert!(cached_provider.schema(schema_ref).is_none());
588 }
589 }
590
591 check(
593 vec![
594 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, "x"),
595 TableReference::full(MOCK_CATALOG, "not_exists", "x"),
596 ],
597 2,
598 &[MOCK_SCHEMA],
599 &["not_exists"],
600 )
601 .await;
602
603 check(
605 vec![TableReference::full("foo", MOCK_SCHEMA, "x")],
606 0,
607 &[],
608 &[MOCK_SCHEMA],
609 )
610 .await;
611
612 check(
614 vec![
615 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, "x"),
616 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, "x"),
617 TableReference::full(MOCK_CATALOG, "not_exists", "x"),
618 TableReference::full(MOCK_CATALOG, "not_exists", "x"),
619 ],
620 2,
621 &[MOCK_SCHEMA],
622 &["not_exists"],
623 )
624 .await;
625 }
626
627 #[derive(Default)]
628 struct MockAsyncCatalogProviderList {
629 lookup_count: AtomicU32,
630 }
631
632 #[async_trait]
633 impl AsyncCatalogProviderList for MockAsyncCatalogProviderList {
634 async fn catalog(
635 &self,
636 name: &str,
637 ) -> Result<Option<Arc<dyn AsyncCatalogProvider>>> {
638 self.lookup_count.fetch_add(1, Ordering::Release);
639 if name == MOCK_CATALOG {
640 Ok(Some(Arc::new(MockAsyncCatalogProvider::default())))
641 } else {
642 Ok(None)
643 }
644 }
645 }
646
647 #[tokio::test]
648 async fn test_async_catalog_provider_list_resolve() {
649 async fn check(
650 refs: Vec<TableReference>,
651 expected_lookup_count: u32,
652 found_catalogs: &[&str],
653 not_found_catalogs: &[&str],
654 ) {
655 let async_provider = MockAsyncCatalogProviderList::default();
656 let cached_provider =
657 async_provider.resolve(&refs, &test_config()).await.unwrap();
658
659 assert_eq!(
660 async_provider.lookup_count.load(Ordering::Acquire),
661 expected_lookup_count
662 );
663
664 for catalog_ref in found_catalogs {
665 let catalog = cached_provider.catalog(catalog_ref);
666 assert!(catalog.is_some());
667 }
668
669 for catalog_ref in not_found_catalogs {
670 assert!(cached_provider.catalog(catalog_ref).is_none());
671 }
672 }
673
674 check(
676 vec![
677 TableReference::full(MOCK_CATALOG, "x", "x"),
678 TableReference::full("not_exists", "x", "x"),
679 ],
680 2,
681 &[MOCK_CATALOG],
682 &["not_exists"],
683 )
684 .await;
685
686 check(
688 vec![
689 TableReference::full(MOCK_CATALOG, "x", "x"),
690 TableReference::full(MOCK_CATALOG, "x", "x"),
691 TableReference::full("not_exists", "x", "x"),
692 TableReference::full("not_exists", "x", "x"),
693 ],
694 2,
695 &[MOCK_CATALOG],
696 &["not_exists"],
697 )
698 .await;
699 }
700
701 #[tokio::test]
702 async fn test_defaults() {
703 for table_ref in &[
704 TableReference::full(MOCK_CATALOG, MOCK_SCHEMA, MOCK_TABLE),
705 TableReference::partial(MOCK_SCHEMA, MOCK_TABLE),
706 TableReference::bare(MOCK_TABLE),
707 ] {
708 let async_provider = MockAsyncCatalogProviderList::default();
709 let cached_provider = async_provider
710 .resolve(std::slice::from_ref(table_ref), &test_config())
711 .await
712 .unwrap();
713
714 let catalog = cached_provider
715 .catalog(table_ref.catalog().unwrap_or(MOCK_CATALOG))
716 .unwrap();
717 let schema = catalog
718 .schema(table_ref.schema().unwrap_or(MOCK_SCHEMA))
719 .unwrap();
720 assert!(schema.table(table_ref.table()).await.unwrap().is_some());
721 }
722 }
723}