Skip to main content

micromegas_analytics/lakehouse/
list_view_sets_table_function.rs

1use super::view_factory::ViewFactory;
2use crate::lakehouse::catalog::list_view_sets;
3use async_trait::async_trait;
4use datafusion::arrow::array::{ArrayRef, BinaryArray, BooleanArray, StringArray};
5use datafusion::arrow::datatypes::DataType;
6use datafusion::arrow::datatypes::Field;
7use datafusion::arrow::datatypes::Schema;
8use datafusion::arrow::datatypes::SchemaRef;
9use datafusion::arrow::record_batch::RecordBatch;
10use datafusion::catalog::Session;
11use datafusion::catalog::TableFunctionArgs;
12use datafusion::catalog::TableFunctionImpl;
13use datafusion::catalog::TableProvider;
14use datafusion::datasource::TableType;
15use datafusion::datasource::memory::{DataSourceExec, MemorySourceConfig};
16use datafusion::error::DataFusionError;
17use datafusion::physical_plan::ExecutionPlan;
18use datafusion::prelude::Expr;
19use std::sync::Arc;
20
21/// A DataFusion `TableFunctionImpl` for listing view sets with their current schema information.
22#[derive(Debug)]
23pub struct ListViewSetsTableFunction {
24    view_factory: Arc<ViewFactory>,
25}
26
27impl ListViewSetsTableFunction {
28    pub fn new(view_factory: Arc<ViewFactory>) -> Self {
29        Self { view_factory }
30    }
31}
32
33impl TableFunctionImpl for ListViewSetsTableFunction {
34    fn call_with_args(
35        &self,
36        _args: TableFunctionArgs,
37    ) -> datafusion::error::Result<Arc<dyn TableProvider>> {
38        Ok(Arc::new(ListViewSetsTableProvider {
39            view_factory: self.view_factory.clone(),
40        }))
41    }
42}
43
44/// A DataFusion `TableProvider` for listing view sets with their current schema information.
45#[derive(Debug)]
46pub struct ListViewSetsTableProvider {
47    pub view_factory: Arc<ViewFactory>,
48}
49
50#[async_trait]
51impl TableProvider for ListViewSetsTableProvider {
52    fn schema(&self) -> SchemaRef {
53        Arc::new(Schema::new(vec![
54            Field::new("view_set_name", DataType::Utf8, false),
55            Field::new("current_schema_hash", DataType::Binary, false),
56            Field::new("schema", DataType::Utf8, false),
57            Field::new("has_view_maker", DataType::Boolean, false),
58            Field::new("global_instance_available", DataType::Boolean, false),
59            Field::new("description", DataType::Utf8, true),
60            Field::new("columns", DataType::Utf8, false),
61            Field::new("sort_order", DataType::Utf8, true),
62        ]))
63    }
64
65    fn table_type(&self) -> TableType {
66        TableType::Temporary
67    }
68
69    async fn scan(
70        &self,
71        _state: &dyn Session,
72        projection: Option<&Vec<usize>>,
73        _filters: &[Expr],
74        limit: Option<usize>,
75    ) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
76        // Get current schema versions from the view factory
77        let schema_infos =
78            list_view_sets(&self.view_factory).map_err(|e| DataFusionError::External(e.into()))?;
79
80        // Apply limit early to avoid building unnecessary arrays.
81        // DataFusion trusts us to apply the limit - if we ignore it, too many rows
82        // will be returned to the client.
83        let limited_infos: &[_] = if let Some(n) = limit {
84            &schema_infos[..n.min(schema_infos.len())]
85        } else {
86            &schema_infos
87        };
88
89        // Convert to Arrow arrays
90        let view_set_names: Vec<String> = limited_infos
91            .iter()
92            .map(|info| info.view_set_name.clone())
93            .collect();
94        let schema_hashes: Vec<&[u8]> = limited_infos
95            .iter()
96            .map(|info| info.current_schema_hash.as_slice())
97            .collect();
98        let schemas: Vec<String> = limited_infos
99            .iter()
100            .map(|info| info.schema.clone())
101            .collect();
102        let has_view_makers: Vec<bool> = limited_infos
103            .iter()
104            .map(|info| info.has_view_maker)
105            .collect();
106        let global_instances: Vec<bool> = limited_infos
107            .iter()
108            .map(|info| info.global_instance_available)
109            .collect();
110
111        let descriptions: Vec<Option<&str>> = limited_infos
112            .iter()
113            .map(|info| info.description.as_deref())
114            .collect();
115        let column_lists: Vec<&str> = limited_infos
116            .iter()
117            .map(|info| info.columns.as_str())
118            .collect();
119        let sort_orders: Vec<Option<String>> = limited_infos
120            .iter()
121            .map(|info| info.sort_order.as_ref().map(|cols| cols.join(", ")))
122            .collect();
123
124        let view_set_name_array: ArrayRef = Arc::new(StringArray::from(view_set_names));
125        let schema_hash_array: ArrayRef = Arc::new(BinaryArray::from(schema_hashes));
126        let schema_array: ArrayRef = Arc::new(StringArray::from(schemas));
127        let has_view_maker_array: ArrayRef = Arc::new(BooleanArray::from(has_view_makers));
128        let global_instance_array: ArrayRef = Arc::new(BooleanArray::from(global_instances));
129
130        let columns = vec![
131            view_set_name_array,
132            schema_hash_array,
133            schema_array,
134            has_view_maker_array,
135            global_instance_array,
136            Arc::new(StringArray::from(descriptions)),
137            Arc::new(StringArray::from(column_lists)),
138            Arc::new(StringArray::from(sort_orders)),
139        ];
140
141        let record_batch = RecordBatch::try_new(self.schema(), columns)
142            .map_err(|e| DataFusionError::External(e.into()))?;
143
144        let source = MemorySourceConfig::try_new(
145            &[vec![record_batch]],
146            self.schema(),
147            projection.map(|v| v.to_owned()),
148        )?;
149        Ok(DataSourceExec::from_data_source(source))
150    }
151}