Skip to main content

micromegas_analytics/lakehouse/
view_ddl.rs

1//! `CREATE [OR REPLACE] MATERIALIZED VIEW ... WITH (...)` / `DROP MATERIALIZED VIEW ...` --
2//! the DDL front end for DDL-defined materialized views: daemon-updated (`update_group` set) or
3//! on-demand (`update_group` omitted).
4//!
5//! All three queries (`extract_query`, `count_src_query`, `merge_partitions_query`) are `WITH`
6//! options, so none of them is privileged the way a statement body would be -- that requires
7//! parsing the statement directly instead of going through `sqlparser`'s own `parse_create_view`,
8//! which unconditionally expects an `AS` body immediately after the view name and so cannot parse
9//! a `CREATE MATERIALIZED VIEW ... WITH (...)` with no `AS` body at all. [`parse_view_ddl`]
10//! therefore hand-rolls the parse off a single `Parser::try_with_sql`.
11
12use super::view_definition::{
13    ViewDefinition, ViewOptions, check_view_set_name_charset, parse_byte_size, parse_time_delta,
14};
15use anyhow::{Context, Result};
16use datafusion::sql::sqlparser::{
17    ast::{Expr as SqlExpr, SqlOption, Value},
18    dialect::GenericDialect,
19    keywords::Keyword,
20    parser::Parser,
21    tokenizer::Token,
22};
23
24/// One parsed `CREATE [OR REPLACE] MATERIALIZED VIEW` / `DROP MATERIALIZED VIEW` statement.
25#[derive(Debug, Clone)]
26pub enum ViewDdl {
27    Create {
28        name: String,
29        or_replace: bool,
30        // Boxed: `ViewDefinition` is far larger than `Drop`'s variant, and clippy's
31        // `large_enum_variant` flags the resulting size gap.
32        definition: Box<ViewDefinition>,
33        /// The verbatim statement text, stored as `lakehouse_view_set_definitions.definition_sql`.
34        sql: String,
35    },
36    Drop {
37        name: String,
38        if_exists: bool,
39    },
40}
41
42/// `Ok(None)` when `sql` is not view DDL -- the overwhelmingly common case, decided by a cheap
43/// keyword peek before any full parse. `Err` when the hand-rolled parse does not reach EOF right
44/// after `<name> WITH (...)` (or, on `DROP`, right after the single name): an unmodelled clause,
45/// an `AS` body, a second `DROP` name, or a second statement each would otherwise silently do less
46/// than the statement says.
47///
48/// Returns a plain `anyhow::Result` rather than a typed error enum: this crate's convention
49/// (`rust/CLAUDE.md`) is to use `anyhow` unless a caller needs to branch on the error kind, and
50/// `execute_query`'s only caller here never does -- it always maps the error into a client-facing
51/// `invalid_argument` `Status`.
52pub fn parse_view_ddl(sql: &str) -> Result<Option<ViewDdl>> {
53    let first_word = sql
54        .trim_start()
55        .split(|c: char| c.is_whitespace() || c == '(')
56        .next()
57        .unwrap_or("")
58        .to_lowercase();
59    // A leading `--` or `/*` comment (routine from BI/notebook front ends) makes the naive
60    // first-word peek useless -- fall through to the real tokenizing parse below, which skips
61    // comments, instead of bailing out here.
62    if first_word != "create"
63        && first_word != "drop"
64        && !first_word.starts_with("--")
65        && !first_word.starts_with("/*")
66    {
67        return Ok(None);
68    }
69
70    let mut parser = Parser::new(&GenericDialect {})
71        .try_with_sql(sql)
72        .with_context(|| "tokenizing statement")?;
73
74    if parser.parse_keyword(Keyword::CREATE) {
75        let or_replace = parser.parse_keywords(&[Keyword::OR, Keyword::REPLACE]);
76        if !parser.parse_keyword(Keyword::MATERIALIZED) {
77            // CREATE VIEW / CREATE TABLE / ... -- not our DDL, let ctx.sql handle it (or reject
78            // it) as usual.
79            return Ok(None);
80        }
81        parser
82            .expect_keyword_is(Keyword::VIEW)
83            .with_context(|| "expected VIEW after CREATE [OR REPLACE] MATERIALIZED")?;
84        let name = parser
85            .parse_object_name(false)
86            .with_context(|| "expected a view set name")?
87            .to_string();
88        let options = parser
89            .parse_options(Keyword::WITH)
90            .with_context(|| "expected WITH (...) options")?;
91        require_eof(
92            &mut parser,
93            "CREATE [OR REPLACE] MATERIALIZED VIEW <name> WITH (...)",
94        )?;
95        let definition = view_definition_from_options(name.clone(), options)
96            .with_context(|| format!("CREATE MATERIALIZED VIEW {name}"))?;
97        return Ok(Some(ViewDdl::Create {
98            name,
99            or_replace,
100            definition: Box::new(definition),
101            sql: sql.to_string(),
102        }));
103    }
104
105    if parser.parse_keyword(Keyword::DROP) {
106        if !parser.parse_keyword(Keyword::MATERIALIZED) {
107            return Ok(None);
108        }
109        parser
110            .expect_keyword_is(Keyword::VIEW)
111            .with_context(|| "expected VIEW after DROP MATERIALIZED")?;
112        let if_exists = parser.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
113        let name = parser
114            .parse_object_name(false)
115            .with_context(|| "expected a view set name")?
116            .to_string();
117        require_eof(&mut parser, "DROP MATERIALIZED VIEW [IF EXISTS] <name>")?;
118        return Ok(Some(ViewDdl::Drop { name, if_exists }));
119    }
120
121    Ok(None)
122}
123
124/// Consumes an optional trailing `;` and requires EOF immediately after -- preserving the
125/// single-statement rule `SessionContext::sql`'s `sql_to_statement` enforces for every non-DDL
126/// query; intercepting DDL ahead of `ctx.sql` would otherwise bypass that guard and silently
127/// execute only the first of several statements.
128fn require_eof(parser: &mut Parser, context: &str) -> Result<()> {
129    let _ = parser.consume_token(&Token::SemiColon);
130    let trailing = parser.peek_token_ref().token.clone();
131    if trailing != Token::EOF {
132        anyhow::bail!("unexpected trailing input after {context}: {trailing}");
133    }
134    Ok(())
135}
136
137fn value_to_string(expr: &SqlExpr) -> Result<String> {
138    match expr {
139        SqlExpr::Value(v) => match &v.value {
140            Value::SingleQuotedString(s) => Ok(s.clone()),
141            Value::DollarQuotedString(d) => Ok(d.value.clone()),
142            other => anyhow::bail!("expected a string literal, got {other}"),
143        },
144        other => anyhow::bail!("expected a string literal, got {other}"),
145    }
146}
147
148fn value_to_i32(expr: &SqlExpr) -> Result<i32> {
149    match expr {
150        SqlExpr::Value(v) => match &v.value {
151            Value::Number(s, _) => s
152                .parse::<i32>()
153                .with_context(|| format!("invalid integer {s:?}")),
154            Value::SingleQuotedString(s) => s
155                .parse::<i32>()
156                .with_context(|| format!("invalid integer {s:?}")),
157            other => anyhow::bail!("expected an integer literal, got {other}"),
158        },
159        other => anyhow::bail!("expected an integer literal, got {other}"),
160    }
161}
162
163/// Assembles the normalized `ViewDefinition` from a `WITH (...)` option list. Option semantics:
164/// `extract_query`, `count_src_query` and `merge_partitions_query` are required; `update_group`
165/// is optional, and its absence makes the view on-demand. `time_column` is required unless
166/// both `min_time_column` and `max_time_column` are given individually; `source_partition_delta`
167/// defaults to `'1 day'`; `merge_partition_delta` defaults to `source_partition_delta`; both are
168/// rejected on an on-demand view, whose partition sizes follow the query range, bounded by
169/// `max_jit_src_data` (an on-demand-only, `'<n> <unit>'` byte size, default `'1 GB'`);
170/// `merge_sort_order` is an optional comma-separated column list; `description` is an optional,
171/// non-blank markdown usage guide. Anything else is a hard error.
172fn view_definition_from_options(name: String, options: Vec<SqlOption>) -> Result<ViewDefinition> {
173    let mut extract_query = None;
174    let mut count_src_query = None;
175    let mut merge_partitions_query = None;
176    let mut update_group = None;
177    let mut time_column = None;
178    let mut min_time_column = None;
179    let mut max_time_column = None;
180    let mut source_partition_delta: Option<String> = None;
181    let mut merge_partition_delta: Option<String> = None;
182    let mut merge_sort_order: Option<Vec<String>> = None;
183    let mut description: Option<String> = None;
184    let mut max_jit_src_data: Option<String> = None;
185
186    for opt in options {
187        let SqlOption::KeyValue { key, value } = opt else {
188            anyhow::bail!("unsupported view option (expected `key = value`)");
189        };
190        let key_name = key.value.to_lowercase();
191        match key_name.as_str() {
192            "extract_query" => extract_query = Some(value_to_string(&value)?),
193            "count_src_query" => count_src_query = Some(value_to_string(&value)?),
194            "merge_partitions_query" => merge_partitions_query = Some(value_to_string(&value)?),
195            "update_group" => update_group = Some(value_to_i32(&value)?),
196            "time_column" => time_column = Some(value_to_string(&value)?),
197            "min_time_column" => min_time_column = Some(value_to_string(&value)?),
198            "max_time_column" => max_time_column = Some(value_to_string(&value)?),
199            "source_partition_delta" => {
200                let s = value_to_string(&value)?;
201                parse_time_delta(&s).with_context(|| "source_partition_delta")?;
202                source_partition_delta = Some(s);
203            }
204            "merge_partition_delta" => {
205                let s = value_to_string(&value)?;
206                parse_time_delta(&s).with_context(|| "merge_partition_delta")?;
207                merge_partition_delta = Some(s);
208            }
209            "merge_sort_order" => {
210                let s = value_to_string(&value)?;
211                let cols: Vec<String> = s
212                    .split(',')
213                    .map(|c| c.trim().to_string())
214                    .filter(|c| !c.is_empty())
215                    .collect();
216                if cols.is_empty() {
217                    anyhow::bail!(
218                        "merge_sort_order must be a non-empty, comma-separated column list"
219                    );
220                }
221                merge_sort_order = Some(cols);
222            }
223            "description" => {
224                let s = value_to_string(&value)?;
225                if s.trim().is_empty() {
226                    anyhow::bail!("description must not be empty");
227                }
228                description = Some(s);
229            }
230            "max_jit_src_data" => {
231                let s = value_to_string(&value)?;
232                parse_byte_size(&s).with_context(|| "max_jit_src_data")?;
233                max_jit_src_data = Some(s);
234            }
235            other => anyhow::bail!("unknown view option '{other}'"),
236        }
237    }
238
239    let extract_query = extract_query.context("missing required option 'extract_query'")?;
240    let count_src_query = count_src_query.context("missing required option 'count_src_query'")?;
241    let merge_partitions_query =
242        merge_partitions_query.context("missing required option 'merge_partitions_query'")?;
243    if update_group.is_none() {
244        for (option, value) in [
245            ("source_partition_delta", &source_partition_delta),
246            ("merge_partition_delta", &merge_partition_delta),
247        ] {
248            if value.is_some() {
249                anyhow::bail!(
250                    "{option} only applies to daemon-updated views (set `update_group`), \
251                     on-demand partition sizes follow the query range, bounded by \
252                     `max_jit_src_data`"
253                );
254            }
255        }
256    } else if max_jit_src_data.is_some() {
257        anyhow::bail!("max_jit_src_data only applies to on-demand views (no `update_group`)");
258    }
259
260    let (resolved_min, resolved_max) = match (time_column, min_time_column, max_time_column) {
261        (Some(t), min, max) => (min.unwrap_or_else(|| t.clone()), max.unwrap_or(t)),
262        (None, Some(min), Some(max)) => (min, max),
263        _ => anyhow::bail!(
264            "missing required option 'time_column' (or both 'min_time_column' and \
265             'max_time_column')"
266        ),
267    };
268
269    let source_partition_delta = source_partition_delta.unwrap_or_else(|| "1 day".to_string());
270    let merge_partition_delta =
271        merge_partition_delta.unwrap_or_else(|| source_partition_delta.clone());
272
273    check_view_set_name_charset(&name)?;
274
275    Ok(ViewDefinition {
276        view_set_name: name,
277        extract_query,
278        count_src_query,
279        merge_partitions_query,
280        update_group,
281        options: ViewOptions {
282            min_time_column: resolved_min,
283            max_time_column: resolved_max,
284            source_partition_delta,
285            merge_partition_delta,
286            merge_sort_order,
287            description,
288            max_jit_src_data,
289        },
290    })
291}