Skip to main content

mz_catalog_decode/
create_sql.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Decoders for catalog `create_sql` strings.
11//!
12//! Each function parses a persisted `create_sql` and returns a JSON value with
13//! the fields a builtin catalog view projects. Errors are human-readable
14//! strings.
15
16use std::collections::BTreeMap;
17
18use mz_repr::adt::interval::Interval;
19use mz_repr::strconv;
20use mz_sql_parser::ast::display::AstDisplay;
21use mz_sql_parser::ast::item_refs::collect_item_references;
22use mz_sql_parser::ast::{
23    AstInfo, AvroSchema, ColumnOption, ConnectionOption, ConnectionOptionName,
24    CreateConnectionType, CreateSinkConnection, CreateSourceOptionName, CreateSubsourceOptionName,
25    Expr, Format, FormatSpecifier, IcebergSinkConfigOptionName, IcebergSinkMode, IndexOptionName,
26    KafkaSinkConfigOptionName, KafkaSourceConfigOptionName, MaterializedViewOptionName,
27    PgConfigOptionName, ProtobufSchema, Raw, RawClusterName, RawItemName, RefreshAtOptionValue,
28    RefreshEveryOptionValue, RefreshOptionValue, SinkEnvelope, SourceEnvelope, SourceErrorPolicy,
29    Statement, TableFromSourceOptionName, TableOptionName, UnresolvedItemName, Value,
30    WithOptionValue,
31};
32use prost::Message as _;
33use serde_json::json;
34
35use crate::durable;
36
37/// Parses `sql`, which must contain exactly one statement.
38fn parse_single_statement(sql: &str) -> Result<Statement<Raw>, String> {
39    let mut stmts = mz_sql_parser::parser::parse_statements(sql)
40        .map_err(|e| format!("failed to parse create_sql: {e}"))?;
41    match stmts.len() {
42        1 => Ok(stmts.remove(0).ast),
43        n => Err(format!("expected a single statement, found {n}")),
44    }
45}
46
47fn item_id(item: RawItemName) -> Result<String, &'static str> {
48    match item {
49        RawItemName::Id(id, _, _) => Ok(id),
50        RawItemName::Name(_) => Err("unresolved item name"),
51    }
52}
53
54fn cluster_id(in_cluster: RawClusterName) -> Result<String, &'static str> {
55    match in_cluster {
56        RawClusterName::Resolved(s) => Ok(s),
57        RawClusterName::Unresolved(_) => Err("unresolved cluster name"),
58    }
59}
60
61fn format_name<T: AstInfo>(fmt: &Format<T>) -> &'static str {
62    match fmt {
63        Format::Bytes => "bytes",
64        Format::Avro(_) => "avro",
65        Format::Protobuf(_) => "protobuf",
66        Format::Regex(_) => "regex",
67        Format::Csv { .. } => "csv",
68        Format::Json { .. } => "json",
69        Format::Text => "text",
70    }
71}
72
73/// Extracts the string form of a `WithOptionValue`, matching how the planner
74/// coerces option values. The blanket `TryFromValue<WithOptionValue<T>>` impl in
75/// `src/sql/src/plan/with_options.rs` accepts a quoted string, a bare identifier,
76/// and a 1-part unresolved item name, all yielding a string. Any other variant
77/// yields None.
78///
79/// `AstDisplay` does not re-quote bare identifiers or 1-part names, so those
80/// forms persist unquoted in `create_sql`. Matching only `Value::String` here
81/// would miss them and silently fall back to a default, so the catalog-raw
82/// parsers below route their string options through this helper.
83fn option_string<T: AstInfo>(value: &WithOptionValue<T>) -> Option<String> {
84    match value {
85        WithOptionValue::Value(Value::String(s)) => Some(s.clone()),
86        WithOptionValue::Ident(ident) => Some(ident.clone().into_string()),
87        WithOptionValue::UnresolvedItemName(UnresolvedItemName(parts)) if parts.len() == 1 => {
88            Some(parts[0].clone().into_string())
89        }
90        _ => None,
91    }
92}
93
94/// The compaction window a `RETAIN HISTORY` option plans to, in milliseconds.
95///
96/// Mirrors `plan_retain_history_option` and `OptionalDuration` in `mz_sql`: `NULL` and a zero
97/// duration disable compaction, which `CompactionWindow::comparable_timestamp` reports as
98/// `u64::MAX`.
99fn retain_history_millis<T: AstInfo>(value: Option<&WithOptionValue<T>>) -> Result<u64, String> {
100    let value = match value {
101        Some(WithOptionValue::RetainHistoryFor(value) | WithOptionValue::Value(value)) => value,
102        _ => return Err("invalid RETAIN HISTORY value".into()),
103    };
104    let interval = match value {
105        Value::Null => None,
106        Value::Interval(literal) => Some(durable::interval_literal(literal)?),
107        Value::Number(s) | Value::String(s) => {
108            Some(strconv::parse_interval(s).map_err(|e| e.to_string())?)
109        }
110        Value::HexString(_) | Value::Boolean(_) => {
111            return Err("invalid RETAIN HISTORY value".into());
112        }
113    };
114    let duration = interval
115        .map(|interval| interval.duration().map_err(|e| e.to_string()))
116        .transpose()?
117        .filter(|duration| !duration.is_zero());
118    match duration {
119        None => Ok(u64::MAX),
120        Some(duration) => u64::try_from(duration.as_millis())
121            .map_err(|_| "RETAIN HISTORY duration out of range".to_string()),
122    }
123}
124
125/// Records the window of the last `RETAIN HISTORY` option among `options`, the one
126/// `CatalogItem::update_retain_history` keeps, as `retain_history_millis` in `info`.
127///
128/// Each statement type has its own option type, so `options` yields each option's name and
129/// value, and `retain_history` is that type's `RetainHistory` name.
130fn insert_retain_history<'a, N, T>(
131    info: &mut BTreeMap<&str, serde_json::Value>,
132    options: impl DoubleEndedIterator<Item = (&'a N, &'a Option<WithOptionValue<T>>)>,
133    retain_history: N,
134) -> Result<(), String>
135where
136    N: PartialEq + 'a,
137    T: AstInfo + 'a,
138{
139    if let Some((_, value)) = options.rev().find(|(name, _)| **name == retain_history) {
140        let millis = retain_history_millis(value.as_ref())?;
141        info.insert("retain_history_millis", json!(millis));
142    }
143    Ok(())
144}
145
146/// Whether `expr` is a bare `NULL` literal, possibly parenthesized.
147fn is_null_literal<T: AstInfo>(expr: &Expr<T>) -> bool {
148    match expr {
149        Expr::Value(Value::Null) => true,
150        Expr::Nested(inner) => is_null_literal(inner),
151        _ => false,
152    }
153}
154
155/// Records the `REFRESH` options among `options` as `refresh` in `info`, one entry per option in
156/// statement order.
157fn insert_refresh_strategies<'a, T: AstInfo + 'a>(
158    info: &mut BTreeMap<&str, serde_json::Value>,
159    options: impl Iterator<Item = &'a Option<WithOptionValue<T>>>,
160) -> Result<(), String> {
161    let mut refresh = Vec::new();
162    for value in options {
163        let Some(WithOptionValue::Refresh(value)) = value else {
164            continue;
165        };
166        refresh.push(match value {
167            RefreshOptionValue::OnCommit => json!({"type": "on-commit"}),
168            RefreshOptionValue::AtCreation => json!({"type": "at", "at": null}),
169            RefreshOptionValue::At(RefreshAtOptionValue { time }) => {
170                json!({"type": "at", "at": time.to_ast_string_stable()})
171            }
172            RefreshOptionValue::Every(RefreshEveryOptionValue {
173                interval,
174                aligned_to,
175            }) => {
176                // The same duration round trip as planning, so that `1 day`
177                // renders as `24:00:00` rather than as a day.
178                let interval = durable::interval_literal(interval)
179                    .and_then(|interval| {
180                        interval
181                            .duration()
182                            .and_then(|duration| Interval::from_duration(&duration))
183                            .map_err(|e| e.to_string())
184                    })
185                    .map_err(|e| format!("invalid REFRESH EVERY interval: {e}"))?;
186                json!({
187                    "type": "every",
188                    "interval": interval.to_string(),
189                    "aligned_to": aligned_to.as_ref().map(|time| time.to_ast_string_stable()),
190                })
191            }
192        });
193    }
194    // Purification leaves at least one REFRESH option, but a statement stored
195    // before it did has none and means ON COMMIT.
196    if refresh.is_empty() {
197        refresh.push(json!({"type": "on-commit"}));
198    }
199    info.insert("refresh", json!(refresh));
200    Ok(())
201}
202
203/// Parses a catalog `create_sql` string into a JSON object.
204///
205/// The returned JSON does not fully reflect the parsed SQL and instead contains only fields
206/// required by current callers.
207pub fn item_details(a: &str) -> Result<serde_json::Value, String> {
208    let stmt = parse_single_statement(a)?;
209
210    let mut info = BTreeMap::<&str, serde_json::Value>::new();
211
212    use mz_sql_parser::ast::Statement::*;
213    let item_type = match stmt {
214        CreateSecret(_) => "secret",
215        CreateConnection(stmt) => {
216            let connection_type = stmt.connection_type.as_str();
217            info.insert("connection_type", json!(connection_type));
218
219            "connection"
220        }
221        CreateView(stmt) => {
222            let mut definition = stmt.definition.query.to_ast_string_stable();
223            // PostgreSQL appends a semicolon in `pg_views.definition`, we
224            // do the same for compatibility's sake.
225            definition.push(';');
226            info.insert("definition", json!(definition));
227
228            "view"
229        }
230        CreateMaterializedView(stmt) => {
231            let Some(in_cluster) = stmt.in_cluster else {
232                return Err("missing IN CLUSTER".into());
233            };
234            let cluster_id = match in_cluster {
235                RawClusterName::Unresolved(ident) => ident.into_string(),
236                RawClusterName::Resolved(s) => s,
237            };
238            info.insert("cluster_id", json!(cluster_id));
239
240            let mut definition = stmt.query.to_ast_string_stable();
241            definition.push(';');
242            info.insert("definition", json!(definition));
243
244            insert_retain_history(
245                &mut info,
246                stmt.with_options.iter().map(|o| (&o.name, &o.value)),
247                MaterializedViewOptionName::RetainHistory,
248            )?;
249
250            insert_refresh_strategies(&mut info, stmt.with_options.iter().map(|o| &o.value))?;
251
252            if let Some(target) = stmt.replacement_for {
253                info.insert("replacement_target", json!(item_id(target)?));
254            }
255
256            "materialized-view"
257        }
258        CreateTable(stmt) => {
259            insert_retain_history(
260                &mut info,
261                stmt.with_options.iter().map(|o| (&o.name, &o.value)),
262                TableOptionName::RetainHistory,
263            )?;
264            let column_defaults: Vec<serde_json::Value> = stmt
265                .columns
266                .iter()
267                .map(|column| {
268                    // A column may repeat `DEFAULT`, and `plan_create_table` applies the last one.
269                    column
270                        .options
271                        .iter()
272                        .rev()
273                        .find_map(|option| match &option.option {
274                            ColumnOption::Default(expr) => Some(expr),
275                            _ => None,
276                        })
277                        .filter(|expr| !is_null_literal(expr))
278                        .map_or(serde_json::Value::Null, |expr| {
279                            json!(expr.to_ast_string_stable())
280                        })
281                })
282                .collect();
283            info.insert("column_defaults", json!(column_defaults));
284            "table"
285        }
286        CreateTableFromSource(stmt) => {
287            let source_id = item_id(stmt.source)?;
288            info.insert("source_id", json!(source_id));
289
290            insert_retain_history(
291                &mut info,
292                stmt.with_options.iter().map(|o| (&o.name, &o.value)),
293                TableFromSourceOptionName::RetainHistory,
294            )?;
295
296            "table"
297        }
298        CreateSource(stmt) => {
299            insert_retain_history(
300                &mut info,
301                stmt.with_options.iter().map(|o| (&o.name, &o.value)),
302                CreateSourceOptionName::RetainHistory,
303            )?;
304
305            let Some(in_cluster) = stmt.in_cluster else {
306                return Err("missing IN CLUSTER".into());
307            };
308            let cluster_id = cluster_id(in_cluster)?;
309            info.insert("cluster_id", json!(cluster_id));
310
311            use mz_sql_parser::ast::CreateSourceConnection::*;
312            let (source_type, connection) = match stmt.connection {
313                Kafka { connection, .. } => ("kafka", Some(connection)),
314                Postgres { connection, .. } => ("postgres", Some(connection)),
315                MySql { connection, .. } => ("mysql", Some(connection)),
316                SqlServer { connection, .. } => ("sql-server", Some(connection)),
317                LoadGenerator { .. } => ("load-generator", None),
318            };
319            info.insert("source_type", json!(source_type));
320            if let Some(conn) = connection {
321                let conn_id = item_id(conn)?;
322                info.insert("connection_id", json!(conn_id));
323            }
324
325            let is_debezium = matches!(
326                stmt.envelope,
327                Some(mz_sql_parser::ast::SourceEnvelope::Debezium)
328            );
329
330            // An old-syntax kafka source ingests into its own relation, so an
331            // omitted ENVELOPE means the default ENVELOPE NONE and the pre-MV
332            // packer reported 'none'. A new-syntax source (no progress
333            // subsource, hence no EXPOSE PROGRESS AS in create_sql) ingests
334            // nothing itself. Its envelopes live on the per-table exports, so
335            // its own envelope_type stays absent (SQL NULL), matching released
336            // behavior. `progress_subsource.is_some()` is the planner's own
337            // old-vs-new discriminator (see `OldSyntaxIngestion` in
338            // plan_create_source). Non-kafka sources carry no envelope either.
339            // See the `mz_sources.envelope_type` column.
340            let envelope_type = match &stmt.envelope {
341                Some(envelope) => {
342                    use mz_sql_parser::ast::SourceEnvelope::*;
343                    Some(match envelope {
344                        None => "none",
345                        Debezium => "debezium",
346                        Upsert { .. } => "upsert",
347                        CdcV2 => "materialize",
348                    })
349                }
350                None if source_type == "kafka" && stmt.progress_subsource.is_some() => Some("none"),
351                None => None,
352            };
353            if let Some(envelope_type) = envelope_type {
354                info.insert("envelope_type", json!(envelope_type));
355            }
356
357            if let Some(format_spec) = stmt.format {
358                match &format_spec {
359                    FormatSpecifier::Bare(fmt) => {
360                        // Debezium sources with a single format spec implicitly use
361                        // the same format for both key and value.
362                        if is_debezium {
363                            info.insert("key_format", json!(format_name(fmt)));
364                        }
365                        info.insert("value_format", json!(format_name(fmt)));
366                    }
367                    FormatSpecifier::KeyValue { key, value } => {
368                        info.insert("key_format", json!(format_name(key)));
369                        info.insert("value_format", json!(format_name(value)));
370                    }
371                }
372            }
373
374            "source"
375        }
376        CreateWebhookSource(stmt) => {
377            if stmt.is_table {
378                "table"
379            } else {
380                info.insert("source_type", json!("webhook"));
381                if let Some(in_cluster) = stmt.in_cluster {
382                    let cluster_id = cluster_id(in_cluster)?;
383                    info.insert("cluster_id", json!(cluster_id));
384                }
385                "source"
386            }
387        }
388        CreateSubsource(stmt) => {
389            use mz_sql_parser::ast::CreateSubsourceOptionName;
390            let is_progress = stmt
391                .with_options
392                .iter()
393                .any(|o| matches!(o.name, CreateSubsourceOptionName::Progress));
394            let source_type = if is_progress { "progress" } else { "subsource" };
395            info.insert("source_type", json!(source_type));
396
397            insert_retain_history(
398                &mut info,
399                stmt.with_options.iter().map(|o| (&o.name, &o.value)),
400                CreateSubsourceOptionName::RetainHistory,
401            )?;
402
403            if let Some(of_source) = stmt.of_source {
404                let of_source_id = item_id(of_source)?;
405                info.insert("of_source_id", json!(of_source_id));
406            }
407
408            "subsource"
409        }
410        // Everything the mz_sinks, mz_kafka_sinks and mz_iceberg_sinks
411        // views read. The Rust side of each value lives in `Sink` and
412        // `StorageSinkConnection`, so those and this have to move together.
413        //
414        // NOTE: we bail below if a sink has no resolved `IN CLUSTER`, no
415        // `TOPIC` on kafka, or no `NAMESPACE`/`TABLE` on iceberg. Planning
416        // guarantees all four. But if one ever slipped through it would
417        // take down every view built on this function, not just the sink
418        // ones.
419        CreateSink(stmt) => {
420            let Some(in_cluster) = stmt.in_cluster else {
421                return Err("missing IN CLUSTER".into());
422            };
423            info.insert("cluster_id", json!(cluster_id(in_cluster)?));
424
425            match stmt.connection {
426                CreateSinkConnection::Kafka {
427                    connection,
428                    options,
429                    key: sink_key,
430                    ..
431                } => {
432                    info.insert("sink_type", json!("kafka"));
433                    info.insert("connection_id", json!(item_id(connection)?));
434
435                    let topic = options
436                        .into_iter()
437                        .find(|o| o.name == KafkaSinkConfigOptionName::Topic)
438                        .and_then(|o| o.value.as_ref().and_then(option_string))
439                        .ok_or("kafka sink missing TOPIC")?;
440                    info.insert("topic", json!(topic));
441
442                    if let Some(envelope) = stmt.envelope {
443                        let envelope_type = match envelope {
444                            SinkEnvelope::Upsert => "upsert",
445                            SinkEnvelope::Debezium => "debezium",
446                        };
447                        info.insert("envelope_type", json!(envelope_type));
448                    }
449
450                    if let Some(format_spec) = stmt.format {
451                        // A key format only survives if the sink has a
452                        // `KEY`. Without one `kafka_sink_builder` throws
453                        // away the key half of a key/value spec, and does
454                        // not copy a bare spec over to the key either.
455                        let (key_format, value_format) = match (&format_spec, sink_key.is_some()) {
456                            (FormatSpecifier::Bare(fmt), false) => (None, format_name(fmt)),
457                            (FormatSpecifier::Bare(fmt), true) => {
458                                (Some(format_name(fmt)), format_name(fmt))
459                            }
460                            (FormatSpecifier::KeyValue { value, .. }, false) => {
461                                (None, format_name(value))
462                            }
463                            (FormatSpecifier::KeyValue { key, value }, true) => {
464                                (Some(format_name(key)), format_name(value))
465                            }
466                        };
467                        if let Some(key_format) = key_format {
468                            info.insert("key_format", json!(key_format));
469                        }
470                        info.insert("value_format", json!(value_format));
471
472                        // The deprecated combined `format`. Only avro/avro
473                        // and json/json collapse to a single name.
474                        // Everything else, text/text and bytes/bytes
475                        // included, gets the composite form.
476                        let combined = match key_format {
477                            None => value_format.to_string(),
478                            Some(key_format)
479                                if key_format == value_format
480                                    && matches!(value_format, "avro" | "json") =>
481                            {
482                                value_format.to_string()
483                            }
484                            Some(key_format) => {
485                                format!("key-{key_format}-value-{value_format}")
486                            }
487                        };
488                        info.insert("format", json!(combined));
489                    }
490                }
491                CreateSinkConnection::Iceberg {
492                    catalog_connection,
493                    options,
494                    ..
495                } => {
496                    info.insert("sink_type", json!("iceberg"));
497                    // The catalog connection, not the optional AWS one.
498                    info.insert("connection_id", json!(item_id(catalog_connection)?));
499
500                    let mut namespace = None;
501                    let mut table = None;
502                    for option in options {
503                        match option.name {
504                            IcebergSinkConfigOptionName::Namespace => {
505                                namespace = option.value.as_ref().and_then(option_string)
506                            }
507                            IcebergSinkConfigOptionName::Table => {
508                                table = option.value.as_ref().and_then(option_string)
509                            }
510                        }
511                    }
512                    info.insert(
513                        "namespace",
514                        json!(namespace.ok_or("iceberg sink missing NAMESPACE")?),
515                    );
516                    info.insert("table", json!(table.ok_or("iceberg sink missing TABLE")?));
517
518                    // Iceberg spells the envelope `MODE`, and has no format
519                    // columns at all.
520                    if let Some(mode) = stmt.mode {
521                        let envelope_type = match mode {
522                            IcebergSinkMode::Upsert => "upsert",
523                            IcebergSinkMode::Append => "append",
524                        };
525                        info.insert("envelope_type", json!(envelope_type));
526                    }
527                }
528            }
529
530            "sink"
531        }
532        CreateMetricSink(stmt) => {
533            let Some(in_cluster) = stmt.in_cluster else {
534                return Err("missing IN CLUSTER".into());
535            };
536            let cluster_id = cluster_id(in_cluster)?;
537            info.insert("cluster_id", json!(cluster_id));
538            let from_id = item_id(stmt.from)?;
539            info.insert("from_id", json!(from_id));
540            "metric-sink"
541        }
542        CreateIndex(stmt) => {
543            let Some(in_cluster) = stmt.in_cluster else {
544                return Err("missing IN CLUSTER".into());
545            };
546            let cluster_id = cluster_id(in_cluster)?;
547            info.insert("cluster_id", json!(cluster_id));
548            let on_id = item_id(stmt.on_name)?;
549            info.insert("on_id", json!(on_id));
550            insert_retain_history(
551                &mut info,
552                stmt.with_options.iter().map(|o| (&o.name, &o.value)),
553                IndexOptionName::RetainHistory,
554            )?;
555            let key_parts: Vec<_> = stmt
556                .key_parts
557                .iter()
558                .flatten()
559                .map(|expr| json!(expr.to_ast_string_simple()))
560                .collect();
561            info.insert("key_parts", json!(key_parts));
562            "index"
563        }
564        CreateType(_) => "type",
565        // NOTE: every statement that creates a catalog item needs an arm above. These
566        // catalog views run this over every item row before their type filter drops the
567        // unwanted rows, so one unclassified `create_sql` takes out `mz_objects`,
568        // `mz_indexes`, and every sibling view at once. The match is exhaustive to make
569        // that a compile error here, not a runtime failure.
570        Select(_)
571        | Insert(_)
572        | Copy(_)
573        | Update(_)
574        | Delete(_)
575        | CreateDatabase(_)
576        | CreateSchema(_)
577        | CreateRole(_)
578        | CreateCluster(_)
579        | CreateClusterReplica(_)
580        | CreateNetworkPolicy(_)
581        | CreateQueryPolicy(_)
582        | AlterCluster(_)
583        | AlterOwner(_)
584        | AlterObjectRename(_)
585        | AlterObjectSwap(_)
586        | AlterRetainHistory(_)
587        | AlterIndex(_)
588        | AlterSecret(_)
589        | AlterSetCluster(_)
590        | AlterSink(_)
591        | AlterSource(_)
592        | AlterSystemSet(_)
593        | AlterSystemReset(_)
594        | AlterSystemResetAll(_)
595        | AlterConnection(_)
596        | AlterNetworkPolicy(_)
597        | AlterQueryPolicy(_)
598        | AlterRole(_)
599        | AlterTableAddColumn(_)
600        | AlterMaterializedViewApplyReplacement(_)
601        | Discard(_)
602        | DropObjects(_)
603        | DropOwned(_)
604        | SetVariable(_)
605        | ResetVariable(_)
606        | Show(_)
607        | StartTransaction(_)
608        | SetTransaction(_)
609        | Commit(_)
610        | Rollback(_)
611        | Subscribe(_)
612        | ExplainPlan(_)
613        | ExplainPushdown(_)
614        | ExplainTimestamp(_)
615        | ExplainSinkSchema(_)
616        | ExplainAnalyzeObject(_)
617        | ExplainAnalyzeCluster(_)
618        | Declare(_)
619        | Fetch(_)
620        | Close(_)
621        | Prepare(_)
622        | Execute(_)
623        | ExecuteUnitTest(_)
624        | Deallocate(_)
625        | Raise(_)
626        | GrantRole(_)
627        | RevokeRole(_)
628        | GrantPrivileges(_)
629        | RevokePrivileges(_)
630        | AlterDefaultPrivileges(_)
631        | ReassignOwned(_)
632        | ValidateConnection(_)
633        | Comment(_) => return Err("not a CREATE item statement".into()),
634    };
635    info.insert("type", json!(item_type));
636
637    let info = info.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
638    Ok(info)
639}
640
641/// Extracts the catalog item references from a catalog `create_sql` string as a JSONB object.
642///
643/// - `ids`: array of catalog id strings from `[<id> AS <name>]` references.
644/// - `named_funcs`: array of function references such as "pg_catalog"."max".
645/// - `named_types`: array of type references such as "pg_catalog"."int4", exclusive from the ones
646///   in `ids`.
647/// - `named_relations`: array of relation references, exclusive from the ones in `ids`.
648pub fn item_references(a: &str) -> Result<serde_json::Value, String> {
649    fn qualified(name: &UnresolvedItemName) -> serde_json::Value {
650        match &name.0[..] {
651            [.., schema, item] => json!({"schema": schema.as_str(), "name": item.as_str()}),
652            [item] => json!({"schema": serde_json::Value::Null, "name": item.as_str()}),
653            [] => json!({"schema": serde_json::Value::Null, "name": ""}),
654        }
655    }
656
657    let stmt = parse_single_statement(a)?;
658
659    let refs = collect_item_references(&stmt);
660    mz_ore::soft_assert_or_log!(
661        refs.named_array_elements.is_empty(),
662        "persisted create_sql should never carry an array type T[] \
663        and resolve its array type in `ids`: {:?}",
664        refs.named_array_elements
665    );
666    Ok(json!({
667        "ids": refs.ids.iter().collect::<Vec<_>>(),
668        "named_funcs": refs.named_funcs.iter().map(qualified).collect::<Vec<_>>(),
669        "named_types": refs.named_types.iter().map(qualified).collect::<Vec<_>>(),
670        "named_relations": refs.named_relations.iter().map(qualified).collect::<Vec<_>>(),
671    }))
672}
673
674/// Minimal decoder for `ProtoPostgresSourcePublicationDetails`. The
675/// canonical proto lives in `mz-storage-types`, which depends on this
676/// crate via `mz-expr`, so we redeclare the two tags we read here. Upstream tag
677/// renumbers slip past silently. The `mz_postgres_sources` lockdown
678/// SLTs catch them.
679#[derive(Clone, PartialEq, ::prost::Message)]
680struct PostgresPublicationDetailsSubset {
681    #[prost(string, tag = "2")]
682    slot: String,
683    #[prost(uint64, optional, tag = "3")]
684    timeline_id: Option<u64>,
685}
686
687/// Extracts postgres source publication details (slot, timeline_id) from a
688/// catalog `create_sql`. Returns:
689///
690/// - jsonb `{"slot": <text>, "timeline_id": <u64 | null>}` for `CREATE SOURCE ... FROM POSTGRES
691///   CONNECTION ... (DETAILS = ...)` statements.
692/// - jsonb `null` for any other statement.
693///
694/// Errors if the statement fails to parse, is a postgres source without
695/// a `DETAILS` option, or if the `DETAILS` value can't be hex- and
696/// proto-decoded.
697pub fn postgres_source_details(a: &str) -> Result<serde_json::Value, String> {
698    let stmt = parse_single_statement(a)?;
699
700    use mz_sql_parser::ast::CreateSourceConnection;
701    use mz_sql_parser::ast::Statement::CreateSource;
702    let options = match stmt {
703        CreateSource(stmt) => match stmt.connection {
704            CreateSourceConnection::Postgres { options, .. } => options,
705            _ => return Ok(serde_json::Value::Null),
706        },
707        _ => return Ok(serde_json::Value::Null),
708    };
709
710    let details_hex = options
711        .into_iter()
712        .find(|opt| opt.name == PgConfigOptionName::Details)
713        .and_then(|opt| match opt.value {
714            Some(WithOptionValue::Value(Value::String(s))) => Some(s),
715            _ => None,
716        })
717        .ok_or("missing DETAILS option on postgres source")?;
718
719    let details_bytes =
720        hex::decode(&details_hex).map_err(|e| format!("DETAILS is not valid hex: {e}"))?;
721
722    let details = PostgresPublicationDetailsSubset::decode(&*details_bytes)
723        .map_err(|e| format!("DETAILS is not a valid publication-details proto: {e}"))?;
724
725    Ok(json!({
726        "slot": details.slot,
727        "timeline_id": details.timeline_id,
728    }))
729}
730
731/// Extracts kafka source configuration (topic, group id prefix, connection
732/// id) from a catalog `create_sql`. Returns:
733///
734/// - jsonb `{"topic": <text>, "group_id_prefix": <text | null>, "connection_id": <text>}` for
735///   `CREATE SOURCE ... FROM KAFKA CONNECTION ... (TOPIC = ..., [GROUP ID PREFIX = ...])`
736///   statements.
737/// - jsonb `null` for any other statement.
738///
739/// Errors if the statement fails to parse, is a kafka source without a
740/// `TOPIC` option, or references an unresolved connection name (i.e. one
741/// that hasn't been through purification).
742pub fn kafka_source_details(a: &str) -> Result<serde_json::Value, String> {
743    let stmt = parse_single_statement(a)?;
744
745    use mz_sql_parser::ast::CreateSourceConnection;
746    use mz_sql_parser::ast::Statement::CreateSource;
747    let (connection, options) = match stmt {
748        CreateSource(stmt) => match stmt.connection {
749            CreateSourceConnection::Kafka {
750                connection,
751                options,
752            } => (connection, options),
753            _ => return Ok(serde_json::Value::Null),
754        },
755        _ => return Ok(serde_json::Value::Null),
756    };
757
758    let connection_id = item_id(connection)?;
759
760    let mut topic: Option<String> = None;
761    let mut group_id_prefix: Option<String> = None;
762    for opt in options {
763        let string_value = opt.value.as_ref().and_then(option_string);
764        match opt.name {
765            KafkaSourceConfigOptionName::Topic => topic = string_value,
766            KafkaSourceConfigOptionName::GroupIdPrefix => group_id_prefix = string_value,
767            _ => {}
768        }
769    }
770
771    let topic = topic.ok_or("missing TOPIC option on kafka source")?;
772
773    Ok(json!({
774        "topic": topic,
775        "group_id_prefix": group_id_prefix,
776        "connection_id": connection_id,
777    }))
778}
779
780/// Extracts source-export (source table) metadata from a catalog `create_sql`.
781///
782/// Returns, for a `CREATE TABLE ... FROM SOURCE` or a non-progress
783/// `CREATE SUBSOURCE ... OF SOURCE ...` statement:
784///
785/// ```json
786/// {
787///   "source_id": "<parent source item id>",
788///   "external_reference": ["part1", "part2", ...],
789///   "envelope_type": <text | null>,
790///   "key_format": <text | null>,
791///   "value_format": <text | null>
792/// }
793/// ```
794///
795/// `envelope_type`, `key_format`, and `value_format` are always null for a
796/// `CREATE SUBSOURCE` (the postgres/mysql/sql-server exports that use the old
797/// subsource syntax carry neither format nor envelope). They may also be null
798/// for a `CREATE TABLE ... FROM SOURCE` that omits FORMAT/ENVELOPE.
799///
800/// Returns jsonb `null` for progress subsources and for any statement that is
801/// not a source export. The caller distinguishes the four source-table views
802/// by joining `source_id` against `mz_sources` and filtering on the parent's
803/// type, so this helper stays connection-type agnostic.
804///
805/// Errors if the statement fails to parse, references an unresolved item name,
806/// or is a non-progress subsource missing its OF SOURCE or EXTERNAL REFERENCE.
807///
808/// The `key_format`/`value_format` derivation mirrors the runtime
809/// `DataSourceDesc::formats()` that the removed `pack_kafka_source_tables_update`
810/// packer read. A bare FORMAT only carries a key when it resolves to an
811/// encoding that has one, which among bare formats is only Avro or Protobuf
812/// read from a Confluent Schema Registry whose purified seed carries a key
813/// schema. A KEY FORMAT ... VALUE FORMAT ... spec always carries both.
814pub fn source_export_details(a: &str) -> Result<serde_json::Value, String> {
815    // A bare FORMAT resolves to an encoding with a key only for Avro or
816    // Protobuf read from a schema registry whose purified seed carries a key
817    // schema. Every other bare format is value-only.
818    fn bare_format_has_key<T: AstInfo>(fmt: &Format<T>) -> bool {
819        match fmt {
820            Format::Avro(AvroSchema::Csr { csr_connection }) => csr_connection
821                .seed
822                .as_ref()
823                .is_some_and(|seed| seed.key_schema.is_some()),
824            Format::Protobuf(ProtobufSchema::Csr { csr_connection }) => csr_connection
825                .seed
826                .as_ref()
827                .is_some_and(|seed| seed.key.is_some()),
828            _ => false,
829        }
830    }
831
832    fn key_value_formats<T: AstInfo>(
833        spec: &FormatSpecifier<T>,
834    ) -> (Option<&'static str>, Option<&'static str>) {
835        match spec {
836            FormatSpecifier::KeyValue { key, value } => {
837                (Some(format_name(key)), Some(format_name(value)))
838            }
839            FormatSpecifier::Bare(fmt) => {
840                let value = Some(format_name(fmt));
841                let key = bare_format_has_key(fmt).then(|| format_name(fmt));
842                (key, value)
843            }
844        }
845    }
846
847    fn envelope_name(envelope: &SourceEnvelope) -> &'static str {
848        match envelope {
849            SourceEnvelope::None => "none",
850            SourceEnvelope::Debezium => "debezium",
851            SourceEnvelope::Upsert {
852                value_decode_err_policy,
853            } => {
854                if value_decode_err_policy
855                    .iter()
856                    .any(|p| matches!(p, SourceErrorPolicy::Inline { .. }))
857                {
858                    "upsert-value-err-inline"
859                } else {
860                    "upsert"
861                }
862            }
863            SourceEnvelope::CdcV2 => "materialize",
864        }
865    }
866
867    let stmt = parse_single_statement(a)?;
868
869    use mz_sql_parser::ast::Statement::{CreateSubsource, CreateTableFromSource};
870    match stmt {
871        CreateTableFromSource(stmt) => {
872            let source_id = item_id(stmt.source)?;
873            let external_reference = stmt
874                .external_reference
875                .ok_or("missing external reference on CREATE TABLE FROM SOURCE")?
876                .0
877                .into_iter()
878                .map(|ident| ident.into_string())
879                .collect::<Vec<_>>();
880
881            let envelope_type = stmt.envelope.as_ref().map(envelope_name);
882            let (key_format, value_format) = match &stmt.format {
883                Some(spec) => key_value_formats(spec),
884                None => (None, None),
885            };
886
887            Ok(json!({
888                "source_id": source_id,
889                "external_reference": external_reference,
890                "envelope_type": envelope_type,
891                "key_format": key_format,
892                "value_format": value_format,
893            }))
894        }
895        CreateSubsource(stmt) => {
896            // Progress subsources track ingestion progress and are not
897            // source tables. They have no external reference.
898            let is_progress = stmt
899                .with_options
900                .iter()
901                .any(|o| matches!(o.name, CreateSubsourceOptionName::Progress));
902            if is_progress {
903                return Ok(serde_json::Value::Null);
904            }
905
906            let source_id = stmt
907                .of_source
908                .ok_or("non-progress CREATE SUBSOURCE without OF SOURCE")
909                .and_then(item_id)?;
910
911            let external_reference = stmt
912                .with_options
913                .into_iter()
914                .find(|o| matches!(o.name, CreateSubsourceOptionName::ExternalReference))
915                .and_then(|o| match o.value {
916                    Some(WithOptionValue::UnresolvedItemName(name)) => Some(name),
917                    _ => None,
918                })
919                .ok_or("CREATE SUBSOURCE missing EXTERNAL REFERENCE option")?
920                .0
921                .into_iter()
922                .map(|ident| ident.into_string())
923                .collect::<Vec<_>>();
924
925            Ok(json!({
926                "source_id": source_id,
927                "external_reference": external_reference,
928                "envelope_type": serde_json::Value::Null,
929                "key_format": serde_json::Value::Null,
930                "value_format": serde_json::Value::Null,
931            }))
932        }
933        _ => Ok(serde_json::Value::Null),
934    }
935}
936
937/// Extracts connection-detail metadata from a catalog `create_sql`.
938///
939/// Returns a per-connection-type object with the fields that the
940/// `mz_kafka_connections`, `mz_ssh_tunnel_connections`, and `mz_aws_connections`
941/// builtin views need. For everything else (other connection types, including
942/// aws-privatelink whose only detail is context-derived, and non-connection
943/// statements) it returns jsonb `null`, so callers filter on `IS NOT NULL` and
944/// gate on the connection type separately (via
945/// `parse_catalog_create_sql(...)->>'connection_type'`, the way `mz_connections`
946/// already does).
947///
948/// The shape per type:
949///
950/// ```json
951/// // kafka
952/// { "brokers": ["host:port", ...], "progress_topic": <text | null> }
953/// // ssh-tunnel
954/// { "public_key_1": "<text>", "public_key_2": "<text>" }
955/// // aws
956/// {
957///   "auth_kind": "credentials" | "assume-role",
958///   "endpoint": <text | null>, "region": <text | null>,
959///   "access_key_id": <text | null>, "access_key_id_secret_id": <text | null>,
960///   "secret_access_key_secret_id": <text | null>,
961///   "session_token": <text | null>, "session_token_secret_id": <text | null>,
962///   "assume_role_arn": <text | null>, "assume_role_session_name": <text | null>
963/// }
964/// ```
965///
966/// `progress_topic` is null when the connection does not set an explicit
967/// `PROGRESS TOPIC`. The default (`_materialize-progress-<env>-<conn_id>`) is
968/// reconstructed by the view, not here, because it needs the environment id and
969/// the connection's own id. Values derived only from environment context
970/// (AWS principal, external id, trust policy, privatelink principal) are also
971/// left to the view. This keeps the helper a pure function of the `create_sql`.
972///
973/// For aws, an option is either an inline value or a secret reference. Inline
974/// values land in `access_key_id`/`session_token`; a secret reference lands in
975/// the matching `*_secret_id` as the referenced secret's catalog item id (the
976/// persisted `create_sql` stores resolved references as `[uNNN AS name]`).
977/// `auth_kind` is `assume-role` when `ASSUME ROLE ARN` is present, else
978/// `credentials`, matching the `AwsAuth` variant the removed packer read.
979///
980/// Errors if the statement fails to parse.
981pub fn connection_details(a: &str) -> Result<serde_json::Value, String> {
982    // The persisted `create_sql` stores an inline broker as a single `BROKER`
983    // option and a broker list as a `BROKERS (...)` sequence. Either way we
984    // only need the addresses, which are present regardless of the tunnel
985    // (direct, SSH, or PrivateLink).
986    fn broker_addresses<T: AstInfo>(values: &[ConnectionOption<T>]) -> Vec<String> {
987        let mut brokers = Vec::new();
988        for opt in values {
989            match (&opt.name, &opt.value) {
990                (ConnectionOptionName::Broker, Some(WithOptionValue::ConnectionKafkaBroker(b))) => {
991                    brokers.push(b.address.clone());
992                }
993                (ConnectionOptionName::Brokers, Some(WithOptionValue::Sequence(seq))) => {
994                    for v in seq {
995                        if let WithOptionValue::ConnectionKafkaBroker(b) = v {
996                            brokers.push(b.address.clone());
997                        }
998                    }
999                }
1000                _ => {}
1001            }
1002        }
1003        brokers
1004    }
1005
1006    fn string_option<T: AstInfo>(
1007        values: &[ConnectionOption<T>],
1008        name: ConnectionOptionName,
1009    ) -> Option<String> {
1010        values
1011            .iter()
1012            .find(|o| o.name == name)
1013            .and_then(|o| o.value.as_ref())
1014            .and_then(option_string)
1015    }
1016
1017    // The catalog id of the secret a `SECRET ...` option references. Resolved
1018    // references persist as `RawItemName::Id`, so an unresolved name yields
1019    // None (the same treatment [`item_id`] gives item names).
1020    fn secret_id_option<T: AstInfo<ItemName = RawItemName>>(
1021        values: &[ConnectionOption<T>],
1022        name: ConnectionOptionName,
1023    ) -> Option<String> {
1024        values.iter().find_map(|o| match &o.value {
1025            Some(WithOptionValue::Secret(RawItemName::Id(id, _, _))) if o.name == name => {
1026                Some(id.clone())
1027            }
1028            _ => None,
1029        })
1030    }
1031
1032    let stmt = parse_single_statement(a)?;
1033
1034    use mz_sql_parser::ast::Statement::CreateConnection;
1035    let stmt = match stmt {
1036        CreateConnection(stmt) => stmt,
1037        _ => return Ok(serde_json::Value::Null),
1038    };
1039
1040    match stmt.connection_type {
1041        CreateConnectionType::Kafka => Ok(json!({
1042            "brokers": broker_addresses(&stmt.values),
1043            "progress_topic": string_option(&stmt.values, ConnectionOptionName::ProgressTopic),
1044        })),
1045        CreateConnectionType::Ssh => Ok(json!({
1046            "public_key_1": string_option(&stmt.values, ConnectionOptionName::PublicKey1),
1047            "public_key_2": string_option(&stmt.values, ConnectionOptionName::PublicKey2),
1048        })),
1049        CreateConnectionType::Aws => {
1050            let assume_role_arn = string_option(&stmt.values, ConnectionOptionName::AssumeRoleArn);
1051            let auth_kind = if assume_role_arn.is_some() {
1052                "assume-role"
1053            } else {
1054                "credentials"
1055            };
1056            Ok(json!({
1057                "auth_kind": auth_kind,
1058                // Planning coerces an empty ENDPOINT to None (see
1059                // `src/sql/src/plan/statement/ddl/connection.rs`), so the
1060                // removed packer wrote NULL for `ENDPOINT = ''`. Match that.
1061                "endpoint": string_option(&stmt.values, ConnectionOptionName::Endpoint)
1062                    .filter(|s| !s.is_empty()),
1063                "region": string_option(&stmt.values, ConnectionOptionName::Region),
1064                "access_key_id": string_option(&stmt.values, ConnectionOptionName::AccessKeyId),
1065                "access_key_id_secret_id":
1066                    secret_id_option(&stmt.values, ConnectionOptionName::AccessKeyId),
1067                "secret_access_key_secret_id":
1068                    secret_id_option(&stmt.values, ConnectionOptionName::SecretAccessKey),
1069                "session_token": string_option(&stmt.values, ConnectionOptionName::SessionToken),
1070                "session_token_secret_id":
1071                    secret_id_option(&stmt.values, ConnectionOptionName::SessionToken),
1072                "assume_role_arn": assume_role_arn,
1073                "assume_role_session_name":
1074                    string_option(&stmt.values, ConnectionOptionName::AssumeRoleSessionName),
1075            }))
1076        }
1077        _ => Ok(serde_json::Value::Null),
1078    }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083    use prost::Message as _;
1084    use serde_json::json;
1085
1086    /// Encode the two proto fields our decoder cares about, using the same
1087    /// tag numbering as the canonical proto.
1088    fn encode_pg_details(slot: &str, timeline_id: Option<u64>) -> String {
1089        let details = super::PostgresPublicationDetailsSubset {
1090            slot: slot.to_string(),
1091            timeline_id,
1092        };
1093        hex::encode(details.encode_to_vec())
1094    }
1095
1096    fn pg_source_sql(details_hex: &str) -> String {
1097        format!(
1098            "CREATE SOURCE \"materialize\".\"public\".\"pg_src\" \
1099             IN CLUSTER [u42] \
1100             FROM POSTGRES CONNECTION [u10 AS \"materialize\".\"public\".\"pg_conn\"] \
1101             (DETAILS = '{details_hex}', PUBLICATION = 'mz_source') \
1102             FOR ALL TABLES"
1103        )
1104    }
1105
1106    fn kafka_source_sql(with_prefix: bool) -> String {
1107        let prefix_opt = if with_prefix {
1108            ", GROUP ID PREFIX 'my-prefix-'"
1109        } else {
1110            ""
1111        };
1112        format!(
1113            "CREATE SOURCE \"materialize\".\"public\".\"k_src\" \
1114             IN CLUSTER [u42] \
1115             FROM KAFKA CONNECTION [u11 AS \"materialize\".\"public\".\"k_conn\"] \
1116             (TOPIC 'test'{prefix_opt}) FORMAT TEXT"
1117        )
1118    }
1119
1120    // --- parse_postgres_source_details ---------------------------------------
1121
1122    #[mz_ore::test]
1123    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
1124    fn pg_happy_path_with_timeline() {
1125        let hex = encode_pg_details("materialize_abc", Some(42));
1126        let sql = pg_source_sql(&hex);
1127        let out = super::postgres_source_details(&sql).expect("ok");
1128        assert_eq!(out, json!({ "slot": "materialize_abc", "timeline_id": 42 }));
1129    }
1130
1131    #[mz_ore::test]
1132    fn pg_happy_path_null_timeline() {
1133        // Pre-2024 sources have no timeline_id field. The decoder must
1134        // surface that as JSON null, not error.
1135        let hex = encode_pg_details("materialize_legacy", None);
1136        let sql = pg_source_sql(&hex);
1137        let out = super::postgres_source_details(&sql).expect("ok");
1138        assert_eq!(
1139            out,
1140            json!({ "slot": "materialize_legacy", "timeline_id": null }),
1141        );
1142    }
1143
1144    #[mz_ore::test]
1145    fn pg_non_postgres_source_returns_null_jsonb() {
1146        let sql = "CREATE SOURCE \"materialize\".\"public\".\"lg\" \
1147             IN CLUSTER [u42] FROM LOAD GENERATOR COUNTER";
1148        let out = super::postgres_source_details(sql).expect("ok");
1149        assert_eq!(out, serde_json::Value::Null);
1150    }
1151
1152    #[mz_ore::test]
1153    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1154    fn pg_non_create_source_returns_null_jsonb() {
1155        let sql = "CREATE VIEW v AS SELECT 1";
1156        let out = super::postgres_source_details(sql).expect("ok");
1157        assert_eq!(out, serde_json::Value::Null);
1158    }
1159
1160    #[mz_ore::test]
1161    fn pg_missing_details_option_errors() {
1162        let sql = "CREATE SOURCE \"materialize\".\"public\".\"pg_src\" \
1163             IN CLUSTER [u42] \
1164             FROM POSTGRES CONNECTION [u10 AS \"materialize\".\"public\".\"pg_conn\"] \
1165             (PUBLICATION = 'mz_source') FOR ALL TABLES";
1166        let err = super::postgres_source_details(sql).unwrap_err();
1167        assert!(
1168            err.contains("missing DETAILS"),
1169            "wrong error message: {err}"
1170        );
1171    }
1172
1173    #[mz_ore::test]
1174    fn pg_malformed_hex_errors() {
1175        let sql = pg_source_sql("not-hex!!");
1176        let err = super::postgres_source_details(&sql).unwrap_err();
1177        assert!(err.contains("valid hex"), "wrong error message: {err}");
1178    }
1179
1180    #[mz_ore::test]
1181    fn pg_malformed_proto_errors() {
1182        // Valid hex, garbage bytes. Prost decoding fails on unexpected wire
1183        // format.
1184        let sql = pg_source_sql("ffff");
1185        let err = super::postgres_source_details(&sql).unwrap_err();
1186        assert!(
1187            err.contains("publication-details proto"),
1188            "wrong error message: {err}"
1189        );
1190    }
1191
1192    // --- parse_kafka_source_details ------------------------------------------
1193
1194    #[mz_ore::test]
1195    fn kafka_happy_path_with_prefix() {
1196        let sql = kafka_source_sql(true);
1197        let out = super::kafka_source_details(&sql).expect("ok");
1198        assert_eq!(
1199            out,
1200            json!({
1201                "topic": "test",
1202                "group_id_prefix": "my-prefix-",
1203                "connection_id": "u11",
1204            }),
1205        );
1206    }
1207
1208    #[mz_ore::test]
1209    fn kafka_happy_path_without_prefix() {
1210        let sql = kafka_source_sql(false);
1211        let out = super::kafka_source_details(&sql).expect("ok");
1212        assert_eq!(
1213            out,
1214            json!({
1215                "topic": "test",
1216                "group_id_prefix": null,
1217                "connection_id": "u11",
1218            }),
1219        );
1220    }
1221
1222    #[mz_ore::test]
1223    fn kafka_non_kafka_source_returns_null_jsonb() {
1224        let sql = "CREATE SOURCE \"materialize\".\"public\".\"lg\" \
1225             IN CLUSTER [u42] FROM LOAD GENERATOR COUNTER";
1226        let out = super::kafka_source_details(sql).expect("ok");
1227        assert_eq!(out, serde_json::Value::Null);
1228    }
1229
1230    #[mz_ore::test]
1231    fn kafka_missing_topic_errors() {
1232        let sql = "CREATE SOURCE \"materialize\".\"public\".\"k_src\" \
1233             IN CLUSTER [u42] \
1234             FROM KAFKA CONNECTION [u11 AS \"materialize\".\"public\".\"k_conn\"] \
1235             FORMAT TEXT";
1236        let err = super::kafka_source_details(sql).unwrap_err();
1237        assert!(err.contains("missing TOPIC"), "wrong error message: {err}");
1238    }
1239
1240    #[mz_ore::test]
1241    fn kafka_unquoted_topic_and_prefix() {
1242        // Planning accepts a bare identifier for TOPIC / GROUP ID PREFIX, and it
1243        // persists unquoted in create_sql. Matching only quoted strings would
1244        // drop TOPIC and error the whole mz_kafka_source_tables view.
1245        let sql = "CREATE SOURCE \"materialize\".\"public\".\"k_src\" \
1246             IN CLUSTER [u42] \
1247             FROM KAFKA CONNECTION [u11 AS \"materialize\".\"public\".\"k_conn\"] \
1248             (TOPIC = my_topic, GROUP ID PREFIX = my_prefix) FORMAT TEXT";
1249        let out = super::kafka_source_details(sql).expect("ok");
1250        assert_eq!(out["topic"], json!("my_topic"));
1251        assert_eq!(out["group_id_prefix"], json!("my_prefix"));
1252    }
1253
1254    #[mz_ore::test]
1255    fn kafka_unresolved_connection_errors() {
1256        // A bare-name connection reference never happens after purification,
1257        // but the decoder must reject it explicitly rather than silently
1258        // dropping the connection_id.
1259        let sql = "CREATE SOURCE \"materialize\".\"public\".\"k_src\" \
1260             IN CLUSTER [u42] \
1261             FROM KAFKA CONNECTION k_conn (TOPIC 'test') FORMAT TEXT";
1262        let err = super::kafka_source_details(sql).unwrap_err();
1263        assert!(
1264            err.contains("unresolved item name"),
1265            "wrong error message: {err}"
1266        );
1267    }
1268
1269    // --- parse_source_export_details -----------------------------------------
1270
1271    fn table_from_source_sql(reference: &str, suffix: &str) -> String {
1272        format!(
1273            "CREATE TABLE \"materialize\".\"public\".\"tbl\" \
1274             FROM SOURCE [u1 AS \"materialize\".\"public\".\"src\"] \
1275             (REFERENCE = {reference}){suffix}"
1276        )
1277    }
1278
1279    #[mz_ore::test]
1280    fn export_table_postgres_style_no_format() {
1281        // Postgres/mysql/sql-server tables carry a multi-part external
1282        // reference and no format or envelope.
1283        let sql = table_from_source_sql("\"db\".\"public\".\"t\"", "");
1284        let out = super::source_export_details(&sql).expect("ok");
1285        assert_eq!(
1286            out,
1287            json!({
1288                "source_id": "u1",
1289                "external_reference": ["db", "public", "t"],
1290                "envelope_type": null,
1291                "key_format": null,
1292                "value_format": null,
1293            }),
1294        );
1295    }
1296
1297    #[mz_ore::test]
1298    fn export_table_kafka_bare_value_only() {
1299        // A bare non-registry FORMAT is value-only: no key format.
1300        let sql = table_from_source_sql("\"topic\"", " FORMAT TEXT ENVELOPE NONE");
1301        let out = super::source_export_details(&sql).expect("ok");
1302        assert_eq!(
1303            out,
1304            json!({
1305                "source_id": "u1",
1306                "external_reference": ["topic"],
1307                "envelope_type": "none",
1308                "key_format": null,
1309                "value_format": "text",
1310            }),
1311        );
1312    }
1313
1314    #[mz_ore::test]
1315    fn export_table_kafka_omitted_envelope_is_null() {
1316        // Omitting ENVELOPE persists as absent in create_sql, so this
1317        // source-type-agnostic helper reports null. The mz_kafka_source_tables
1318        // view is responsible for defaulting kafka's null envelope to 'none'.
1319        let sql = table_from_source_sql("\"topic\"", " FORMAT TEXT");
1320        let out = super::source_export_details(&sql).expect("ok");
1321        assert_eq!(out["envelope_type"], serde_json::Value::Null);
1322    }
1323
1324    #[mz_ore::test]
1325    fn export_table_kafka_key_value_format() {
1326        let sql = table_from_source_sql(
1327            "\"topic\"",
1328            " KEY FORMAT TEXT VALUE FORMAT TEXT ENVELOPE NONE",
1329        );
1330        let out = super::source_export_details(&sql).expect("ok");
1331        assert_eq!(
1332            out,
1333            json!({
1334                "source_id": "u1",
1335                "external_reference": ["topic"],
1336                "envelope_type": "none",
1337                "key_format": "text",
1338                "value_format": "text",
1339            }),
1340        );
1341    }
1342
1343    #[mz_ore::test]
1344    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1345    fn export_table_kafka_bare_avro_seed_with_key() {
1346        // A bare Avro CSR format whose seed carries a key schema resolves to
1347        // an encoding with a key, so key_format mirrors value_format. This is
1348        // the upsert/debezium path.
1349        let sql = table_from_source_sql(
1350            "\"topic\"",
1351            " FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY \
1352             CONNECTION [u5 AS \"materialize\".\"public\".\"csr\"] \
1353             SEED KEY SCHEMA 'k' VALUE SCHEMA 'v' ENVELOPE UPSERT",
1354        );
1355        let out = super::source_export_details(&sql).expect("ok");
1356        assert_eq!(
1357            out,
1358            json!({
1359                "source_id": "u1",
1360                "external_reference": ["topic"],
1361                "envelope_type": "upsert",
1362                "key_format": "avro",
1363                "value_format": "avro",
1364            }),
1365        );
1366    }
1367
1368    #[mz_ore::test]
1369    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1370    fn export_table_kafka_bare_avro_seed_without_key() {
1371        // A bare Avro CSR seed with only a value schema is value-only.
1372        let sql = table_from_source_sql(
1373            "\"topic\"",
1374            " FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY \
1375             CONNECTION [u5 AS \"materialize\".\"public\".\"csr\"] \
1376             SEED VALUE SCHEMA 'v' ENVELOPE NONE",
1377        );
1378        let out = super::source_export_details(&sql).expect("ok");
1379        assert_eq!(
1380            out,
1381            json!({
1382                "source_id": "u1",
1383                "external_reference": ["topic"],
1384                "envelope_type": "none",
1385                "key_format": null,
1386                "value_format": "avro",
1387            }),
1388        );
1389    }
1390
1391    #[mz_ore::test]
1392    fn export_subsource_non_progress() {
1393        // Old-syntax subsource: external reference lives in a WITH option, and
1394        // there is never a format or envelope.
1395        let sql = "CREATE SUBSOURCE \"materialize\".\"public\".\"sub\" (id int4) \
1396             OF SOURCE [u1 AS \"materialize\".\"public\".\"src\"] \
1397             WITH (EXTERNAL REFERENCE = \"db\".\"public\".\"t\")";
1398        let out = super::source_export_details(sql).expect("ok");
1399        assert_eq!(
1400            out,
1401            json!({
1402                "source_id": "u1",
1403                "external_reference": ["db", "public", "t"],
1404                "envelope_type": null,
1405                "key_format": null,
1406                "value_format": null,
1407            }),
1408        );
1409    }
1410
1411    #[mz_ore::test]
1412    fn export_progress_subsource_returns_null_jsonb() {
1413        let sql = "CREATE SUBSOURCE \"materialize\".\"public\".\"progress\" (id int4) \
1414             WITH (PROGRESS)";
1415        let out = super::source_export_details(sql).expect("ok");
1416        assert_eq!(out, serde_json::Value::Null);
1417    }
1418
1419    #[mz_ore::test]
1420    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1421    fn export_non_source_export_returns_null_jsonb() {
1422        let sql = "CREATE VIEW v AS SELECT 1";
1423        let out = super::source_export_details(sql).expect("ok");
1424        assert_eq!(out, serde_json::Value::Null);
1425    }
1426
1427    #[mz_ore::test]
1428    fn export_unresolved_source_name_errors() {
1429        let sql = "CREATE TABLE \"materialize\".\"public\".\"tbl\" \
1430             FROM SOURCE src (REFERENCE = \"topic\")";
1431        let err = super::source_export_details(sql).unwrap_err();
1432        assert!(
1433            err.contains("unresolved item name"),
1434            "wrong error message: {err}"
1435        );
1436    }
1437
1438    // --- parse_connection_details --------------------------------------------
1439
1440    #[mz_ore::test]
1441    fn connection_kafka_single_broker_default_progress() {
1442        // No explicit PROGRESS TOPIC: the helper leaves it null and the view
1443        // reconstructs the default.
1444        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO KAFKA \
1445             (BROKER = 'localhost:9092', SECURITY PROTOCOL = plaintext)";
1446        let out = super::connection_details(sql).expect("ok");
1447        assert_eq!(
1448            out,
1449            json!({
1450                "brokers": ["localhost:9092"],
1451                "progress_topic": null,
1452            }),
1453        );
1454    }
1455
1456    #[mz_ore::test]
1457    fn connection_kafka_explicit_progress_topic() {
1458        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO KAFKA \
1459             (BROKER = 'localhost:9092', PROGRESS TOPIC = 'override', \
1460              SECURITY PROTOCOL = plaintext)";
1461        let out = super::connection_details(sql).expect("ok");
1462        assert_eq!(
1463            out,
1464            json!({
1465                "brokers": ["localhost:9092"],
1466                "progress_topic": "override",
1467            }),
1468        );
1469    }
1470
1471    #[mz_ore::test]
1472    fn connection_kafka_broker_list() {
1473        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO KAFKA \
1474             (BROKERS ('b1:9092', 'b2:9092'), SECURITY PROTOCOL = plaintext)";
1475        let out = super::connection_details(sql).expect("ok");
1476        assert_eq!(
1477            out,
1478            json!({
1479                "brokers": ["b1:9092", "b2:9092"],
1480                "progress_topic": null,
1481            }),
1482        );
1483    }
1484
1485    #[mz_ore::test]
1486    fn connection_ssh_public_keys() {
1487        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO SSH TUNNEL \
1488             (HOST = 'ssh.example.com', PORT = 22, USER = 'mz', \
1489              PUBLIC KEY 1 = 'ssh-ed25519 AAAA', PUBLIC KEY 2 = 'ssh-ed25519 BBBB')";
1490        let out = super::connection_details(sql).expect("ok");
1491        assert_eq!(
1492            out,
1493            json!({
1494                "public_key_1": "ssh-ed25519 AAAA",
1495                "public_key_2": "ssh-ed25519 BBBB",
1496            }),
1497        );
1498    }
1499
1500    #[mz_ore::test]
1501    fn connection_aws_credentials_inline_key() {
1502        // Inline ACCESS KEY ID, secret SECRET ACCESS KEY. Assume-role columns
1503        // stay null and auth_kind is credentials.
1504        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO AWS \
1505             (ACCESS KEY ID = 'AKIAEXAMPLE', \
1506              SECRET ACCESS KEY = SECRET [u1 AS \"materialize\".\"public\".\"sk\"])";
1507        let out = super::connection_details(sql).expect("ok");
1508        assert_eq!(
1509            out,
1510            json!({
1511                "auth_kind": "credentials",
1512                "endpoint": null,
1513                "region": null,
1514                "access_key_id": "AKIAEXAMPLE",
1515                "access_key_id_secret_id": null,
1516                "secret_access_key_secret_id": "u1",
1517                "session_token": null,
1518                "session_token_secret_id": null,
1519                "assume_role_arn": null,
1520                "assume_role_session_name": null,
1521            }),
1522        );
1523    }
1524
1525    #[mz_ore::test]
1526    fn connection_aws_credentials_secret_key_and_session_token() {
1527        // Every credential provided as a secret reference lands in the matching
1528        // *_secret_id column as the referenced secret's catalog id.
1529        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO AWS \
1530             (ENDPOINT = 'http://localhost', REGION = 'us-east-1', \
1531              ACCESS KEY ID = SECRET [u1 AS \"materialize\".\"public\".\"ak\"], \
1532              SECRET ACCESS KEY = SECRET [u2 AS \"materialize\".\"public\".\"sk\"], \
1533              SESSION TOKEN = SECRET [u3 AS \"materialize\".\"public\".\"st\"])";
1534        let out = super::connection_details(sql).expect("ok");
1535        assert_eq!(
1536            out,
1537            json!({
1538                "auth_kind": "credentials",
1539                "endpoint": "http://localhost",
1540                "region": "us-east-1",
1541                "access_key_id": null,
1542                "access_key_id_secret_id": "u1",
1543                "secret_access_key_secret_id": "u2",
1544                "session_token": null,
1545                "session_token_secret_id": "u3",
1546                "assume_role_arn": null,
1547                "assume_role_session_name": null,
1548            }),
1549        );
1550    }
1551
1552    #[mz_ore::test]
1553    fn connection_aws_assume_role() {
1554        // Assume-role sets auth_kind and the assume-role columns; credential
1555        // columns stay null.
1556        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO AWS \
1557             (ASSUME ROLE ARN 'arn:aws:iam::123:role/mz', \
1558              ASSUME ROLE SESSION NAME 'sess')";
1559        let out = super::connection_details(sql).expect("ok");
1560        assert_eq!(
1561            out,
1562            json!({
1563                "auth_kind": "assume-role",
1564                "endpoint": null,
1565                "region": null,
1566                "access_key_id": null,
1567                "access_key_id_secret_id": null,
1568                "secret_access_key_secret_id": null,
1569                "session_token": null,
1570                "session_token_secret_id": null,
1571                "assume_role_arn": "arn:aws:iam::123:role/mz",
1572                "assume_role_session_name": "sess",
1573            }),
1574        );
1575    }
1576
1577    #[mz_ore::test]
1578    fn connection_kafka_unquoted_progress_topic() {
1579        // A bare identifier PROGRESS TOPIC persists unquoted in create_sql. The
1580        // helper must surface it, else the view substitutes the default topic.
1581        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO KAFKA \
1582             (BROKER = 'localhost:9092', PROGRESS TOPIC = my_topic, \
1583              SECURITY PROTOCOL = plaintext)";
1584        let out = super::connection_details(sql).expect("ok");
1585        assert_eq!(out["progress_topic"], json!("my_topic"));
1586    }
1587
1588    #[mz_ore::test]
1589    fn connection_aws_unquoted_option_values() {
1590        // Planning accepts bare identifiers for these options and persists them
1591        // unquoted. The helper must surface them, not fall back to NULL.
1592        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO AWS \
1593             (ENDPOINT = localhost, REGION = useast1, \
1594              ASSUME ROLE ARN 'arn:aws:iam::123:role/mz', \
1595              ASSUME ROLE SESSION NAME = mysession)";
1596        let out = super::connection_details(sql).expect("ok");
1597        assert_eq!(out["endpoint"], json!("localhost"));
1598        assert_eq!(out["region"], json!("useast1"));
1599        assert_eq!(out["assume_role_session_name"], json!("mysession"));
1600    }
1601
1602    #[mz_ore::test]
1603    fn connection_aws_empty_endpoint_is_null() {
1604        // Planning coerces ENDPOINT = '' to None, so the packer wrote NULL. The
1605        // view must match, not report an empty string.
1606        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO AWS \
1607             (ENDPOINT = '', ASSUME ROLE ARN 'arn:aws:iam::123:role/mz')";
1608        let out = super::connection_details(sql).expect("ok");
1609        assert_eq!(out["endpoint"], serde_json::Value::Null);
1610    }
1611
1612    #[mz_ore::test]
1613    fn connection_other_type_returns_null_jsonb() {
1614        // A connection type without a detail view (postgres) yields null.
1615        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"c\" TO POSTGRES \
1616             (HOST = 'db', DATABASE = 'postgres', USER = 'mz')";
1617        let out = super::connection_details(sql).expect("ok");
1618        assert_eq!(out, serde_json::Value::Null);
1619    }
1620
1621    #[mz_ore::test]
1622    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1623    fn connection_non_connection_returns_null_jsonb() {
1624        let sql = "CREATE VIEW v AS SELECT 1";
1625        let out = super::connection_details(sql).expect("ok");
1626        assert_eq!(out, serde_json::Value::Null);
1627    }
1628
1629    // --- parse_catalog_create_sql envelope_type ------------------------------
1630
1631    #[mz_ore::test]
1632    fn catalog_kafka_old_syntax_omitted_envelope_defaults_none() {
1633        // An old-syntax kafka source (carries EXPOSE PROGRESS AS) ingests into
1634        // its own relation, so an omitted ENVELOPE means the default NONE, which
1635        // the pre-MV packer reported as 'none'.
1636        let sql = "CREATE SOURCE \"materialize\".\"public\".\"k\" \
1637             IN CLUSTER [u42] \
1638             FROM KAFKA CONNECTION [u11 AS \"materialize\".\"public\".\"k_conn\"] \
1639             (TOPIC 'test') FORMAT TEXT \
1640             EXPOSE PROGRESS AS [u12 AS \"materialize\".\"public\".\"k_progress\"]";
1641        let out = super::item_details(sql).expect("ok");
1642        assert_eq!(out["envelope_type"], json!("none"));
1643    }
1644
1645    #[mz_ore::test]
1646    fn catalog_kafka_old_syntax_explicit_envelope() {
1647        let sql = "CREATE SOURCE \"materialize\".\"public\".\"k\" \
1648             IN CLUSTER [u42] \
1649             FROM KAFKA CONNECTION [u11 AS \"materialize\".\"public\".\"k_conn\"] \
1650             (TOPIC 'test') FORMAT BYTES ENVELOPE UPSERT \
1651             EXPOSE PROGRESS AS [u12 AS \"materialize\".\"public\".\"k_progress\"]";
1652        let out = super::item_details(sql).expect("ok");
1653        assert_eq!(out["envelope_type"], json!("upsert"));
1654    }
1655
1656    #[mz_ore::test]
1657    fn catalog_kafka_new_syntax_source_omits_envelope_type() {
1658        // A new-syntax kafka source has no progress subsource (no EXPOSE PROGRESS
1659        // AS). It ingests nothing itself. Envelopes live on the per-table exports,
1660        // so its own envelope_type stays absent (SQL NULL).
1661        let sql = "CREATE SOURCE \"materialize\".\"public\".\"k\" \
1662             IN CLUSTER [u42] \
1663             FROM KAFKA CONNECTION [u11 AS \"materialize\".\"public\".\"k_conn\"]";
1664        let out = super::item_details(sql).expect("ok");
1665        assert_eq!(out.get("envelope_type"), None);
1666    }
1667
1668    #[mz_ore::test]
1669    fn catalog_non_kafka_source_omits_envelope_type() {
1670        // Non-kafka sources carry no envelope, so envelope_type stays absent
1671        // (SQL NULL), not 'none'.
1672        let sql = "CREATE SOURCE \"materialize\".\"public\".\"lg\" \
1673             IN CLUSTER [u42] FROM LOAD GENERATOR COUNTER";
1674        let out = super::item_details(sql).expect("ok");
1675        assert_eq!(out.get("envelope_type"), None);
1676    }
1677
1678    // --- parse_catalog_create_sql, CreateSink arm ----------------------------
1679
1680    const AVRO_FORMAT: &str = "FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY CONNECTION \
1681         [u12 AS \"materialize\".\"public\".\"csr_conn\"]";
1682
1683    /// A persisted kafka-sink `create_sql`: resolved names, and a `TOPIC` that
1684    /// planning guarantees.
1685    fn kafka_sink_sql(key: Option<&str>, format: &str, envelope: &str) -> String {
1686        let key_clause = key.map(|k| format!(" KEY ({k})")).unwrap_or_default();
1687        format!(
1688            "CREATE SINK \"materialize\".\"public\".\"snk\" \
1689             IN CLUSTER [u42] \
1690             FROM [u1 AS \"materialize\".\"public\".\"t\"] \
1691             INTO KAFKA CONNECTION [u10 AS \"materialize\".\"public\".\"k_conn\"] \
1692             (TOPIC 'sink-topic'){key_clause} {format} ENVELOPE {envelope}"
1693        )
1694    }
1695
1696    fn iceberg_sink_sql(mode: &str) -> String {
1697        format!(
1698            "CREATE SINK \"materialize\".\"public\".\"ice\" \
1699             IN CLUSTER [u42] \
1700             FROM [u1 AS \"materialize\".\"public\".\"t\"] \
1701             INTO ICEBERG CATALOG CONNECTION [u20 AS \"materialize\".\"public\".\"cat_conn\"] \
1702             (NAMESPACE 'ns', TABLE 'tbl') \
1703             USING AWS CONNECTION [u21 AS \"materialize\".\"public\".\"aws_conn\"] \
1704             MODE {mode}"
1705        )
1706    }
1707
1708    #[mz_ore::test]
1709    fn sink_kafka_bare_format_without_key() {
1710        let sql = kafka_sink_sql(None, "FORMAT JSON", "DEBEZIUM");
1711        let out = super::item_details(&sql).expect("ok");
1712        assert_eq!(
1713            out,
1714            json!({
1715                "type": "sink",
1716                "sink_type": "kafka",
1717                "cluster_id": "u42",
1718                "connection_id": "u10",
1719                "topic": "sink-topic",
1720                "envelope_type": "debezium",
1721                "format": "json",
1722                "value_format": "json",
1723            }),
1724        );
1725    }
1726
1727    #[mz_ore::test]
1728    fn sink_kafka_bare_format_with_key_derives_key_format() {
1729        // A bare format applies to the key too once the sink has a KEY, which
1730        // is what makes the deprecated `format` column collapse to `avro`.
1731        let sql = kafka_sink_sql(Some("a"), AVRO_FORMAT, "UPSERT");
1732        let out = super::item_details(&sql).expect("ok");
1733        assert_eq!(
1734            out,
1735            json!({
1736                "type": "sink",
1737                "sink_type": "kafka",
1738                "cluster_id": "u42",
1739                "connection_id": "u10",
1740                "topic": "sink-topic",
1741                "envelope_type": "upsert",
1742                "format": "avro",
1743                "key_format": "avro",
1744                "value_format": "avro",
1745            }),
1746        );
1747    }
1748
1749    #[mz_ore::test]
1750    fn sink_kafka_bare_text_format_with_key_does_not_collapse() {
1751        // Only avro/avro and json/json collapse, so a keyed text sink reports
1752        // the composite form even though both halves are `text`.
1753        let sql = kafka_sink_sql(Some("a"), "FORMAT TEXT", "UPSERT");
1754        let out = super::item_details(&sql).expect("ok");
1755        assert_eq!(out["format"], json!("key-text-value-text"));
1756        assert_eq!(out["key_format"], json!("text"));
1757        assert_eq!(out["value_format"], json!("text"));
1758    }
1759
1760    #[mz_ore::test]
1761    fn sink_kafka_key_value_json_collapses() {
1762        let sql = kafka_sink_sql(Some("a"), "KEY FORMAT JSON VALUE FORMAT JSON", "UPSERT");
1763        let out = super::item_details(&sql).expect("ok");
1764        assert_eq!(out["format"], json!("json"));
1765        assert_eq!(out["key_format"], json!("json"));
1766        assert_eq!(out["value_format"], json!("json"));
1767    }
1768
1769    #[mz_ore::test]
1770    fn sink_kafka_key_value_mixed_is_composite() {
1771        let sql = kafka_sink_sql(Some("a"), "KEY FORMAT TEXT VALUE FORMAT BYTES", "UPSERT");
1772        let out = super::item_details(&sql).expect("ok");
1773        assert_eq!(out["format"], json!("key-text-value-bytes"));
1774        assert_eq!(out["key_format"], json!("text"));
1775        assert_eq!(out["value_format"], json!("bytes"));
1776    }
1777
1778    #[mz_ore::test]
1779    fn sink_kafka_key_format_without_key_is_dropped() {
1780        // `kafka_sink_builder` ignores the key half of the format spec when the
1781        // sink has no KEY, so neither `key_format` nor the composite `format`
1782        // may reflect it.
1783        let sql = kafka_sink_sql(None, "KEY FORMAT JSON VALUE FORMAT TEXT", "DEBEZIUM");
1784        let out = super::item_details(&sql).expect("ok");
1785        assert_eq!(out["format"], json!("text"));
1786        assert_eq!(out["key_format"], serde_json::Value::Null);
1787        assert_eq!(out["value_format"], json!("text"));
1788    }
1789
1790    #[mz_ore::test]
1791    fn sink_kafka_missing_topic_errors() {
1792        let sql = "CREATE SINK \"materialize\".\"public\".\"snk\" \
1793             IN CLUSTER [u42] \
1794             FROM [u1 AS \"materialize\".\"public\".\"t\"] \
1795             INTO KAFKA CONNECTION [u10 AS \"materialize\".\"public\".\"k_conn\"] \
1796             FORMAT JSON ENVELOPE DEBEZIUM";
1797        let err = super::item_details(sql).unwrap_err();
1798        assert!(err.contains("missing TOPIC"), "wrong error message: {err}");
1799    }
1800
1801    #[mz_ore::test]
1802    fn sink_iceberg_upsert_mode() {
1803        let sql = iceberg_sink_sql("UPSERT");
1804        let out = super::item_details(&sql).expect("ok");
1805        assert_eq!(
1806            out,
1807            json!({
1808                "type": "sink",
1809                "sink_type": "iceberg",
1810                "cluster_id": "u42",
1811                // The catalog connection, never the AWS connection (u21).
1812                "connection_id": "u20",
1813                "namespace": "ns",
1814                "table": "tbl",
1815                "envelope_type": "upsert",
1816            }),
1817        );
1818    }
1819
1820    #[mz_ore::test]
1821    fn sink_iceberg_append_mode() {
1822        let sql = iceberg_sink_sql("APPEND");
1823        let out = super::item_details(&sql).expect("ok");
1824        // `append` is reachable only through an iceberg sink's MODE.
1825        assert_eq!(out["envelope_type"], json!("append"));
1826    }
1827
1828    #[mz_ore::test]
1829    fn sink_iceberg_missing_table_errors() {
1830        let sql = "CREATE SINK \"materialize\".\"public\".\"ice\" \
1831             IN CLUSTER [u42] \
1832             FROM [u1 AS \"materialize\".\"public\".\"t\"] \
1833             INTO ICEBERG CATALOG CONNECTION [u20 AS \"materialize\".\"public\".\"cat_conn\"] \
1834             (NAMESPACE 'ns') MODE UPSERT";
1835        let err = super::item_details(sql).unwrap_err();
1836        assert!(err.contains("missing TABLE"), "wrong error message: {err}");
1837    }
1838
1839    #[mz_ore::test]
1840    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1841    fn sink_arm_leaves_other_item_types_alone() {
1842        let sql = "CREATE VIEW \"materialize\".\"public\".\"v\" AS SELECT 1";
1843        let out = super::item_details(sql).expect("ok");
1844        assert_eq!(out, json!({ "type": "view", "definition": "SELECT 1;" }));
1845    }
1846
1847    // --- parse_catalog_create_sql --------------------------------------------
1848
1849    /// `type` for a `create_sql`, or the error message if parsing failed.
1850    fn item_type(sql: &str) -> Result<String, String> {
1851        match super::item_details(sql) {
1852            Ok(out) => match out {
1853                serde_json::Value::Object(mut m) => match m.remove("type") {
1854                    Some(serde_json::Value::String(s)) => Ok(s),
1855                    other => panic!("no string `type` key: {other:?}"),
1856                },
1857                other => panic!("not a JSON object: {other:?}"),
1858            },
1859            Err(msg) => Err(msg),
1860        }
1861    }
1862
1863    fn view_sql(query: &str) -> String {
1864        format!("CREATE VIEW \"materialize\".\"public\".\"v\" AS {query}")
1865    }
1866
1867    /// `definition` for a `CREATE VIEW` whose query is `query`.
1868    fn view_definition(query: &str) -> String {
1869        match super::item_details(&view_sql(query)).expect("ok") {
1870            serde_json::Value::Object(mut m) => match m.remove("definition") {
1871                Some(serde_json::Value::String(s)) => s,
1872                other => panic!("no string `definition` key: {other:?}"),
1873            },
1874            other => panic!("not a JSON object: {other:?}"),
1875        }
1876    }
1877
1878    /// `mz_tables` and `mz_views` select rows by
1879    /// `parse_catalog_create_sql(...)->>'type'`, and the function runs over
1880    /// every `Item` row in the catalog, so a statement kind that changes its
1881    /// reported type silently gains or loses rows in those relations. Pin the
1882    /// type of every kind the catalog can hold.
1883    #[mz_ore::test]
1884    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1885    fn catalog_item_type_per_statement_kind() {
1886        let cases = [
1887            (
1888                "CREATE TABLE \"materialize\".\"public\".\"t\" (a int4)",
1889                "table",
1890            ),
1891            // A table created from a source, and a webhook table, are both
1892            // `table`, so both land in mz_tables.
1893            (
1894                "CREATE TABLE \"materialize\".\"public\".\"tbl\" \
1895                 FROM SOURCE [u1 AS \"materialize\".\"public\".\"src\"] \
1896                 (REFERENCE = \"topic\") FORMAT TEXT",
1897                "table",
1898            ),
1899            (
1900                "CREATE TABLE \"materialize\".\"public\".\"wht\" FROM WEBHOOK BODY FORMAT JSON",
1901                "table",
1902            ),
1903            (
1904                "CREATE VIEW \"materialize\".\"public\".\"v\" AS SELECT 1",
1905                "view",
1906            ),
1907            (
1908                "CREATE MATERIALIZED VIEW \"materialize\".\"public\".\"mv\" \
1909                 IN CLUSTER [u1] AS SELECT 1",
1910                "materialized-view",
1911            ),
1912            (
1913                "CREATE SOURCE \"materialize\".\"public\".\"lg\" \
1914                 IN CLUSTER [u1] FROM LOAD GENERATOR COUNTER",
1915                "source",
1916            ),
1917            (
1918                "CREATE SOURCE \"materialize\".\"public\".\"wh\" \
1919                 IN CLUSTER [u1] FROM WEBHOOK BODY FORMAT JSON",
1920                "source",
1921            ),
1922            (
1923                "CREATE SUBSOURCE \"materialize\".\"public\".\"sub\" (id int4) \
1924                 OF SOURCE [u1 AS \"materialize\".\"public\".\"src\"]",
1925                "subsource",
1926            ),
1927            (
1928                "CREATE SUBSOURCE \"materialize\".\"public\".\"progress\" (id int4) \
1929                 WITH (PROGRESS)",
1930                "subsource",
1931            ),
1932            (
1933                "CREATE SINK \"materialize\".\"public\".\"snk\" IN CLUSTER [u1] \
1934                 FROM [u1 AS \"materialize\".\"public\".\"t\"] \
1935                 INTO KAFKA CONNECTION [u2 AS \"materialize\".\"public\".\"c\"] \
1936                 (TOPIC 'tp') FORMAT JSON ENVELOPE DEBEZIUM",
1937                "sink",
1938            ),
1939            (
1940                "CREATE INDEX \"i\" IN CLUSTER [u1] \
1941                 ON [u1 AS \"materialize\".\"public\".\"t\"] (\"a\")",
1942                "index",
1943            ),
1944            (
1945                "CREATE TYPE \"materialize\".\"public\".\"ty\" AS LIST (ELEMENT TYPE = int4)",
1946                "type",
1947            ),
1948            (
1949                "CREATE SECRET \"materialize\".\"public\".\"s\" AS 'x'",
1950                "secret",
1951            ),
1952            (
1953                "CREATE CONNECTION \"materialize\".\"public\".\"c\" \
1954                 TO KAFKA (BROKER 'b', SECURITY PROTOCOL PLAINTEXT)",
1955                "connection",
1956            ),
1957        ];
1958        for (sql, expected) in cases {
1959            assert_eq!(item_type(sql).as_deref(), Ok(expected), "for {sql}");
1960        }
1961    }
1962
1963    /// `mz_views.definition` is produced here. It used to be produced by
1964    /// `pack_view_update` in the adapter, so the exact rendering is a
1965    /// compatibility surface: `pg_views.definition` reads it.
1966    #[mz_ore::test]
1967    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
1968    fn catalog_view_definition() {
1969        // Identifiers and function names come back fully quoted, literals
1970        // untouched, and PostgreSQL's trailing semicolon is appended.
1971        assert_eq!(view_definition("SELECT 1"), "SELECT 1;");
1972        assert_eq!(
1973            view_definition("WITH c AS (SELECT 1 AS a) SELECT a FROM c"),
1974            "WITH \"c\" AS (SELECT 1 AS \"a\") SELECT \"a\" FROM \"c\";"
1975        );
1976        assert_eq!(
1977            view_definition("SELECT 1 UNION ALL SELECT 2"),
1978            "SELECT 1 UNION ALL SELECT 2;"
1979        );
1980        assert_eq!(
1981            view_definition("SELECT (SELECT max(a) FROM [u1 AS \"materialize\".\"public\".\"t\"])"),
1982            "SELECT (SELECT \"max\"(\"a\") FROM [u1 AS \"materialize\".\"public\".\"t\"]);"
1983        );
1984        // Identifiers needing quotes, an embedded double quote, non-ASCII, an
1985        // embedded single quote in a literal, and ORDER BY all survive.
1986        assert_eq!(
1987            view_definition(
1988                "SELECT \"a b\", \"héllo\", \"q\"\"x\" \
1989                 FROM [u1 AS \"materialize\".\"public\".\"t\"] \
1990                 WHERE s = 'lit''eral' AND n = 42 ORDER BY 1"
1991            ),
1992            "SELECT \"a b\", \"héllo\", \"q\"\"x\" \
1993             FROM [u1 AS \"materialize\".\"public\".\"t\"] \
1994             WHERE \"s\" = 'lit''eral' AND \"n\" = 42 ORDER BY 1;"
1995        );
1996    }
1997
1998    /// The rendering must be a fixed point: `pg_views` consumers re-issue
1999    /// `definition` as the body of a new view, so a second pass through the
2000    /// parser has to produce the identical string. The trailing `;` is part of
2001    /// what gets re-parsed.
2002    #[mz_ore::test]
2003    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2004    fn catalog_view_definition_is_idempotent() {
2005        for query in [
2006            "SELECT 1",
2007            "WITH c AS (SELECT 1 AS a) SELECT a FROM c",
2008            "SELECT 1 UNION ALL SELECT 2",
2009            "SELECT \"a b\", \"q\"\"x\" FROM [u1 AS \"materialize\".\"public\".\"t\"] \
2010             WHERE s = 'lit''eral' ORDER BY 1",
2011        ] {
2012            let once = view_definition(query);
2013            assert_eq!(
2014                view_definition(&once),
2015                once,
2016                "not a fixed point for {query}"
2017            );
2018        }
2019    }
2020
2021    /// `mz_tables.source_id` comes from this key. A table with no source must
2022    /// omit it entirely, so the MV's `->>'source_id'` yields SQL NULL.
2023    #[mz_ore::test]
2024    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2025    fn catalog_table_source_id() {
2026        let from_source = super::item_details(
2027            "CREATE TABLE \"materialize\".\"public\".\"tbl\" \
2028                 FROM SOURCE [u1 AS \"materialize\".\"public\".\"src\"] \
2029                 (REFERENCE = \"topic\") FORMAT TEXT",
2030        )
2031        .expect("ok");
2032        assert_eq!(from_source, json!({ "type": "table", "source_id": "u1" }));
2033
2034        let plain = super::item_details("CREATE TABLE \"materialize\".\"public\".\"t\" (a int4)")
2035            .expect("ok");
2036        assert_eq!(plain, json!({ "type": "table", "column_defaults": [null] }));
2037
2038        let webhook = super::item_details(
2039            "CREATE TABLE \"materialize\".\"public\".\"wht\" FROM WEBHOOK BODY FORMAT JSON",
2040        )
2041        .expect("ok");
2042        assert_eq!(webhook, json!({ "type": "table" }));
2043    }
2044
2045    #[mz_ore::test]
2046    fn item_details_reports_column_defaults() {
2047        let sql = r#"CREATE TABLE "materialize"."public"."t" ("a" [s20 AS "pg_catalog"."int4"] DEFAULT 1 + 1, "b" [s46 AS "pg_catalog"."text"] NOT NULL, "c" [s46 AS "pg_catalog"."text"] VERSION ADDED 1)"#;
2048        let out = super::item_details(sql).expect("ok");
2049        assert_eq!(out["column_defaults"], json!(["1 + 1", null, null]));
2050
2051        // A bare NULL literal is no default, a cast of one is an expression.
2052        let sql = r#"CREATE TABLE "materialize"."public"."t" ("a" [s46 AS "pg_catalog"."text"] DEFAULT NULL, "b" [s46 AS "pg_catalog"."text"] DEFAULT (NULL), "c" [s46 AS "pg_catalog"."text"] DEFAULT NULL::[s46 AS "pg_catalog"."text"])"#;
2053        let out = super::item_details(sql).expect("ok");
2054        assert_eq!(
2055            out["column_defaults"],
2056            json!([null, null, "NULL::[s46 AS \"pg_catalog\".\"text\"]"])
2057        );
2058
2059        // The last of several defaults applies, even when it is a bare NULL.
2060        let sql = r#"CREATE TABLE "materialize"."public"."t" ("a" [s20 AS "pg_catalog"."int4"] DEFAULT 1 DEFAULT 2, "b" [s20 AS "pg_catalog"."int4"] DEFAULT 5 DEFAULT NULL)"#;
2061        let out = super::item_details(sql).expect("ok");
2062        assert_eq!(out["column_defaults"], json!(["2", null]));
2063
2064        let sql =
2065            r#"CREATE TABLE "t" FROM SOURCE [u1 AS "materialize"."public"."s"] (REFERENCE = "t")"#;
2066        let out = super::item_details(sql).expect("ok");
2067        assert_eq!(out["column_defaults"], json!(null));
2068    }
2069
2070    #[mz_ore::test]
2071    fn item_details_packs_as_jsonb_for_any_column_name() {
2072        let sql = r#"CREATE TABLE "materialize"."public"."t" ("$serde_json::private::Number" [s20 AS "pg_catalog"."int4"] DEFAULT 5, "b" [s46 AS "pg_catalog"."text"])"#;
2073        let out = super::item_details(sql).expect("ok");
2074        assert_eq!(out["column_defaults"], json!(["5", null]));
2075        mz_repr::adt::jsonb::Jsonb::from_serde_json(out).expect("packs as jsonb");
2076    }
2077
2078    #[mz_ore::test]
2079    fn item_details_reports_index_key_parts() {
2080        let sql = r#"CREATE INDEX "t_idx" IN CLUSTER [u1] ON [u4 AS "materialize"."public"."t"] ("pg_catalog"."abs"("a"), "a" + 1, COALESCE("a", 0), 2)"#;
2081        let out = super::item_details(sql).expect("ok");
2082        assert_eq!(
2083            out["key_parts"],
2084            json!(["pg_catalog.abs(a)", "a + 1", "COALESCE(a, 0)", "2"])
2085        );
2086    }
2087
2088    /// Every error here is fatal to the whole of `mz_tables`/`mz_views`, not to
2089    /// one row: the MVs call this function inside their `WHERE` clause, so an
2090    /// item the parser rejects makes the relation unreadable for everyone.
2091    #[mz_ore::test]
2092    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2093    fn catalog_create_sql_errors() {
2094        assert_eq!(
2095            item_type("this is not sql"),
2096            Err(
2097                "failed to parse create_sql: Expected a keyword at the beginning of a statement, \
2098                 found identifier \"this\""
2099                    .to_string()
2100            )
2101        );
2102        assert_eq!(
2103            item_type("CREATE TABLE t (a int4); CREATE TABLE u (b int4)"),
2104            Err("expected a single statement, found 2".to_string())
2105        );
2106        // A statement that is not a CREATE of a catalog item, e.g. if a future
2107        // change persists something else in an Item record.
2108        assert_eq!(
2109            item_type("SELECT 1"),
2110            Err("not a CREATE item statement".to_string())
2111        );
2112        // Catalog `create_sql` always names items by id. An unresolved name
2113        // means the record was written wrong.
2114        assert_eq!(
2115            item_type(
2116                "CREATE TABLE \"materialize\".\"public\".\"tbl\" \
2117                 FROM SOURCE src (REFERENCE = \"topic\")"
2118            ),
2119            Err("unresolved item name".to_string())
2120        );
2121    }
2122
2123    // --- parse_catalog_item_references ----------------------------------------
2124
2125    #[mz_ore::test]
2126    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2127    fn item_references_view() {
2128        let sql = "CREATE VIEW \"materialize\".\"public\".\"v\" AS \
2129             SELECT \"pg_catalog\".\"abs\"(\"a\"::[s20 AS \"pg_catalog\".\"int4\"]) \
2130             FROM [u1 AS \"materialize\".\"public\".\"t\"]";
2131        let out = super::item_references(sql).expect("ok");
2132        assert_eq!(
2133            out,
2134            json!({
2135                "ids": ["s20", "u1"],
2136                "named_funcs": [{"schema": "pg_catalog", "name": "abs"}],
2137                "named_types": [],
2138                "named_relations": [],
2139            })
2140        );
2141    }
2142
2143    #[mz_ore::test]
2144    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2145    fn item_references_connection() {
2146        let sql = "CREATE CONNECTION \"materialize\".\"public\".\"kc\" TO KAFKA (\
2147             BROKER 'kafka:9092', \
2148             SSH TUNNEL [u5 AS \"materialize\".\"public\".\"ssh\"], \
2149             SASL PASSWORD = SECRET [u7 AS \"materialize\".\"public\".\"pw\"])";
2150        let out = super::item_references(sql).expect("ok");
2151        assert_eq!(out["ids"], json!(["u5", "u7"]));
2152        assert_eq!(out["named_funcs"], json!([]));
2153    }
2154
2155    #[mz_ore::test]
2156    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2157    fn item_references_cte_shadowing() {
2158        let sql = "CREATE VIEW \"materialize\".\"public\".\"v\" AS \
2159             WITH \"c\" AS (SELECT * FROM [u1 AS \"materialize\".\"public\".\"t\"]) \
2160             SELECT * FROM \"c\"";
2161        let out = super::item_references(sql).expect("ok");
2162        assert_eq!(out["ids"], json!(["u1"]));
2163        assert_eq!(out["named_relations"], json!([]));
2164    }
2165
2166    #[mz_ore::test]
2167    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
2168    fn item_references_name_based_relation_surfaces() {
2169        // Stored SQL always prints relations as id references. A name-based
2170        // relation must surface in "named_relations" rather than vanish.
2171        let sql = "CREATE VIEW \"materialize\".\"public\".\"v\" AS \
2172             SELECT * FROM \"mz_catalog\".\"mz_tables\"";
2173        let out = super::item_references(sql).expect("ok");
2174        assert_eq!(
2175            out["named_relations"],
2176            json!([{"schema": "mz_catalog", "name": "mz_tables"}])
2177        );
2178    }
2179
2180    #[mz_ore::test]
2181    fn item_references_parse_error() {
2182        let err = super::item_references("NOT SQL").unwrap_err();
2183        assert!(
2184            err.contains("failed to parse"),
2185            "wrong error message: {err}"
2186        );
2187    }
2188
2189    #[mz_ore::test]
2190    fn catalog_retain_history_absent_is_omitted() {
2191        let sql = "CREATE TABLE \"materialize\".\"public\".\"t\" (\"a\" pg_catalog.int4)";
2192        let out = super::item_details(sql).expect("ok");
2193        assert_eq!(out.get("retain_history_millis"), None);
2194    }
2195
2196    #[mz_ore::test]
2197    fn catalog_retain_history_spellings() {
2198        // A string or a bare number parses as an interval, the number as seconds, and an
2199        // interval literal applies its range qualifier.
2200        for (option, millis) in [
2201            ("'1h'", 3_600_000u64),
2202            ("90", 90_000),
2203            ("INTERVAL '2' DAY", 172_800_000),
2204            ("INTERVAL '1:30' MINUTE TO SECOND", 90_000),
2205        ] {
2206            let sql = format!(
2207                "CREATE TABLE \"materialize\".\"public\".\"t\" (\"a\" pg_catalog.int4) \
2208                 WITH (RETAIN HISTORY = FOR {option})"
2209            );
2210            let out = super::item_details(&sql).expect("ok");
2211            assert_eq!(out["retain_history_millis"], json!(millis), "{option}");
2212        }
2213    }
2214
2215    #[mz_ore::test]
2216    fn catalog_retain_history_zero_disables_compaction() {
2217        for option in ["'0'", "0", "NULL"] {
2218            let sql = format!(
2219                "CREATE TABLE \"materialize\".\"public\".\"t\" (\"a\" pg_catalog.int4) \
2220                 WITH (RETAIN HISTORY = FOR {option})"
2221            );
2222            let out = super::item_details(&sql).expect("ok");
2223            assert_eq!(out["retain_history_millis"], json!(u64::MAX), "{option}");
2224        }
2225    }
2226
2227    #[mz_ore::test]
2228    fn catalog_retain_history_on_each_item_kind() {
2229        let cases = [
2230            (
2231                "CREATE SOURCE \"materialize\".\"public\".\"s\" IN CLUSTER [u1] \
2232                 FROM LOAD GENERATOR COUNTER WITH (RETAIN HISTORY = FOR '2h')",
2233                7_200_000u64,
2234            ),
2235            (
2236                "CREATE INDEX \"t_idx\" IN CLUSTER [u1] \
2237                 ON [u2 AS \"materialize\".\"public\".\"t\"] (\"a\") \
2238                 WITH (RETAIN HISTORY = FOR '3h')",
2239                10_800_000,
2240            ),
2241            (
2242                "CREATE MATERIALIZED VIEW \"materialize\".\"public\".\"mv\" IN CLUSTER [u1] \
2243                 WITH (RETAIN HISTORY = FOR '4h', REFRESH = ON COMMIT) AS SELECT 1",
2244                14_400_000,
2245            ),
2246            (
2247                "CREATE SUBSOURCE \"materialize\".\"public\".\"sub\" (id int4) \
2248                 OF SOURCE [u1 AS \"materialize\".\"public\".\"src\"] \
2249                 WITH (EXTERNAL REFERENCE = \"db\".\"public\".\"t\", RETAIN HISTORY = FOR '5h')",
2250                18_000_000,
2251            ),
2252            (
2253                "CREATE TABLE \"materialize\".\"public\".\"tbl\" \
2254                 FROM SOURCE [u1 AS \"materialize\".\"public\".\"src\"] \
2255                 (REFERENCE = \"db\".\"public\".\"t\") WITH (RETAIN HISTORY = FOR '6h')",
2256                21_600_000,
2257            ),
2258        ];
2259        for (sql, millis) in cases {
2260            let out = super::item_details(sql).expect("ok");
2261            assert_eq!(out["retain_history_millis"], json!(millis), "{sql}");
2262        }
2263    }
2264
2265    const MZ_TIMESTAMP: &str = "[s1 AS \"mz_catalog\".\"mz_timestamp\"]";
2266
2267    #[mz_ore::test]
2268    fn catalog_refresh_omitted_means_on_commit() {
2269        let sql = "CREATE MATERIALIZED VIEW \"materialize\".\"public\".\"mv\" IN CLUSTER [u1] \
2270                   AS SELECT 1";
2271        let out = super::item_details(sql).expect("ok");
2272        assert_eq!(out["refresh"], json!([{"type": "on-commit"}]));
2273    }
2274
2275    #[mz_ore::test]
2276    fn catalog_refresh_one_entry_per_option() {
2277        let sql = format!(
2278            "CREATE MATERIALIZED VIEW \"materialize\".\"public\".\"mv\" IN CLUSTER [u1] \
2279             WITH (REFRESH = ON COMMIT, \
2280             REFRESH = AT 32472144000000::{MZ_TIMESTAMP}, \
2281             REFRESH = EVERY '1 day' ALIGNED TO 946684800000::{MZ_TIMESTAMP}, \
2282             REFRESH = EVERY '90 minutes' ALIGNED TO '2000-01-01 00:00:00+00') \
2283             AS SELECT 1"
2284        );
2285        let out = super::item_details(&sql).expect("ok");
2286        assert_eq!(
2287            out["refresh"],
2288            json!([
2289                {"type": "on-commit"},
2290                {"type": "at", "at": format!("32472144000000::{MZ_TIMESTAMP}")},
2291                {
2292                    "type": "every",
2293                    "interval": "24:00:00",
2294                    "aligned_to": format!("946684800000::{MZ_TIMESTAMP}"),
2295                },
2296                {
2297                    "type": "every",
2298                    "interval": "01:30:00",
2299                    "aligned_to": "'2000-01-01 00:00:00+00'",
2300                },
2301            ])
2302        );
2303    }
2304
2305    #[mz_ore::test]
2306    fn catalog_refresh_times_read_as_written() {
2307        let sql = format!(
2308            "CREATE MATERIALIZED VIEW \"materialize\".\"public\".\"mv\" IN CLUSTER [u1] \
2309             WITH (REFRESH = AT ((1790696789484::{MZ_TIMESTAMP})), \
2310             REFRESH = AT 946684800000::{MZ_TIMESTAMP}::[s46 AS \"pg_catalog\".\"text\"]::[s22 AS \"pg_catalog\".\"int8\"] + 2000, \
2311             REFRESH = EVERY '1 day' ALIGNED TO '2000-01-01 00:00:00+00'::[s52 AS \"pg_catalog\".\"timestamptz\"] + INTERVAL '1 hour') \
2312             AS SELECT 1"
2313        );
2314        let out = super::item_details(&sql).expect("ok");
2315        assert_eq!(
2316            out["refresh"],
2317            json!([
2318                {"type": "at", "at": format!("((1790696789484::{MZ_TIMESTAMP}))")},
2319                {
2320                    "type": "at",
2321                    "at": format!(
2322                        "946684800000::{MZ_TIMESTAMP}::[s46 AS \"pg_catalog\".\"text\"]::[s22 AS \"pg_catalog\".\"int8\"] + 2000"
2323                    ),
2324                },
2325                {
2326                    "type": "every",
2327                    "interval": "24:00:00",
2328                    "aligned_to": "'2000-01-01 00:00:00+00'::[s52 AS \"pg_catalog\".\"timestamptz\"] + INTERVAL '1 hour'",
2329                },
2330            ])
2331        );
2332    }
2333
2334    #[mz_ore::test]
2335    fn catalog_replacement_target() {
2336        let mv_sql_without_replacement = "CREATE MATERIALIZED VIEW \"materialize\".\"public\".\"mv\" IN CLUSTER [u1] \
2337             AS SELECT 1";
2338        let out = super::item_details(mv_sql_without_replacement).expect("ok");
2339        assert_eq!(out.get("replacement_target"), None);
2340
2341        let mv_sql_with_replacement = "CREATE REPLACEMENT MATERIALIZED VIEW \"materialize\".\"public\".\"rp\" \
2342                   FOR [u7 AS \"materialize\".\"public\".\"mv\"] IN CLUSTER [u1] \
2343                   WITH (REFRESH = ON COMMIT) AS SELECT 1";
2344        let out = super::item_details(mv_sql_with_replacement).expect("ok");
2345        assert_eq!(out["replacement_target"], json!("u7"));
2346    }
2347}