Skip to main content

micromegas_analytics/lakehouse/
list_view_set_definitions_table_function.rs

1//! `list_view_set_definitions()` -- admin UDTF listing every view set: the rows of
2//! `lakehouse_view_set_definitions` read straight from Postgres (`source = 'ddl'`), plus the
3//! built-in view sets of the `ViewFactory` that have no such row (`source = 'builtin'`).
4//! Postgres rows are read directly rather than from `ViewRegistry::current()` so an admin can
5//! see a definition that exists on disk but failed to load. Built-in rows carry the
6//! `update_group` of their global view, which gives clients the materialization order.
7//! Registered inside the same admin-gated block as `list_query_denials()`'s siblings.
8
9use super::view_factory::ViewFactory;
10use async_trait::async_trait;
11use datafusion::arrow::array::{Int32Array, RecordBatch, StringArray, TimestampNanosecondArray};
12use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit};
13use datafusion::catalog::Session;
14use datafusion::catalog::TableFunctionArgs;
15use datafusion::catalog::TableFunctionImpl;
16use datafusion::catalog::TableProvider;
17use datafusion::datasource::TableType;
18use datafusion::datasource::memory::{DataSourceExec, MemorySourceConfig};
19use datafusion::error::DataFusionError;
20use datafusion::physical_plan::ExecutionPlan;
21use datafusion::prelude::Expr;
22use micromegas_ingestion::data_lake_connection::DataLakeConnection;
23use sqlx::Row;
24use std::collections::HashSet;
25use std::sync::Arc;
26
27fn schema() -> SchemaRef {
28    Arc::new(Schema::new(vec![
29        Field::new("view_set_name", DataType::Utf8, false),
30        Field::new("definition_sql", DataType::Utf8, true),
31        Field::new("update_group", DataType::Int32, true),
32        Field::new(
33            "updated_at",
34            DataType::Timestamp(TimeUnit::Nanosecond, Some("+00:00".into())),
35            true,
36        ),
37        Field::new("updated_by", DataType::Utf8, true),
38        Field::new("source", DataType::Utf8, false),
39    ]))
40}
41
42/// A row of `lakehouse_view_set_definitions`.
43#[derive(Debug, Clone)]
44pub struct DdlRow {
45    pub view_set_name: String,
46    pub definition_sql: String,
47    pub update_group: Option<i32>,
48    pub updated_at_nanos: i64,
49    pub updated_by: Option<String>,
50}
51
52/// A row of the `list_view_set_definitions()` output.
53#[derive(Debug, Clone, PartialEq)]
54pub struct DefinitionRow {
55    pub view_set_name: String,
56    pub definition_sql: Option<String>,
57    pub update_group: Option<i32>,
58    pub updated_at_nanos: Option<i64>,
59    pub updated_by: Option<String>,
60    pub source: &'static str,
61}
62
63/// Unions the Postgres rows with the factory view sets they do not name, sorted by name.
64/// A Postgres row wins on a name collision, which covers a DDL set that is also in the factory
65/// and one that failed to load.
66pub fn merge_rows(ddl: Vec<DdlRow>, factory: &ViewFactory) -> Vec<DefinitionRow> {
67    let mut rows: Vec<DefinitionRow> = ddl
68        .into_iter()
69        .map(|r| DefinitionRow {
70            view_set_name: r.view_set_name,
71            definition_sql: Some(r.definition_sql),
72            update_group: r.update_group,
73            updated_at_nanos: Some(r.updated_at_nanos),
74            updated_by: r.updated_by,
75            source: "ddl",
76        })
77        .collect();
78    let mut seen: HashSet<String> = rows.iter().map(|r| r.view_set_name.clone()).collect();
79    let mut builtin = |name: String, update_group: Option<i32>| {
80        if seen.insert(name.clone()) {
81            rows.push(DefinitionRow {
82                view_set_name: name,
83                definition_sql: None,
84                update_group,
85                updated_at_nanos: None,
86                updated_by: None,
87                source: "builtin",
88            });
89        }
90    };
91    for view in factory.get_global_views() {
92        builtin(
93            view.get_view_set_name().to_string(),
94            view.get_update_group(),
95        );
96    }
97    for name in factory.get_view_sets().keys() {
98        builtin(name.clone(), None);
99    }
100    rows.sort_by(|a, b| a.view_set_name.cmp(&b.view_set_name));
101    rows
102}
103
104/// Builds the output batch, keeping at most `limit` rows.
105pub fn build_batch(
106    rows: &[DefinitionRow],
107    limit: Option<usize>,
108) -> datafusion::error::Result<RecordBatch> {
109    let rows = &rows[..limit.map_or(rows.len(), |n| n.min(rows.len()))];
110    Ok(RecordBatch::try_new(
111        schema(),
112        vec![
113            Arc::new(StringArray::from_iter_values(
114                rows.iter().map(|r| r.view_set_name.as_str()),
115            )),
116            Arc::new(StringArray::from_iter(
117                rows.iter().map(|r| r.definition_sql.as_deref()),
118            )),
119            Arc::new(Int32Array::from_iter(rows.iter().map(|r| r.update_group))),
120            Arc::new(
121                TimestampNanosecondArray::from_iter(rows.iter().map(|r| r.updated_at_nanos))
122                    .with_timezone("+00:00".to_string()),
123            ),
124            Arc::new(StringArray::from_iter(
125                rows.iter().map(|r| r.updated_by.as_deref()),
126            )),
127            Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.source))),
128        ],
129    )?)
130}
131
132/// A DataFusion `TableFunctionImpl` for `list_view_set_definitions()`.
133#[derive(Debug)]
134pub struct ListViewSetDefinitionsTableFunction {
135    lake: Arc<DataLakeConnection>,
136    view_factory: Arc<ViewFactory>,
137}
138
139impl ListViewSetDefinitionsTableFunction {
140    pub fn new(lake: Arc<DataLakeConnection>, view_factory: Arc<ViewFactory>) -> Self {
141        Self { lake, view_factory }
142    }
143}
144
145impl TableFunctionImpl for ListViewSetDefinitionsTableFunction {
146    fn call_with_args(
147        &self,
148        _args: TableFunctionArgs,
149    ) -> datafusion::error::Result<Arc<dyn TableProvider>> {
150        Ok(Arc::new(ListViewSetDefinitionsTableProvider {
151            lake: self.lake.clone(),
152            view_factory: self.view_factory.clone(),
153        }))
154    }
155}
156
157#[derive(Debug)]
158struct ListViewSetDefinitionsTableProvider {
159    lake: Arc<DataLakeConnection>,
160    view_factory: Arc<ViewFactory>,
161}
162
163#[async_trait]
164impl TableProvider for ListViewSetDefinitionsTableProvider {
165    fn schema(&self) -> SchemaRef {
166        schema()
167    }
168
169    fn table_type(&self) -> TableType {
170        TableType::Temporary
171    }
172
173    async fn scan(
174        &self,
175        _state: &dyn Session,
176        projection: Option<&Vec<usize>>,
177        _filters: &[Expr],
178        limit: Option<usize>,
179    ) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
180        let rows = sqlx::query(
181            "SELECT view_set_name, definition_sql, update_group, updated_at, updated_by \
182             FROM lakehouse_view_set_definitions ORDER BY view_set_name",
183        )
184        .fetch_all(&self.lake.db_pool)
185        .await
186        .map_err(|e| DataFusionError::External(e.into()))?;
187        let mut ddl = Vec::with_capacity(rows.len());
188        for row in &rows {
189            let ts: chrono::DateTime<chrono::Utc> = row
190                .try_get("updated_at")
191                .map_err(|e| DataFusionError::External(e.into()))?;
192            ddl.push(DdlRow {
193                view_set_name: row
194                    .try_get("view_set_name")
195                    .map_err(|e| DataFusionError::External(e.into()))?,
196                definition_sql: row
197                    .try_get("definition_sql")
198                    .map_err(|e| DataFusionError::External(e.into()))?,
199                update_group: row
200                    .try_get("update_group")
201                    .map_err(|e| DataFusionError::External(e.into()))?,
202                updated_at_nanos: ts.timestamp_nanos_opt().unwrap_or_default(),
203                updated_by: row
204                    .try_get("updated_by")
205                    .map_err(|e| DataFusionError::External(e.into()))?,
206            });
207        }
208        let rb = build_batch(&merge_rows(ddl, &self.view_factory), limit)?;
209        let source =
210            MemorySourceConfig::try_new(&[vec![rb]], schema(), projection.map(|v| v.to_owned()))?;
211        Ok(DataSourceExec::from_data_source(source))
212    }
213}