Skip to main content

mz_catalog/builtin/
mz_internal.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//! Built-in catalog items for the `mz_internal` schema.
11
12use std::collections::BTreeMap;
13use std::sync::LazyLock;
14use std::time::Duration;
15
16use mz_adapter_types::compaction::CompactionWindow;
17use mz_pgrepr::oid;
18use mz_repr::adt::mz_acl_item::MzAclItem;
19use mz_repr::namespaces::MZ_INTERNAL_SCHEMA;
20use mz_repr::{RelationDesc, SemanticType, SqlScalarType};
21use mz_sql::catalog::{ObjectType, SystemObjectType};
22use mz_sql::rbac;
23use mz_sql::session::user::{MZ_ANALYTICS_ROLE_ID, MZ_SYSTEM_ROLE_ID};
24use mz_sql::session::vars::METRICS_RETENTION;
25use mz_storage_client::controller::IntrospectionType;
26use mz_storage_client::healthcheck::{
27    MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC, MZ_PREPARED_STATEMENT_HISTORY_DESC,
28    MZ_SESSION_HISTORY_DESC, MZ_SINK_STATUS_HISTORY_DESC, MZ_SOURCE_STATUS_HISTORY_DESC,
29    MZ_SQL_TEXT_DESC, MZ_STATEMENT_EXECUTION_HISTORY_DESC, REPLICA_METRICS_HISTORY_DESC,
30    REPLICA_STATUS_HISTORY_DESC, WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC,
31    WALLCLOCK_LAG_HISTORY_DESC,
32};
33use mz_storage_client::statistics::{MZ_SINK_STATISTICS_RAW_DESC, MZ_SOURCE_STATISTICS_RAW_DESC};
34
35use crate::memory::objects::DataSourceDesc;
36
37use super::{
38    ANALYTICS_SELECT, BuiltinConnection, BuiltinIndex, BuiltinMaterializedView, BuiltinSource,
39    BuiltinTable, BuiltinView, Cardinality, LinkProperties, MONITOR_REDACTED_SELECT,
40    MONITOR_SELECT, Ontology, OntologyLink, PUBLIC_SELECT, RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL,
41    SUPPORT_SELECT,
42};
43
44// TODO(SQL-932): every builtin relation but `mz_catalog_state` and the audit
45// log should stop reading this source and read `mz_catalog_state` instead.
46pub static MZ_CATALOG_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
47    name: "mz_catalog_raw",
48    schema: MZ_INTERNAL_SCHEMA,
49    oid: oid::SOURCE_MZ_CATALOG_RAW_OID,
50    data_source: DataSourceDesc::Catalog,
51    desc: crate::durable::persist_desc(),
52    column_comments: BTreeMap::new(),
53    is_retained_metrics_object: false,
54    // The raw catalog contains unredacted SQL statements, so we limit access to the system user.
55    access: vec![],
56    ontology: None,
57});
58
59/// Every catalog record but the audit log, with its kind as a column.
60///
61/// The audit log is append-only, so a relation reading `mz_catalog_raw` decodes
62/// the whole audit log at hydration. To optimize on hydration time,
63/// catalog relations read this copy instead and filter on `kind`.
64pub static MZ_CATALOG_STATE: LazyLock<BuiltinMaterializedView> =
65    LazyLock::new(|| BuiltinMaterializedView {
66        name: "mz_catalog_state",
67        schema: MZ_INTERNAL_SCHEMA,
68        oid: oid::MV_MZ_CATALOG_STATE_OID,
69        desc: RelationDesc::builder()
70            .with_column("kind", SqlScalarType::String.nullable(false))
71            .with_column("data", SqlScalarType::Jsonb.nullable(false))
72            .finish(),
73        column_comments: BTreeMap::new(),
74        sql: "
75IN CLUSTER mz_catalog_server
76WITH (ASSERT NOT NULL kind) AS
77SELECT data->>'kind' AS kind, data
78FROM mz_internal.mz_catalog_raw
79WHERE data->>'kind' <> 'AuditLog'",
80        is_retained_metrics_object: false,
81        access: vec![],
82        ontology: None,
83    });
84/// Every catalog item that has an `Item` record: user items, including temporary ones, and
85/// runtime-alterable builtins such as `mz_internal.mz_analytics`.
86/// This is an intermediate layer, intended to be used by
87/// downstream builtin item relations (e.g. mz_sources). Without it,
88/// they would need to parse DDL statements of all items in the durable catalog
89/// then filter down to their specific object type.
90///
91/// A temporary item has its owning session in `ephemeral_owner_session`, and its
92/// `schema_id` is the placeholder `u0`.
93///
94/// A `create_sql` that fails to decode errors this relation and every reader. Once SQL-795
95/// is implemented, per-row errors can be raised in readers through `mz_unsafe.mz_error_if_null`.
96pub static MZ_CATALOG_ITEMS: LazyLock<BuiltinMaterializedView> =
97    LazyLock::new(|| BuiltinMaterializedView {
98        name: "mz_catalog_items",
99        schema: MZ_INTERNAL_SCHEMA,
100        oid: oid::MV_MZ_CATALOG_ITEMS_OID,
101        desc: RelationDesc::builder()
102            .with_column("id", SqlScalarType::String.nullable(false))
103            .with_column("global_id", SqlScalarType::String.nullable(false))
104            .with_column("oid", SqlScalarType::Oid.nullable(false))
105            .with_column("schema_id", SqlScalarType::String.nullable(false))
106            .with_column("name", SqlScalarType::String.nullable(false))
107            .with_column("owner_id", SqlScalarType::String.nullable(false))
108            .with_column(
109                "privileges",
110                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
111            )
112            .with_column(
113                "ephemeral_owner_session",
114                SqlScalarType::Uuid.nullable(true),
115            )
116            .with_column("type", SqlScalarType::String.nullable(false))
117            .with_column("create_sql", SqlScalarType::String.nullable(false))
118            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
119            .with_column("details", SqlScalarType::Jsonb.nullable(false))
120            .finish(),
121        column_comments: BTreeMap::new(),
122        sql: "
123IN CLUSTER mz_catalog_server
124WITH (
125    ASSERT NOT NULL id,
126    ASSERT NOT NULL global_id,
127    ASSERT NOT NULL oid,
128    ASSERT NOT NULL schema_id,
129    ASSERT NOT NULL name,
130    ASSERT NOT NULL owner_id,
131    ASSERT NOT NULL privileges,
132    ASSERT NOT NULL type,
133    ASSERT NOT NULL create_sql,
134    ASSERT NOT NULL redacted_create_sql,
135    ASSERT NOT NULL details
136) AS
137WITH
138    items AS (
139        SELECT
140            mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
141            mz_internal.parse_catalog_id(data->'value'->'global_id') AS global_id,
142            (data->'value'->>'oid')::oid AS oid,
143            mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,
144            data->'value'->>'name' AS name,
145            mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
146            mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
147            (data->'value'->>'ephemeral_owner_session')::uuid AS ephemeral_owner_session,
148            data->'value'->'definition'->'V1'->>'create_sql' AS create_sql
149        FROM mz_internal.mz_catalog_state
150        WHERE kind = 'Item'
151    ),
152    decoded AS (
153        SELECT
154            items.*,
155            mz_internal.parse_catalog_create_sql(create_sql) AS details
156        FROM items
157    )
158SELECT
159    id,
160    global_id,
161    oid,
162    schema_id,
163    name,
164    owner_id,
165    privileges,
166    ephemeral_owner_session,
167    details->>'type' AS type,
168    create_sql,
169    mz_internal.redact_sql(create_sql) AS redacted_create_sql,
170    details
171FROM decoded",
172        is_retained_metrics_object: false,
173        access: vec![],
174        ontology: None,
175    });
176
177/// `mz_catalog_items` without the statement text such that the index holds
178/// no DDL text.
179pub static MZ_CATALOG_ITEM_METADATA: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
180    name: "mz_catalog_item_metadata",
181    schema: MZ_INTERNAL_SCHEMA,
182    oid: oid::VIEW_MZ_CATALOG_ITEM_METADATA_OID,
183    desc: RelationDesc::builder()
184        .with_column("id", SqlScalarType::String.nullable(false))
185        .with_column("global_id", SqlScalarType::String.nullable(false))
186        .with_column("oid", SqlScalarType::Oid.nullable(false))
187        .with_column("schema_id", SqlScalarType::String.nullable(false))
188        .with_column("name", SqlScalarType::String.nullable(false))
189        .with_column("owner_id", SqlScalarType::String.nullable(false))
190        .with_column(
191            "privileges",
192            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
193        )
194        .with_column(
195            "ephemeral_owner_session",
196            SqlScalarType::Uuid.nullable(true),
197        )
198        .with_column("type", SqlScalarType::String.nullable(false))
199        .with_column("details", SqlScalarType::Jsonb.nullable(true))
200        .finish(),
201    column_comments: BTreeMap::new(),
202    sql: "
203SELECT
204    id,
205    global_id,
206    oid,
207    schema_id,
208    name,
209    owner_id,
210    privileges,
211    ephemeral_owner_session,
212    type,
213    details - 'definition' AS details
214FROM mz_internal.mz_catalog_items",
215    access: vec![],
216    ontology: None,
217});
218
219pub const MZ_CATALOG_ITEM_METADATA_IND: BuiltinIndex = BuiltinIndex {
220    name: "mz_catalog_item_metadata_ind",
221    schema: MZ_INTERNAL_SCHEMA,
222    oid: oid::INDEX_MZ_CATALOG_ITEM_METADATA_IND_OID,
223    sql: "IN CLUSTER mz_catalog_server
224ON mz_internal.mz_catalog_item_metadata (id)",
225    is_retained_metrics_object: false,
226};
227
228/// The catalog ids of builtin objects.
229///
230/// Builtin objects' ids come from their `GidMapping` records in the catalog.
231pub static MZ_BUILTIN_OBJECT_MAPPINGS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
232    name: "mz_builtin_object_mappings",
233    schema: MZ_INTERNAL_SCHEMA,
234    oid: oid::VIEW_MZ_BUILTIN_OBJECT_MAPPINGS_OID,
235    desc: RelationDesc::builder()
236        .with_column("schema_name", SqlScalarType::String.nullable(false))
237        .with_column("name", SqlScalarType::String.nullable(false))
238        .with_column("object_type", SqlScalarType::String.nullable(false))
239        .with_column("id", SqlScalarType::String.nullable(false))
240        .with_column("global_id", SqlScalarType::String.nullable(false))
241        .finish(),
242    column_comments: BTreeMap::new(),
243    // Although these values should never be nullable, JSONB lookup
244    // types are inferred as nullable. Thus we coalesce to infer as
245    // non-nullable.
246    //
247    // We exclude runtime-alterable builtins to avoid duplicate entries when
248    // unioning this view with item records in the durable catalog.
249    sql: Box::leak(
250        format!(
251            "
252SELECT
253    COALESCE(data->'key'->>'schema_name', '') AS schema_name,
254    COALESCE(data->'key'->>'object_name', '') AS name,
255    COALESCE(data->'key'->>'object_type', '') AS object_type,
256    COALESCE('s' || (data->'value'->>'catalog_id'), '') AS id,
257    COALESCE('s' || (data->'value'->>'global_id'), '') AS global_id
258FROM mz_internal.mz_catalog_state
259WHERE
260    kind = 'GidMapping' AND
261    data->'value'->>'fingerprint' <> '{RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL}'"
262        )
263        .into_boxed_str(),
264    ),
265    access: vec![],
266    ontology: None,
267});
268
269pub const MZ_BUILTIN_OBJECT_MAPPINGS_IND: BuiltinIndex = BuiltinIndex {
270    name: "mz_builtin_object_mappings_ind",
271    schema: MZ_INTERNAL_SCHEMA,
272    oid: oid::INDEX_MZ_BUILTIN_OBJECT_MAPPINGS_IND_OID,
273    sql: "IN CLUSTER mz_catalog_server
274ON mz_internal.mz_builtin_object_mappings (schema_name, name)",
275    is_retained_metrics_object: false,
276};
277
278pub static MZ_POSTGRES_SOURCES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
279    BuiltinMaterializedView {
280        name: "mz_postgres_sources",
281        schema: MZ_INTERNAL_SCHEMA,
282        oid: oid::MV_MZ_POSTGRES_SOURCES_OID,
283        desc: RelationDesc::builder()
284            .with_column("id", SqlScalarType::String.nullable(false))
285            .with_column("replication_slot", SqlScalarType::String.nullable(false))
286            .with_column("timeline_id", SqlScalarType::UInt64.nullable(true))
287            .with_key(vec![0])
288            .finish(),
289        column_comments: BTreeMap::from_iter([
290            (
291                "id",
292                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
293            ),
294            (
295                "replication_slot",
296                "The name of the replication slot in the PostgreSQL database that Materialize will create and stream data from.",
297            ),
298            (
299                "timeline_id",
300                "The PostgreSQL timeline ID determined on source creation.",
301            ),
302        ]),
303        // `parse_postgres_source_details` extracts `slot` and `timeline_id`
304        // from the hex-encoded protobuf `DETAILS` option on the persisted
305        // `CREATE SOURCE`. Any row where that decode fails poisons the whole
306        // MV, so this MV MUST be filtered to postgres sources first via
307        // `parse_catalog_create_sql`.
308        sql: "
309IN CLUSTER mz_catalog_server
310WITH (
311    ASSERT NOT NULL id,
312    ASSERT NOT NULL replication_slot
313) AS
314SELECT
315    mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
316    details->>'slot' AS replication_slot,
317    (details->>'timeline_id')::uint8 AS timeline_id
318FROM
319    mz_internal.mz_catalog_raw,
320    LATERAL (
321        SELECT mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')
322    ) AS l(parsed),
323    LATERAL (
324        SELECT mz_internal.parse_postgres_source_details(data->'value'->'definition'->'V1'->>'create_sql')
325    ) AS d(details)
326WHERE
327    data->>'kind' = 'Item' AND
328    parsed->>'source_type' = 'postgres'",
329        is_retained_metrics_object: false,
330        access: vec![PUBLIC_SELECT],
331        ontology: Some(Ontology {
332            entity_name: "postgres_source",
333            description: "Postgres source-level details",
334            links: &const {
335                [OntologyLink {
336                    name: "details_of",
337                    target: "source",
338                    properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
339                }]
340            },
341            column_semantic_types: &[("id", SemanticType::CatalogItemId)],
342        }),
343    }
344});
345// The three relational source-table views (postgres, mysql, sql-server) share
346// the same shape. Each reads Item rows from `mz_catalog_raw`, pulls the parent
347// source id and external reference out of the persisted `create_sql` via
348// `parse_source_export_details`, and joins `mz_sources` to keep only exports
349// whose parent is of the matching connection type. The external reference for
350// postgres and sql-server is `[database, schema, table]`, so schema/table come
351// from positions 1 and 2. MySQL references are `[schema, table]`, so positions
352// 0 and 1. This is the same slicing the removed packers applied.
353pub static MZ_POSTGRES_SOURCE_TABLES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
354    BuiltinMaterializedView {
355        name: "mz_postgres_source_tables",
356        schema: MZ_INTERNAL_SCHEMA,
357        oid: oid::MV_MZ_POSTGRES_SOURCE_TABLES_OID,
358        desc: RelationDesc::builder()
359            .with_column("id", SqlScalarType::String.nullable(false))
360            .with_column("schema_name", SqlScalarType::String.nullable(false))
361            .with_column("table_name", SqlScalarType::String.nullable(false))
362            .with_key(vec![0])
363            .finish(),
364        column_comments: BTreeMap::from_iter([
365            (
366                "id",
367                "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
368            ),
369            (
370                "schema_name",
371                "The schema of the upstream table being ingested.",
372            ),
373            (
374                "table_name",
375                "The name of the upstream table being ingested.",
376            ),
377        ]),
378        sql: "
379IN CLUSTER mz_catalog_server
380WITH (
381    ASSERT NOT NULL id,
382    ASSERT NOT NULL schema_name,
383    ASSERT NOT NULL table_name
384) AS
385SELECT
386    mz_internal.parse_catalog_id(r.data->'key'->'gid') AS id,
387    details->'external_reference'->>1 AS schema_name,
388    details->'external_reference'->>2 AS table_name
389FROM
390    mz_internal.mz_catalog_raw r,
391    LATERAL (
392        SELECT mz_internal.parse_source_export_details(
393            r.data->'value'->'definition'->'V1'->>'create_sql')
394    ) AS d(details)
395    JOIN mz_catalog.mz_sources s
396        ON s.id = details->>'source_id' AND s.type = 'postgres'
397WHERE
398    r.data->>'kind' = 'Item' AND
399    details IS NOT NULL",
400        is_retained_metrics_object: true,
401        access: vec![PUBLIC_SELECT],
402        ontology: Some(Ontology {
403            entity_name: "postgres_source_table",
404            description: "Postgres source table-level details",
405            links: &const {
406                [OntologyLink {
407                    name: "describes_source_table",
408                    target: "table",
409                    properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
410                }]
411            },
412            column_semantic_types: &[("id", SemanticType::CatalogItemId)],
413        }),
414    }
415});
416pub static MZ_MYSQL_SOURCE_TABLES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
417    BuiltinMaterializedView {
418        name: "mz_mysql_source_tables",
419        schema: MZ_INTERNAL_SCHEMA,
420        oid: oid::MV_MZ_MYSQL_SOURCE_TABLES_OID,
421        desc: RelationDesc::builder()
422            .with_column("id", SqlScalarType::String.nullable(false))
423            .with_column("schema_name", SqlScalarType::String.nullable(false))
424            .with_column("table_name", SqlScalarType::String.nullable(false))
425            .with_key(vec![0])
426            .finish(),
427        column_comments: BTreeMap::from_iter([
428            (
429                "id",
430                "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
431            ),
432            (
433                "schema_name",
434                "The schema (or, database) of the upstream table being ingested.",
435            ),
436            (
437                "table_name",
438                "The name of the upstream table being ingested.",
439            ),
440        ]),
441        sql: "
442IN CLUSTER mz_catalog_server
443WITH (
444    ASSERT NOT NULL id,
445    ASSERT NOT NULL schema_name,
446    ASSERT NOT NULL table_name
447) AS
448SELECT
449    mz_internal.parse_catalog_id(r.data->'key'->'gid') AS id,
450    details->'external_reference'->>0 AS schema_name,
451    details->'external_reference'->>1 AS table_name
452FROM
453    mz_internal.mz_catalog_raw r,
454    LATERAL (
455        SELECT mz_internal.parse_source_export_details(
456            r.data->'value'->'definition'->'V1'->>'create_sql')
457    ) AS d(details)
458    JOIN mz_catalog.mz_sources s
459        ON s.id = details->>'source_id' AND s.type = 'mysql'
460WHERE
461    r.data->>'kind' = 'Item' AND
462    details IS NOT NULL",
463        is_retained_metrics_object: true,
464        access: vec![PUBLIC_SELECT],
465        ontology: Some(Ontology {
466            entity_name: "mysql_source_table",
467            description: "MySQL source table-level details",
468            links: &const {
469                [OntologyLink {
470                    name: "describes_source_table",
471                    target: "table",
472                    properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
473                }]
474            },
475            column_semantic_types: &[("id", SemanticType::CatalogItemId)],
476        }),
477    }
478});
479pub static MZ_SQL_SERVER_SOURCE_TABLES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
480    BuiltinMaterializedView {
481        name: "mz_sql_server_source_tables",
482        schema: MZ_INTERNAL_SCHEMA,
483        oid: oid::MV_MZ_SQL_SERVER_SOURCE_TABLES_OID,
484        desc: RelationDesc::builder()
485            .with_column("id", SqlScalarType::String.nullable(false))
486            .with_column("schema_name", SqlScalarType::String.nullable(false))
487            .with_column("table_name", SqlScalarType::String.nullable(false))
488            .with_key(vec![0])
489            .finish(),
490        column_comments: BTreeMap::from_iter([
491            (
492                "id",
493                "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
494            ),
495            (
496                "schema_name",
497                "The schema of the upstream table being ingested.",
498            ),
499            (
500                "table_name",
501                "The name of the upstream table being ingested.",
502            ),
503        ]),
504        sql: "
505IN CLUSTER mz_catalog_server
506WITH (
507    ASSERT NOT NULL id,
508    ASSERT NOT NULL schema_name,
509    ASSERT NOT NULL table_name
510) AS
511SELECT
512    mz_internal.parse_catalog_id(r.data->'key'->'gid') AS id,
513    details->'external_reference'->>1 AS schema_name,
514    details->'external_reference'->>2 AS table_name
515FROM
516    mz_internal.mz_catalog_raw r,
517    LATERAL (
518        SELECT mz_internal.parse_source_export_details(
519            r.data->'value'->'definition'->'V1'->>'create_sql')
520    ) AS d(details)
521    JOIN mz_catalog.mz_sources s
522        ON s.id = details->>'source_id' AND s.type = 'sql-server'
523WHERE
524    r.data->>'kind' = 'Item' AND
525    details IS NOT NULL",
526        is_retained_metrics_object: true,
527        access: vec![PUBLIC_SELECT],
528        ontology: Some(Ontology {
529            entity_name: "sql_server_source_table",
530            description: "SQL Server source table-level details",
531            links: &const {
532                [OntologyLink {
533                    name: "describes_source_table",
534                    target: "table",
535                    properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
536                }]
537            },
538            column_semantic_types: &[("id", SemanticType::CatalogItemId)],
539        }),
540    }
541});
542pub static MZ_KAFKA_SOURCE_TABLES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
543    BuiltinMaterializedView {
544        name: "mz_kafka_source_tables",
545        schema: MZ_INTERNAL_SCHEMA,
546        oid: oid::MV_MZ_KAFKA_SOURCE_TABLES_OID,
547        desc: RelationDesc::builder()
548            .with_column("id", SqlScalarType::String.nullable(false))
549            .with_column("topic", SqlScalarType::String.nullable(false))
550            .with_column("envelope_type", SqlScalarType::String.nullable(false))
551            .with_column("key_format", SqlScalarType::String.nullable(true))
552            .with_column("value_format", SqlScalarType::String.nullable(true))
553            .with_key(vec![0])
554            .finish(),
555        column_comments: BTreeMap::from_iter([
556            (
557                "id",
558                "The ID of the table. Corresponds to `mz_catalog.mz_tables.id`.",
559            ),
560            ("topic", "The topic being ingested."),
561            (
562                "envelope_type",
563                "The envelope type: `none`, `upsert`, or `debezium`. Defaults to `none` when the source table omits an explicit envelope.",
564            ),
565            (
566                "key_format",
567                "The format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
568            ),
569            (
570                "value_format",
571                "The format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
572            ),
573        ]),
574        // Kafka exports are only ever created with the new
575        // `CREATE TABLE ... FROM SOURCE` syntax (kafka has no subsource path),
576        // so the topic sits at position 0 of the single-part external
577        // reference. `parse_source_export_details` resolves the envelope and
578        // key/value formats straight from the table's own `create_sql`,
579        // reproducing the runtime `DataSourceDesc::formats()`/`envelope()` the
580        // old packer read.
581        sql: "
582IN CLUSTER mz_catalog_server
583WITH (
584    ASSERT NOT NULL id,
585    ASSERT NOT NULL topic
586) AS
587SELECT
588    mz_internal.parse_catalog_id(r.data->'key'->'gid') AS id,
589    details->'external_reference'->>0 AS topic,
590    -- Kafka defaults to ENVELOPE NONE when the clause is omitted. The parser
591    -- helper is source-type agnostic and reports NULL for that case, so default
592    -- to 'none' here, where the join has already scoped rows to kafka.
593    COALESCE(details->>'envelope_type', 'none') AS envelope_type,
594    details->>'key_format' AS key_format,
595    details->>'value_format' AS value_format
596FROM
597    mz_internal.mz_catalog_raw r,
598    LATERAL (
599        SELECT mz_internal.parse_source_export_details(
600            r.data->'value'->'definition'->'V1'->>'create_sql')
601    ) AS d(details)
602    JOIN mz_catalog.mz_sources s
603        ON s.id = details->>'source_id' AND s.type = 'kafka'
604WHERE
605    r.data->>'kind' = 'Item' AND
606    details IS NOT NULL",
607        is_retained_metrics_object: true,
608        access: vec![PUBLIC_SELECT],
609        ontology: Some(Ontology {
610            entity_name: "kafka_source_table",
611            description: "Kafka source table-level details",
612            links: &const {
613                [OntologyLink {
614                    name: "describes_source_table",
615                    target: "table",
616                    properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
617                }]
618            },
619            column_semantic_types: &[("id", SemanticType::CatalogItemId)],
620        }),
621    }
622});
623
624pub static MZ_COMPUTE_DEPENDENCIES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
625    name: "mz_compute_dependencies",
626    schema: MZ_INTERNAL_SCHEMA,
627    oid: oid::SOURCE_MZ_COMPUTE_DEPENDENCIES_OID,
628    data_source: IntrospectionType::ComputeDependencies.into(),
629    desc: RelationDesc::builder()
630        .with_column("object_id", SqlScalarType::String.nullable(false))
631        .with_column("dependency_id", SqlScalarType::String.nullable(false))
632        .finish(),
633    column_comments: BTreeMap::from_iter([
634        (
635            "object_id",
636            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions.id`.",
637        ),
638        (
639            "dependency_id",
640            "The ID of a compute dependency. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, `mz_catalog.mz_sources.id`, or `mz_catalog.mz_tables.id`.",
641        ),
642    ]),
643    is_retained_metrics_object: false,
644    access: vec![PUBLIC_SELECT],
645    ontology: Some(Ontology {
646        entity_name: "compute_dependency",
647        description: "Dependency edge from a compute object (index, materialized view, or subscription) to one of the sources of its data",
648        links: &const {
649            [
650                OntologyLink {
651                    name: "depends_on",
652                    target: "object",
653                    properties: LinkProperties::DependsOn {
654                        source_column: "object_id",
655                        target_column: "id",
656                        source_id_type: Some(mz_repr::SemanticType::GlobalId),
657                        requires_mapping: Some("mz_internal.mz_object_global_ids"),
658                    },
659                },
660                OntologyLink {
661                    name: "dependency_is",
662                    target: "object",
663                    properties: LinkProperties::DependsOn {
664                        source_column: "dependency_id",
665                        target_column: "id",
666                        source_id_type: Some(mz_repr::SemanticType::GlobalId),
667                        requires_mapping: Some("mz_internal.mz_object_global_ids"),
668                    },
669                },
670            ]
671        },
672        column_semantic_types: &const {
673            [
674                ("object_id", SemanticType::GlobalId),
675                ("dependency_id", SemanticType::GlobalId),
676            ]
677        },
678    }),
679});
680
681pub static MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES: LazyLock<BuiltinMaterializedView> =
682    LazyLock::new(|| {
683        BuiltinMaterializedView {
684        name: "mz_materialized_view_refresh_strategies",
685        schema: MZ_INTERNAL_SCHEMA,
686        oid: oid::MV_MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES_OID,
687        desc: RelationDesc::builder()
688            .with_column(
689                "materialized_view_id",
690                SqlScalarType::String.nullable(false),
691            )
692            .with_column("type", SqlScalarType::String.nullable(false))
693            .with_column("interval", SqlScalarType::Interval.nullable(true))
694            .with_column("aligned_to_expression", SqlScalarType::String.nullable(true))
695            .with_column("at_expression", SqlScalarType::String.nullable(true))
696            .finish(),
697        column_comments: BTreeMap::from_iter([
698            (
699                "materialized_view_id",
700                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
701            ),
702            (
703                "type",
704                "`at`, `every`, or `on-commit`. Default: `on-commit`",
705            ),
706            (
707                "interval",
708                "The refresh interval of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
709            ),
710            (
711                "aligned_to_expression",
712                "The `ALIGNED TO` expression of a `REFRESH EVERY` option, as it appears in the materialized view's `create_sql`, or `NULL` if the `type` is not `every`.",
713            ),
714            (
715                "at_expression",
716                "The time expression of a `REFRESH AT` option, as it appears in the materialized view's `create_sql`, or `NULL` if the `type` is not `at`.",
717            ),
718        ]),
719        sql: "
720IN CLUSTER mz_catalog_server
721WITH (
722    ASSERT NOT NULL materialized_view_id,
723    ASSERT NOT NULL type
724) AS
725WITH
726    items AS (
727        SELECT
728            mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
729            mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql') AS parsed
730        FROM mz_internal.mz_catalog_raw
731        WHERE data->>'kind' = 'Item'
732    ),
733    user_strategies AS (
734        SELECT
735            i.id AS materialized_view_id,
736            r->>'type' AS type,
737            (r->>'interval')::interval AS interval,
738            r->>'aligned_to' AS aligned_to_expression,
739            r->>'at' AS at_expression
740        FROM
741            items i,
742            jsonb_array_elements(i.parsed->'refresh') AS r
743        WHERE i.parsed->>'type' = 'materialized-view'
744    ),
745    builtin_strategies AS (
746        SELECT
747            's' || (gm.data->'value'->>'catalog_id') AS materialized_view_id,
748            -- Builtin materialized views do not have refresh strategies
749            'on-commit' AS type,
750            NULL::interval AS interval,
751            NULL::text AS aligned_to_expression,
752            NULL::text AS at_expression
753        FROM mz_internal.mz_builtin_materialized_views b
754        JOIN mz_internal.mz_catalog_raw gm ON
755            gm.data->>'kind' = 'GidMapping' AND
756            gm.data->'key'->>'object_type' = b.object_type AND
757            gm.data->'key'->>'schema_name' = b.schema_name AND
758            gm.data->'key'->>'object_name' = b.name
759    )
760SELECT * FROM user_strategies
761UNION ALL
762SELECT * FROM builtin_strategies",
763        is_retained_metrics_object: false,
764        access: vec![PUBLIC_SELECT],
765        ontology: None,
766    }
767    });
768
769pub static MZ_NETWORK_POLICIES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
770    BuiltinMaterializedView {
771        name: "mz_network_policies",
772        schema: MZ_INTERNAL_SCHEMA,
773        oid: oid::MV_MZ_NETWORK_POLICIES_OID,
774        desc: RelationDesc::builder()
775            .with_column("id", SqlScalarType::String.nullable(false))
776            .with_column("name", SqlScalarType::String.nullable(false))
777            .with_column("owner_id", SqlScalarType::String.nullable(false))
778            .with_column(
779                "privileges",
780                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
781            )
782            .with_column("oid", SqlScalarType::Oid.nullable(false))
783            .with_key(vec![0])
784            .with_key(vec![4])
785            .finish(),
786        column_comments: BTreeMap::from_iter([
787            ("id", "The ID of the network policy."),
788            ("name", "The name of the network policy."),
789            (
790                "owner_id",
791                "The role ID of the owner of the network policy. Corresponds to `mz_catalog.mz_roles.id`.",
792            ),
793            (
794                "privileges",
795                "The privileges belonging to the network policy.",
796            ),
797            ("oid", "A PostgreSQL-compatible OID for the network policy."),
798        ]),
799        sql: "
800IN CLUSTER mz_catalog_server
801WITH (
802    ASSERT NOT NULL id,
803    ASSERT NOT NULL name,
804    ASSERT NOT NULL owner_id,
805    ASSERT NOT NULL privileges,
806    ASSERT NOT NULL oid
807) AS
808SELECT
809    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
810    data->'value'->>'name' AS name,
811    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
812    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
813    (data->'value'->>'oid')::oid AS oid
814FROM mz_internal.mz_catalog_raw
815WHERE data->>'kind' = 'NetworkPolicy'",
816        is_retained_metrics_object: false,
817        access: vec![PUBLIC_SELECT],
818        ontology: Some(Ontology {
819            entity_name: "network_policy",
820            description: "Network access policies",
821            links: &const {
822                [OntologyLink {
823                    name: "owned_by",
824                    target: "role",
825                    properties: LinkProperties::fk("owner_id", "id", Cardinality::ManyToOne),
826                }]
827            },
828            column_semantic_types: &const {
829                [
830                    ("id", SemanticType::NetworkPolicyId),
831                    ("owner_id", SemanticType::RoleId),
832                    ("oid", SemanticType::OID),
833                ]
834            },
835        }),
836    }
837});
838
839pub static MZ_NETWORK_POLICY_RULES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
840    BuiltinMaterializedView {
841        name: "mz_network_policy_rules",
842        schema: MZ_INTERNAL_SCHEMA,
843        oid: oid::MV_MZ_NETWORK_POLICY_RULES_OID,
844        desc: RelationDesc::builder()
845            .with_column("name", SqlScalarType::String.nullable(false))
846            .with_column("policy_id", SqlScalarType::String.nullable(false))
847            .with_column("action", SqlScalarType::String.nullable(false))
848            .with_column("address", SqlScalarType::String.nullable(false))
849            .with_column("direction", SqlScalarType::String.nullable(false))
850            .finish(),
851        column_comments: BTreeMap::from_iter([
852            (
853                "name",
854                "The name of the network policy rule. Can be combined with `policy_id` to form a unique identifier.",
855            ),
856            (
857                "policy_id",
858                "The ID the network policy the rule is part of. Corresponds to `mz_internal.mz_network_policies.id`.",
859            ),
860            (
861                "action",
862                "The action of the rule. `allow` is the only supported action.",
863            ),
864            ("address", "The address the rule will take action on."),
865            (
866                "direction",
867                "The direction of traffic the rule applies to. `ingress` is the only supported direction.",
868            ),
869        ]),
870        sql: "
871IN CLUSTER mz_catalog_server
872WITH (
873    ASSERT NOT NULL name,
874    ASSERT NOT NULL policy_id,
875    ASSERT NOT NULL action,
876    ASSERT NOT NULL address,
877    ASSERT NOT NULL direction
878) AS
879SELECT
880    rule->>'name' AS name,
881    mz_internal.parse_catalog_id(data->'key'->'id') AS policy_id,
882    lower(rule->>'action') AS action,
883    rule->>'address' AS address,
884    lower(rule->>'direction') AS direction
885FROM
886    mz_internal.mz_catalog_raw,
887    jsonb_array_elements(data->'value'->'rules') AS rule
888WHERE data->>'kind' = 'NetworkPolicy'",
889        is_retained_metrics_object: false,
890        access: vec![PUBLIC_SELECT],
891        ontology: Some(Ontology {
892            entity_name: "network_policy_rule",
893            description: "Individual rules within a network policy",
894            links: &const {
895                [OntologyLink {
896                    name: "belongs_to_policy",
897                    target: "network_policy",
898                    properties: LinkProperties::fk("policy_id", "id", Cardinality::ManyToOne),
899                }]
900            },
901            column_semantic_types: &[],
902        }),
903    }
904});
905
906pub static MZ_QUERY_POLICIES: LazyLock<BuiltinMaterializedView> =
907    LazyLock::new(|| BuiltinMaterializedView {
908        name: "mz_query_policies",
909        schema: MZ_INTERNAL_SCHEMA,
910        oid: oid::MV_MZ_QUERY_POLICIES_OID,
911        desc: RelationDesc::builder()
912            .with_column("id", SqlScalarType::String.nullable(false))
913            .with_column("name", SqlScalarType::String.nullable(false))
914            .with_column("mode", SqlScalarType::String.nullable(false))
915            .with_column("owner_id", SqlScalarType::String.nullable(false))
916            .with_column(
917                "privileges",
918                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
919            )
920            .with_column("oid", SqlScalarType::Oid.nullable(false))
921            .with_key(vec![0])
922            .with_key(vec![5])
923            .finish(),
924        column_comments: BTreeMap::from_iter([
925            ("id", "The ID of the query policy."),
926            ("name", "The name of the query policy."),
927            (
928                "mode",
929                "Whether matching rules warn or enforce rejection: `warn` or `enforce`.",
930            ),
931            (
932                "owner_id",
933                "The role ID of the policy owner. Corresponds to `mz_catalog.mz_roles.id`.",
934            ),
935            (
936                "privileges",
937                "The privileges belonging to the query policy.",
938            ),
939            ("oid", "A PostgreSQL-compatible OID for the query policy."),
940        ]),
941        sql: "
942IN CLUSTER mz_catalog_server
943WITH (
944    ASSERT NOT NULL id,
945    ASSERT NOT NULL name,
946    ASSERT NOT NULL mode,
947    ASSERT NOT NULL owner_id,
948    ASSERT NOT NULL privileges,
949    ASSERT NOT NULL oid
950) AS
951SELECT
952    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
953    data->'value'->>'name' AS name,
954    data->'value'->>'mode' AS mode,
955    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
956    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
957    (data->'value'->>'oid')::oid AS oid
958FROM mz_internal.mz_catalog_raw
959WHERE data->>'kind' = 'QueryPolicy'",
960        is_retained_metrics_object: false,
961        access: vec![PUBLIC_SELECT],
962        ontology: None,
963    });
964
965pub static MZ_QUERY_POLICY_RULES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
966    BuiltinMaterializedView {
967        name: "mz_query_policy_rules",
968        schema: MZ_INTERNAL_SCHEMA,
969        oid: oid::MV_MZ_QUERY_POLICY_RULES_OID,
970        desc: RelationDesc::builder()
971            .with_column("policy_id", SqlScalarType::String.nullable(false))
972            .with_column("name", SqlScalarType::String.nullable(false))
973            .with_column("action", SqlScalarType::String.nullable(false))
974            .with_column("metric", SqlScalarType::String.nullable(false))
975            .with_column("value", SqlScalarType::String.nullable(false))
976            .with_key(vec![0, 1])
977            .finish(),
978        column_comments: BTreeMap::from_iter([
979            (
980                "policy_id",
981                "The policy containing this rule. Corresponds to `mz_internal.mz_query_policies.id`.",
982            ),
983            ("name", "The name of the rule within its policy."),
984            ("action", "The rule action: `reject`."),
985            ("metric", "The inspected metric: `query_plan_includes`."),
986            (
987                "value",
988                "The prohibited plan feature: `temporary_dataflow` or `storage_read`.",
989            ),
990        ]),
991        sql: "
992IN CLUSTER mz_catalog_server
993WITH (
994    ASSERT NOT NULL policy_id,
995    ASSERT NOT NULL name,
996    ASSERT NOT NULL action,
997    ASSERT NOT NULL metric,
998    ASSERT NOT NULL value
999) AS
1000SELECT
1001    mz_internal.parse_catalog_id(data->'key'->'id') AS policy_id,
1002    rule->>'name' AS name,
1003    'reject'::text AS action,
1004    'query_plan_includes'::text AS metric,
1005    rule->>'value' AS value
1006FROM mz_internal.mz_catalog_raw,
1007    jsonb_array_elements(data->'value'->'rules') AS rule
1008WHERE data->>'kind' = 'QueryPolicy'",
1009        is_retained_metrics_object: false,
1010        access: vec![PUBLIC_SELECT],
1011        ontology: None,
1012    }
1013});
1014
1015pub static MZ_QUERY_POLICY_ATTACHMENTS: LazyLock<BuiltinMaterializedView> =
1016    LazyLock::new(|| BuiltinMaterializedView {
1017        name: "mz_query_policy_attachments",
1018        schema: MZ_INTERNAL_SCHEMA,
1019        oid: oid::MV_MZ_QUERY_POLICY_ATTACHMENTS_OID,
1020        desc: RelationDesc::builder()
1021            .with_column("policy_id", SqlScalarType::String.nullable(false))
1022            .with_column("object_type", SqlScalarType::String.nullable(false))
1023            .with_column("object_id", SqlScalarType::String.nullable(false))
1024            .with_key(vec![1, 2])
1025            .finish(),
1026        column_comments: BTreeMap::from_iter([
1027            (
1028                "policy_id",
1029                "The attached policy. Corresponds to `mz_internal.mz_query_policies.id`.",
1030            ),
1031            ("object_type", "The attachment target type: `cluster`."),
1032            (
1033                "object_id",
1034                "The attached cluster. Corresponds to `mz_catalog.mz_clusters.id`.",
1035            ),
1036        ]),
1037        sql: "
1038IN CLUSTER mz_catalog_server
1039WITH (
1040    ASSERT NOT NULL policy_id,
1041    ASSERT NOT NULL object_type,
1042    ASSERT NOT NULL object_id
1043) AS
1044SELECT
1045    mz_internal.parse_catalog_id(data->'value'->'config'->'query_policy') AS policy_id,
1046    'cluster'::text AS object_type,
1047    mz_internal.parse_catalog_id(data->'key'->'id') AS object_id
1048FROM mz_internal.mz_catalog_raw
1049WHERE data->>'kind' = 'Cluster'
1050    AND data->'value'->'config'->'query_policy' IS NOT NULL",
1051        is_retained_metrics_object: false,
1052        access: vec![PUBLIC_SELECT],
1053        ontology: None,
1054    });
1055
1056/// PostgreSQL-specific metadata about types that doesn't make sense to expose
1057/// in the `mz_types` table as part of our public, stable API.
1058pub static MZ_TYPE_PG_METADATA: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
1059    name: "mz_type_pg_metadata",
1060    schema: MZ_INTERNAL_SCHEMA,
1061    oid: oid::TABLE_MZ_TYPE_PG_METADATA_OID,
1062    desc: RelationDesc::builder()
1063        .with_column("id", SqlScalarType::String.nullable(false))
1064        .with_column("typinput", SqlScalarType::Oid.nullable(false))
1065        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
1066        // NOTE: `pg_type_all_databases` still needs `COALESCE` on this column,
1067        // because its `LEFT JOIN` against this table yields NULLs for types with
1068        // no PostgreSQL metadata.
1069        .with_column("typsend", SqlScalarType::Oid.nullable(false))
1070        // NULL for pseudo-types and arrays of them.
1071        .with_column("typlen", SqlScalarType::Int16.nullable(true))
1072        .finish(),
1073    column_comments: BTreeMap::new(),
1074    is_retained_metrics_object: false,
1075    access: vec![PUBLIC_SELECT],
1076    ontology: None,
1077});
1078pub static MZ_AGGREGATES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
1079    name: "mz_aggregates",
1080    schema: MZ_INTERNAL_SCHEMA,
1081    oid: oid::TABLE_MZ_AGGREGATES_OID,
1082    desc: RelationDesc::builder()
1083        .with_column("oid", SqlScalarType::Oid.nullable(false))
1084        .with_column("agg_kind", SqlScalarType::String.nullable(false))
1085        .with_column("agg_num_direct_args", SqlScalarType::Int16.nullable(false))
1086        .finish(),
1087    column_comments: BTreeMap::new(),
1088    is_retained_metrics_object: false,
1089    access: vec![PUBLIC_SELECT],
1090    ontology: Some(Ontology {
1091        entity_name: "aggregate",
1092        description: "Aggregate function metadata",
1093        links: &const { [] },
1094        column_semantic_types: &[("oid", SemanticType::OID)],
1095    }),
1096});
1097
1098pub static MZ_CLUSTER_WORKLOAD_CLASSES: LazyLock<BuiltinMaterializedView> =
1099    LazyLock::new(|| BuiltinMaterializedView {
1100        name: "mz_cluster_workload_classes",
1101        schema: MZ_INTERNAL_SCHEMA,
1102        oid: oid::MV_MZ_CLUSTER_WORKLOAD_CLASSES_OID,
1103        desc: RelationDesc::builder()
1104            .with_column("id", SqlScalarType::String.nullable(false))
1105            .with_column("workload_class", SqlScalarType::String.nullable(true))
1106            .with_key(vec![0])
1107            .finish(),
1108        column_comments: BTreeMap::new(),
1109        sql: "
1110IN CLUSTER mz_catalog_server
1111WITH (
1112    ASSERT NOT NULL id
1113) AS
1114SELECT
1115    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
1116    CASE WHEN data->'value'->'config'->'workload_class' != 'null'
1117         THEN data->'value'->'config'->>'workload_class'
1118    END AS workload_class
1119FROM mz_internal.mz_catalog_raw
1120WHERE data->>'kind' = 'Cluster'",
1121        is_retained_metrics_object: false,
1122        access: vec![PUBLIC_SELECT],
1123        ontology: None,
1124    });
1125
1126pub const MZ_CLUSTER_WORKLOAD_CLASSES_IND: BuiltinIndex = BuiltinIndex {
1127    name: "mz_cluster_workload_classes_ind",
1128    schema: MZ_INTERNAL_SCHEMA,
1129    oid: oid::INDEX_MZ_CLUSTER_WORKLOAD_CLASSES_IND_OID,
1130    sql: "IN CLUSTER mz_catalog_server
1131ON mz_internal.mz_cluster_workload_classes (id)",
1132    is_retained_metrics_object: false,
1133};
1134
1135pub static MZ_CLUSTER_SCHEDULES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
1136    BuiltinMaterializedView {
1137        name: "mz_cluster_schedules",
1138        schema: MZ_INTERNAL_SCHEMA,
1139        oid: oid::MV_MZ_CLUSTER_SCHEDULES_OID,
1140        desc: RelationDesc::builder()
1141            .with_column("cluster_id", SqlScalarType::String.nullable(false))
1142            .with_column("type", SqlScalarType::String.nullable(false))
1143            .with_column(
1144                "refresh_hydration_time_estimate",
1145                SqlScalarType::Interval.nullable(true),
1146            )
1147            .with_key(vec![0])
1148            .finish(),
1149        column_comments: BTreeMap::from_iter([
1150            (
1151                "cluster_id",
1152                "The ID of the cluster. Corresponds to `mz_clusters.id`.",
1153            ),
1154            ("type", "`on-refresh`, or `manual`. Default: `manual`"),
1155            (
1156                "refresh_hydration_time_estimate",
1157                "The interval given in the `HYDRATION TIME ESTIMATE` option.",
1158            ),
1159        ]),
1160        // Only managed clusters produce a schedule row. The `schedule` field on
1161        // `ManagedCluster` is a serde-tagged enum: the `Manual` unit variant
1162        // serializes to the bare string "Manual", while `Refresh(opts)`
1163        // serializes to `{"Refresh": {"rehydration_time_estimate": {"secs":..,
1164        // "nanos":..}}}`. Convert the Duration to an Interval by composing a
1165        // string and casting — Materialize has no `make_interval`.
1166        sql: "
1167IN CLUSTER mz_catalog_server
1168WITH (
1169    ASSERT NOT NULL cluster_id,
1170    ASSERT NOT NULL type
1171) AS
1172SELECT
1173    mz_internal.parse_catalog_id(data->'key'->'id') AS cluster_id,
1174    CASE
1175        WHEN data->'value'->'config'->'variant'->'Managed'->'schedule' = '\"Manual\"'::jsonb
1176            THEN 'manual'
1177        WHEN data->'value'->'config'->'variant'->'Managed'->'schedule' ? 'Refresh'
1178            THEN 'on-refresh'
1179    END AS type,
1180    CASE
1181        WHEN data->'value'->'config'->'variant'->'Managed'->'schedule' ? 'Refresh' THEN
1182            (
1183                (data->'value'->'config'->'variant'->'Managed'->'schedule'->'Refresh'->'rehydration_time_estimate'->>'secs')
1184                || ' seconds '
1185                || ((data->'value'->'config'->'variant'->'Managed'->'schedule'->'Refresh'->'rehydration_time_estimate'->>'nanos')::bigint / 1000)::text
1186                || ' microseconds'
1187            )::interval
1188    END AS refresh_hydration_time_estimate
1189FROM mz_internal.mz_catalog_raw
1190WHERE
1191    data->>'kind' = 'Cluster' AND
1192    jsonb_typeof(data->'value'->'config'->'variant') = 'object'",
1193        is_retained_metrics_object: false,
1194        access: vec![PUBLIC_SELECT],
1195        ontology: Some(Ontology {
1196            entity_name: "cluster_schedule",
1197            description: "Cluster scheduling configuration",
1198            links: &const {
1199                [OntologyLink {
1200                    name: "belongs_to_cluster",
1201                    target: "cluster",
1202                    properties: LinkProperties::fk("cluster_id", "id", Cardinality::ManyToOne),
1203                }]
1204            },
1205            column_semantic_types: &[("cluster_id", SemanticType::ClusterId)],
1206        }),
1207    }
1208});
1209
1210pub static MZ_CLUSTER_RECONFIGURATIONS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
1211    BuiltinMaterializedView {
1212        name: "mz_cluster_reconfigurations",
1213        schema: MZ_INTERNAL_SCHEMA,
1214        oid: oid::MV_MZ_CLUSTER_RECONFIGURATIONS_OID,
1215        desc: RelationDesc::builder()
1216            .with_column("cluster_id", SqlScalarType::String.nullable(false))
1217            .with_column("status", SqlScalarType::String.nullable(false))
1218            .with_column("deadline", SqlScalarType::MzTimestamp.nullable(false))
1219            .with_column("on_timeout", SqlScalarType::String.nullable(false))
1220            .with_column("target", SqlScalarType::Jsonb.nullable(false))
1221            .with_column("changes", SqlScalarType::Jsonb.nullable(false))
1222            .with_key(vec![0])
1223            .finish(),
1224        column_comments: BTreeMap::from_iter([
1225            (
1226                "cluster_id",
1227                "The ID of the cluster. Corresponds to `mz_clusters.id`.",
1228            ),
1229            (
1230                "status",
1231                "The lifecycle status of the reconfiguration: `in-progress` while the controller converges on the target, then a terminal `finalized`, `timed-out`, `cancelled`, or `resource-exhausted`. The record is retained after it settles, so the latest outcome stays inspectable until a later reconfiguration overwrites it.",
1232            ),
1233            (
1234                "deadline",
1235                "The deadline by which the reconfiguration must complete. After it passes, the `on_timeout` action applies.",
1236            ),
1237            (
1238                "on_timeout",
1239                "The action applied if `deadline` passes before the target hydrates: `commit` (cut over to the not-yet-hydrated target) or `rollback` (revert to the pre-reconfiguration shape).",
1240            ),
1241            (
1242                "target",
1243                "The config shape the cluster is reconfiguring to, as JSON: `size`, `replication_factor`, `availability_zones`, `logging`, and `arrangement_compression`. The realized (current) shape is in `mz_clusters`.",
1244            ),
1245            (
1246                "changes",
1247                "The dimensions in which `target` differs from the cluster's realized configuration, as a JSON object holding the target value per changed dimension. Empty (`{}`) once a record settles with its target applied. A rolled-back record keeps the abandoned diff.",
1248            ),
1249        ]),
1250        // One row per managed cluster with a reconfiguration record, retained
1251        // with a terminal `status` after it settles until the next `ALTER`
1252        // overwrites it. Two null flavors get filtered: unmanaged clusters
1253        // store their config under the `Unmanaged` variant, so the `Managed`
1254        // lookup is SQL NULL (the CTE's WHERE), and a managed cluster that has
1255        // never gracefully reconfigured has the optional field unset, which
1256        // `mz_catalog_raw` serializes as explicit JSON `null` rather than
1257        // omitting the key (hence `!= 'null'`, `IS NOT NULL` would not filter
1258        // it). Status values are kebab-case like the
1259        // catalog's other multi-word values, and the ELSE arms pass unmapped
1260        // enum variants through verbatim: falling to NULL would trip the
1261        // ASSERT NOT NULL and error every read of this relation and of
1262        // `mz_show_clusters`, which joins it. `changes` diffs `target` against
1263        // the realized config per dimension. Both sides come from the same raw
1264        // catalog document, so the jsonb comparison is trivially canonical,
1265        // and it matches the routing's shape-equality (an AZ reorder counts
1266        // as a change in both).
1267        sql: "
1268IN CLUSTER mz_catalog_server
1269WITH (
1270    ASSERT NOT NULL cluster_id,
1271    ASSERT NOT NULL status,
1272    ASSERT NOT NULL deadline,
1273    ASSERT NOT NULL on_timeout,
1274    ASSERT NOT NULL target,
1275    ASSERT NOT NULL changes
1276) AS
1277WITH
1278    managed AS (
1279        SELECT
1280            mz_internal.parse_catalog_id(data->'key'->'id') AS cluster_id,
1281            data->'value'->'config'->'variant'->'Managed' AS config
1282        FROM mz_internal.mz_catalog_raw
1283        WHERE
1284            data->>'kind' = 'Cluster' AND
1285            data->'value'->'config'->'variant'->'Managed' IS NOT NULL
1286    ),
1287    records AS (
1288        SELECT
1289            cluster_id,
1290            config,
1291            config->'reconfiguration' AS reconfiguration,
1292            config->'reconfiguration'->'target' AS target
1293        FROM managed
1294        WHERE config->'reconfiguration' != 'null'
1295    )
1296SELECT
1297    r.cluster_id,
1298    CASE r.reconfiguration->>'status'
1299        WHEN 'InProgress' THEN 'in-progress'
1300        WHEN 'Finalized' THEN 'finalized'
1301        WHEN 'TimedOut' THEN 'timed-out'
1302        WHEN 'Cancelled' THEN 'cancelled'
1303        WHEN 'ResourceExhausted' THEN 'resource-exhausted'
1304        ELSE r.reconfiguration->>'status'
1305    END AS status,
1306    (r.reconfiguration->>'deadline')::mz_timestamp AS deadline,
1307    CASE r.reconfiguration->>'on_timeout'
1308        WHEN 'Commit' THEN 'commit'
1309        WHEN 'Rollback' THEN 'rollback'
1310        ELSE r.reconfiguration->>'on_timeout'
1311    END AS on_timeout,
1312    r.target,
1313    CASE WHEN r.target->'size' != r.config->'size'
1314        THEN jsonb_build_object('size', r.target->'size') ELSE '{}'::jsonb END ||
1315    CASE WHEN r.target->'replication_factor' != r.config->'replication_factor'
1316        THEN jsonb_build_object('replication_factor', r.target->'replication_factor') ELSE '{}'::jsonb END ||
1317    CASE WHEN r.target->'availability_zones' != r.config->'availability_zones'
1318        THEN jsonb_build_object('availability_zones', r.target->'availability_zones') ELSE '{}'::jsonb END ||
1319    CASE WHEN r.target->'logging' != r.config->'logging'
1320        THEN jsonb_build_object('logging', r.target->'logging') ELSE '{}'::jsonb END ||
1321    CASE WHEN r.target->'arrangement_compression' != r.config->'arrangement_compression'
1322        THEN jsonb_build_object('arrangement_compression', r.target->'arrangement_compression') ELSE '{}'::jsonb END
1323    AS changes
1324FROM records r",
1325        is_retained_metrics_object: false,
1326        access: vec![PUBLIC_SELECT],
1327        ontology: Some(Ontology {
1328            entity_name: "cluster_reconfiguration",
1329            description: "Latest graceful cluster reconfiguration",
1330            links: &const {
1331                [OntologyLink {
1332                    // At most one reconfiguration record per cluster (unique
1333                    // key on `cluster_id`), so the FK is one-to-one.
1334                    name: "belongs_to_cluster",
1335                    target: "cluster",
1336                    properties: LinkProperties::fk("cluster_id", "id", Cardinality::OneToOne),
1337                }]
1338            },
1339            column_semantic_types: &[("cluster_id", SemanticType::ClusterId)],
1340        }),
1341    }
1342});
1343
1344pub const MZ_CLUSTER_RECONFIGURATIONS_IND: BuiltinIndex = BuiltinIndex {
1345    name: "mz_cluster_reconfigurations_ind",
1346    schema: MZ_INTERNAL_SCHEMA,
1347    oid: oid::INDEX_MZ_CLUSTER_RECONFIGURATIONS_IND_OID,
1348    sql: "IN CLUSTER mz_catalog_server
1349ON mz_internal.mz_cluster_reconfigurations (cluster_id)",
1350    is_retained_metrics_object: false,
1351};
1352
1353pub static MZ_CLUSTER_AUTO_SCALING_STRATEGIES: LazyLock<BuiltinMaterializedView> = LazyLock::new(
1354    || {
1355        BuiltinMaterializedView {
1356            name: "mz_cluster_auto_scaling_strategies",
1357            schema: MZ_INTERNAL_SCHEMA,
1358            oid: oid::MV_MZ_CLUSTER_AUTO_SCALING_STRATEGIES_OID,
1359            desc: RelationDesc::builder()
1360                .with_column("cluster_id", SqlScalarType::String.nullable(false))
1361                .with_column("strategy", SqlScalarType::Jsonb.nullable(false))
1362                .with_column("state", SqlScalarType::Jsonb.nullable(true))
1363                .with_key(vec![0])
1364                .finish(),
1365            column_comments: BTreeMap::from_iter([
1366                (
1367                    "cluster_id",
1368                    "The ID of the cluster. Corresponds to `mz_clusters.id`.",
1369                ),
1370                (
1371                    "strategy",
1372                    "**Unstable** The configured autoscaling policy, as JSON. Currently an `on_hydration` sub-policy carrying its `hydration_size` and optional `linger_duration`.",
1373                ),
1374                (
1375                    "state",
1376                    "**Unstable** The in-flight autoscaling runtime state, as JSON keyed by strategy, or `NULL` when nothing is running. Currently a `burst` key carrying the active hydration burst: its `burst_size`, `linger_duration`, and `steady_ready_at`.",
1377                ),
1378            ]),
1379            // One row per managed cluster with a strategy configured or a burst
1380            // running (a burst can briefly outlive a just-removed policy).
1381            // Absent fields serialize as JSON `null`. `state` is keyed by
1382            // strategy so a future strategy's state is another key, not a
1383            // schema change.
1384            sql: "
1385IN CLUSTER mz_catalog_server
1386WITH (
1387    ASSERT NOT NULL cluster_id,
1388    ASSERT NOT NULL strategy
1389) AS
1390WITH
1391    managed AS (
1392        SELECT
1393            mz_internal.parse_catalog_id(data->'key'->'id') AS cluster_id,
1394            data->'value'->'config'->'variant'->'Managed'->'auto_scaling_strategy' AS strategy,
1395            data->'value'->'config'->'variant'->'Managed'->'burst' AS burst
1396        FROM mz_internal.mz_catalog_raw
1397        WHERE
1398            data->>'kind' = 'Cluster' AND
1399            data->'value'->'config'->'variant'->'Managed' IS NOT NULL
1400    )
1401SELECT
1402    m.cluster_id,
1403    COALESCE(m.strategy, 'null'::jsonb) AS strategy,
1404    CASE WHEN m.burst != 'null' THEN jsonb_build_object('burst', m.burst) END AS state
1405FROM managed m
1406WHERE m.strategy != 'null' OR m.burst != 'null'",
1407            is_retained_metrics_object: false,
1408            access: vec![PUBLIC_SELECT],
1409            ontology: Some(Ontology {
1410                entity_name: "cluster_auto_scaling_strategy",
1411                description: "Configured cluster autoscaling strategy and in-flight state",
1412                links: &const {
1413                    [OntologyLink {
1414                        // At most one row per managed cluster (unique key on
1415                        // `cluster_id`), so the FK is one-to-one.
1416                        name: "belongs_to_cluster",
1417                        target: "cluster",
1418                        properties: LinkProperties::fk("cluster_id", "id", Cardinality::OneToOne),
1419                    }]
1420                },
1421                column_semantic_types: &[("cluster_id", SemanticType::ClusterId)],
1422            }),
1423        }
1424    },
1425);
1426
1427pub const MZ_CLUSTER_AUTO_SCALING_STRATEGIES_IND: BuiltinIndex = BuiltinIndex {
1428    name: "mz_cluster_auto_scaling_strategies_ind",
1429    schema: MZ_INTERNAL_SCHEMA,
1430    oid: oid::INDEX_MZ_CLUSTER_AUTO_SCALING_STRATEGIES_IND_OID,
1431    sql: "IN CLUSTER mz_catalog_server
1432ON mz_internal.mz_cluster_auto_scaling_strategies (cluster_id)",
1433    is_retained_metrics_object: false,
1434};
1435
1436pub static MZ_INTERNAL_CLUSTER_REPLICAS: LazyLock<BuiltinMaterializedView> =
1437    LazyLock::new(|| BuiltinMaterializedView {
1438        name: "mz_internal_cluster_replicas",
1439        schema: MZ_INTERNAL_SCHEMA,
1440        oid: oid::MV_MZ_INTERNAL_CLUSTER_REPLICAS_OID,
1441        desc: RelationDesc::builder()
1442            .with_column("id", SqlScalarType::String.nullable(false))
1443            .with_key(vec![0])
1444            .finish(),
1445        column_comments: BTreeMap::from_iter([(
1446            "id",
1447            "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
1448        )]),
1449        sql: "
1450IN CLUSTER mz_catalog_server
1451WITH (
1452    ASSERT NOT NULL id
1453) AS
1454SELECT mz_internal.parse_catalog_id(data->'key'->'id') AS id
1455FROM mz_internal.mz_catalog_raw
1456WHERE
1457    data->>'kind' = 'ClusterReplica' AND
1458    (data->'value'->'config'->'location'->'Managed'->>'internal')::bool = true",
1459        is_retained_metrics_object: false,
1460        access: vec![PUBLIC_SELECT],
1461        ontology: None,
1462    });
1463
1464pub static MZ_PENDING_CLUSTER_REPLICAS: LazyLock<BuiltinMaterializedView> =
1465    LazyLock::new(|| BuiltinMaterializedView {
1466        name: "mz_pending_cluster_replicas",
1467        schema: MZ_INTERNAL_SCHEMA,
1468        oid: oid::MV_MZ_PENDING_CLUSTER_REPLICAS_OID,
1469        desc: RelationDesc::builder()
1470            .with_column("id", SqlScalarType::String.nullable(false))
1471            .with_key(vec![0])
1472            .finish(),
1473        column_comments: BTreeMap::from_iter([(
1474            "id",
1475            "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
1476        )]),
1477        sql: "
1478IN CLUSTER mz_catalog_server
1479WITH (
1480    ASSERT NOT NULL id
1481) AS
1482SELECT mz_internal.parse_catalog_id(data->'key'->'id') AS id
1483FROM mz_internal.mz_catalog_raw
1484WHERE
1485    data->>'kind' = 'ClusterReplica' AND
1486    (data->'value'->'config'->'location'->'Managed'->>'pending')::bool = true",
1487        is_retained_metrics_object: false,
1488        access: vec![PUBLIC_SELECT],
1489        ontology: None,
1490    });
1491
1492/// System-only sidecar to `mz_cluster_replica_sizes`, exposing per-size
1493/// configuration that the cluster MaterializedViews need to compute the
1494/// `disk` column.
1495///
1496/// `mz_clusters.disk` and `mz_cluster_replicas.disk` are computed as
1497/// `NOT swap_enabled AND disk_bytes != 0`. The orchestrator-supplied
1498/// `swap_enabled` flag wasn't SQL-visible before the table→MV conversion,
1499/// so this table is locked down with `access: vec![]` (same pattern as
1500/// `mz_catalog_raw`): builtin MVs read it at bootstrap, but direct user
1501/// `SELECT` is denied.
1502pub static MZ_CLUSTER_REPLICA_SIZE_INTERNAL: LazyLock<BuiltinTable> = LazyLock::new(|| {
1503    BuiltinTable {
1504        name: "mz_cluster_replica_size_internal",
1505        schema: MZ_INTERNAL_SCHEMA,
1506        oid: oid::TABLE_MZ_CLUSTER_REPLICA_SIZE_INTERNAL_OID,
1507        desc: RelationDesc::builder()
1508            .with_column("size", SqlScalarType::String.nullable(false))
1509            .with_column("swap_enabled", SqlScalarType::Bool.nullable(false))
1510            .with_column("disk_bytes", SqlScalarType::UInt64.nullable(false))
1511            .with_key(vec![0])
1512            .finish(),
1513        column_comments: BTreeMap::from_iter([
1514            ("size", "The human-readable replica size."),
1515            (
1516                "swap_enabled",
1517                "Whether the replica size's pods are configured to allow swap. Used internally to compute the public `disk` column.",
1518            ),
1519            (
1520                "disk_bytes",
1521                "The replica size's disk limit in bytes (0 if explicitly disabled). Used internally to compute the public `disk` column.",
1522            ),
1523        ]),
1524        is_retained_metrics_object: true,
1525        access: vec![],
1526        ontology: None,
1527    }
1528});
1529
1530pub const MZ_CLUSTER_REPLICA_SIZE_INTERNAL_IND: BuiltinIndex = BuiltinIndex {
1531    name: "mz_cluster_replica_size_internal_ind",
1532    schema: MZ_INTERNAL_SCHEMA,
1533    oid: oid::INDEX_MZ_CLUSTER_REPLICA_SIZE_INTERNAL_IND_OID,
1534    sql: "IN CLUSTER mz_catalog_server
1535ON mz_internal.mz_cluster_replica_size_internal (size)",
1536    is_retained_metrics_object: true,
1537};
1538
1539pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
1540    BuiltinSource {
1541        name: "mz_cluster_replica_status_history",
1542        schema: MZ_INTERNAL_SCHEMA,
1543        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
1544        data_source: IntrospectionType::ReplicaStatusHistory.into(),
1545        desc: REPLICA_STATUS_HISTORY_DESC.clone(),
1546        column_comments: BTreeMap::from_iter([
1547            ("replica_id", "The ID of a cluster replica."),
1548            ("process_id", "The ID of a process within the replica."),
1549            (
1550                "status",
1551                "The status of the cluster replica: `online` or `offline`.",
1552            ),
1553            (
1554                "reason",
1555                "If the cluster replica is in an `offline` state, the reason (if available). For example, `oom-killed`.",
1556            ),
1557            (
1558                "occurred_at",
1559                "Wall-clock timestamp at which the event occurred.",
1560            ),
1561        ]),
1562        is_retained_metrics_object: false,
1563        access: vec![PUBLIC_SELECT],
1564        ontology: Some(Ontology {
1565            entity_name: "replica_status_event",
1566            description: "Historical replica status events (ready, not-ready, etc.)",
1567            links: &const {
1568                [OntologyLink {
1569                    name: "status_event_of_replica",
1570                    target: "replica",
1571                    properties: LinkProperties::fk_typed(
1572                        "replica_id",
1573                        "id",
1574                        Cardinality::ManyToOne,
1575                        mz_repr::SemanticType::CatalogItemId,
1576                    ),
1577                }]
1578            },
1579            column_semantic_types: &[("replica_id", SemanticType::ReplicaId)],
1580        }),
1581    }
1582});
1583
1584pub static MZ_CLUSTER_REPLICA_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
1585    name: "mz_cluster_replica_statuses",
1586    schema: MZ_INTERNAL_SCHEMA,
1587    oid: oid::VIEW_MZ_CLUSTER_REPLICA_STATUSES_OID,
1588    desc: RelationDesc::builder()
1589        .with_column("replica_id", SqlScalarType::String.nullable(false))
1590        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
1591        .with_column("status", SqlScalarType::String.nullable(false))
1592        .with_column("reason", SqlScalarType::String.nullable(true))
1593        .with_column(
1594            "updated_at",
1595            SqlScalarType::TimestampTz { precision: None }.nullable(false),
1596        )
1597        .with_key(vec![0, 1])
1598        .finish(),
1599    column_comments: BTreeMap::from_iter([
1600        (
1601            "replica_id",
1602            "Materialize's unique ID for the cluster replica.",
1603        ),
1604        (
1605            "process_id",
1606            "The ID of the process within the cluster replica.",
1607        ),
1608        (
1609            "status",
1610            "The status of the cluster replica: `online` or `offline`.",
1611        ),
1612        (
1613            "reason",
1614            "If the cluster replica is in a `offline` state, the reason (if available). For example, `oom-killed`.",
1615        ),
1616        (
1617            "updated_at",
1618            "The time at which the status was last updated.",
1619        ),
1620    ]),
1621    sql: "
1622SELECT
1623    DISTINCT ON (replica_id, process_id)
1624    replica_id,
1625    process_id,
1626    status,
1627    reason,
1628    occurred_at as updated_at
1629FROM mz_internal.mz_cluster_replica_status_history
1630JOIN mz_cluster_replicas r ON r.id = replica_id
1631ORDER BY replica_id, process_id, occurred_at DESC",
1632    access: vec![PUBLIC_SELECT],
1633    ontology: Some(Ontology {
1634        entity_name: "replica_status",
1635        description: "Current status of each replica",
1636        links: &const {
1637            [OntologyLink {
1638                name: "status_of_replica",
1639                target: "replica",
1640                properties: LinkProperties::fk_typed(
1641                    "replica_id",
1642                    "id",
1643                    Cardinality::ManyToOne,
1644                    mz_repr::SemanticType::ReplicaId,
1645                ),
1646            }]
1647        },
1648        column_semantic_types: &const {
1649            [
1650                ("replica_id", SemanticType::ReplicaId),
1651                ("updated_at", SemanticType::WallclockTimestamp),
1652            ]
1653        },
1654    }),
1655});
1656
1657pub static MZ_SOURCE_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
1658    name: "mz_source_status_history",
1659    schema: MZ_INTERNAL_SCHEMA,
1660    oid: oid::SOURCE_MZ_SOURCE_STATUS_HISTORY_OID,
1661    data_source: IntrospectionType::SourceStatusHistory.into(),
1662    desc: MZ_SOURCE_STATUS_HISTORY_DESC.clone(),
1663    column_comments: BTreeMap::from_iter([
1664        (
1665            "occurred_at",
1666            "Wall-clock timestamp of the source status change.",
1667        ),
1668        (
1669            "source_id",
1670            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
1671        ),
1672        (
1673            "status",
1674            "The status of the source: one of `starting`, `running`, `paused`, `stalled`, or `dropped`.",
1675        ),
1676        (
1677            "error",
1678            "If the source is in an error state, the error message.",
1679        ),
1680        (
1681            "details",
1682            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
1683        ),
1684        (
1685            "replica_id",
1686            "The ID of the replica that an instance of a source is running on.",
1687        ),
1688    ]),
1689    is_retained_metrics_object: false,
1690    access: vec![PUBLIC_SELECT],
1691    ontology: Some(Ontology {
1692        entity_name: "source_status_event",
1693        description: "Historical source status events",
1694        links: &const {
1695            [
1696                OntologyLink {
1697                    name: "status_event_of_source",
1698                    target: "source",
1699                    properties: LinkProperties::fk_mapped(
1700                        "source_id",
1701                        "id",
1702                        Cardinality::ManyToOne,
1703                        mz_repr::SemanticType::GlobalId,
1704                        "mz_internal.mz_object_global_ids",
1705                    ),
1706                },
1707                OntologyLink {
1708                    name: "on_replica",
1709                    target: "replica",
1710                    properties: LinkProperties::fk_nullable(
1711                        "replica_id",
1712                        "id",
1713                        Cardinality::ManyToOne,
1714                    ),
1715                },
1716            ]
1717        },
1718        column_semantic_types: &const {
1719            [
1720                ("occurred_at", SemanticType::WallclockTimestamp),
1721                ("source_id", SemanticType::GlobalId),
1722                ("replica_id", SemanticType::ReplicaId),
1723            ]
1724        },
1725    }),
1726});
1727
1728pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(
1729    || BuiltinSource {
1730        name: "mz_aws_privatelink_connection_status_history",
1731        schema: MZ_INTERNAL_SCHEMA,
1732        oid: oid::SOURCE_MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_OID,
1733        data_source: DataSourceDesc::Introspection(
1734            IntrospectionType::PrivatelinkConnectionStatusHistory,
1735        ),
1736        desc: MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC.clone(),
1737        column_comments: BTreeMap::from_iter([
1738            ("occurred_at", "Wall-clock timestamp of the status change."),
1739            (
1740                "connection_id",
1741                "The unique identifier of the AWS PrivateLink connection. Corresponds to `mz_catalog.mz_connections.id`.",
1742            ),
1743            (
1744                "status",
1745                "The status of the connection: one of `pending-service-discovery`, `creating-endpoint`, `recreating-endpoint`, `updating-endpoint`, `available`, `deleted`, `deleting`, `expired`, `failed`, `pending`, `pending-acceptance`, `rejected`, or `unknown`.",
1746            ),
1747        ]),
1748        is_retained_metrics_object: false,
1749        access: vec![PUBLIC_SELECT],
1750        ontology: None,
1751    },
1752);
1753
1754pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| {
1755    BuiltinView {
1756        name: "mz_aws_privatelink_connection_statuses",
1757        schema: MZ_INTERNAL_SCHEMA,
1758        oid: oid::VIEW_MZ_AWS_PRIVATELINK_CONNECTION_STATUSES_OID,
1759        desc: RelationDesc::builder()
1760            .with_column("id", SqlScalarType::String.nullable(false))
1761            .with_column("name", SqlScalarType::String.nullable(false))
1762            .with_column(
1763                "last_status_change_at",
1764                SqlScalarType::TimestampTz { precision: None }.nullable(true),
1765            )
1766            .with_column("status", SqlScalarType::String.nullable(true))
1767            .with_key(vec![0])
1768            .finish(),
1769        column_comments: BTreeMap::from_iter([
1770            (
1771                "id",
1772                "The ID of the connection. Corresponds to `mz_catalog.mz_connections.id`.",
1773            ),
1774            ("name", "The name of the connection."),
1775            (
1776                "last_status_change_at",
1777                "Wall-clock timestamp of the connection status change.",
1778            ),
1779            (
1780                "status",
1781                "The status of the connection: one of `pending-service-discovery`, `creating-endpoint`, `recreating-endpoint`, `updating-endpoint`, `available`, `deleted`, `deleting`, `expired`, `failed`, `pending`, `pending-acceptance`, `rejected`, or `unknown`.",
1782            ),
1783        ]),
1784        sql: "
1785    WITH statuses_w_last_status AS (
1786        SELECT
1787            connection_id,
1788            occurred_at,
1789            status,
1790            lag(status) OVER (PARTITION BY connection_id ORDER BY occurred_at) AS last_status
1791        FROM mz_internal.mz_aws_privatelink_connection_status_history
1792    ),
1793    latest_events AS (
1794        -- Only take the most recent transition for each ID
1795        SELECT DISTINCT ON(connection_id) connection_id, occurred_at, status
1796        FROM statuses_w_last_status
1797        -- Only keep first status transitions
1798        WHERE status <> last_status OR last_status IS NULL
1799        ORDER BY connection_id, occurred_at DESC
1800    )
1801    SELECT
1802        conns.id,
1803        name,
1804        occurred_at as last_status_change_at,
1805        status
1806    FROM latest_events
1807    JOIN mz_catalog.mz_connections AS conns
1808    ON conns.id = latest_events.connection_id",
1809        access: vec![PUBLIC_SELECT],
1810        ontology: Some(Ontology {
1811            entity_name: "privatelink_status",
1812            description: "PrivateLink connection health status",
1813            links: &const {
1814                [OntologyLink {
1815                    name: "status_of",
1816                    target: "connection",
1817                    properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
1818                }]
1819            },
1820            column_semantic_types: &[("id", SemanticType::CatalogItemId)],
1821        }),
1822    }
1823});
1824
1825pub static MZ_STATEMENT_EXECUTION_HISTORY: LazyLock<BuiltinSource> =
1826    LazyLock::new(|| BuiltinSource {
1827        name: "mz_statement_execution_history",
1828        schema: MZ_INTERNAL_SCHEMA,
1829        oid: oid::SOURCE_MZ_STATEMENT_EXECUTION_HISTORY_OID,
1830        data_source: IntrospectionType::StatementExecutionHistory.into(),
1831        desc: MZ_STATEMENT_EXECUTION_HISTORY_DESC.clone(),
1832        column_comments: BTreeMap::new(),
1833        is_retained_metrics_object: false,
1834        access: vec![MONITOR_SELECT],
1835        ontology: None,
1836    });
1837
1838pub static MZ_STATEMENT_EXECUTION_HISTORY_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
1839    BuiltinView {
1840    name: "mz_statement_execution_history_redacted",
1841    schema: MZ_INTERNAL_SCHEMA,
1842    oid: oid::VIEW_MZ_STATEMENT_EXECUTION_HISTORY_REDACTED_OID,
1843    // everything but `params` and `error_message`
1844    desc: RelationDesc::builder()
1845        .with_column("id", SqlScalarType::Uuid.nullable(false))
1846        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
1847        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
1848        .with_column("cluster_id", SqlScalarType::String.nullable(true))
1849        .with_column("application_name", SqlScalarType::String.nullable(false))
1850        .with_column("cluster_name", SqlScalarType::String.nullable(true))
1851        .with_column("database_name", SqlScalarType::String.nullable(false))
1852        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
1853        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
1854        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
1855        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
1856        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
1857        .with_column("mz_version", SqlScalarType::String.nullable(false))
1858        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
1859        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
1860        .with_column("finished_status", SqlScalarType::String.nullable(true))
1861        .with_column("result_size", SqlScalarType::Int64.nullable(true))
1862        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
1863        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
1864        .finish(),
1865    column_comments: BTreeMap::new(),
1866    sql: "
1867SELECT id, prepared_statement_id, sample_rate, cluster_id, application_name,
1868cluster_name, database_name, search_path, transaction_isolation, execution_timestamp, transaction_id,
1869transient_index_id, mz_version, began_at, finished_at, finished_status,
1870result_size, rows_returned, execution_strategy
1871FROM mz_internal.mz_statement_execution_history",
1872    access: vec![SUPPORT_SELECT, ANALYTICS_SELECT, MONITOR_REDACTED_SELECT, MONITOR_SELECT],
1873    ontology: None,
1874}
1875});
1876
1877pub static MZ_PREPARED_STATEMENT_HISTORY: LazyLock<BuiltinSource> =
1878    LazyLock::new(|| BuiltinSource {
1879        name: "mz_prepared_statement_history",
1880        schema: MZ_INTERNAL_SCHEMA,
1881        oid: oid::SOURCE_MZ_PREPARED_STATEMENT_HISTORY_OID,
1882        data_source: IntrospectionType::PreparedStatementHistory.into(),
1883        desc: MZ_PREPARED_STATEMENT_HISTORY_DESC.clone(),
1884        column_comments: BTreeMap::new(),
1885        is_retained_metrics_object: false,
1886        access: vec![
1887            SUPPORT_SELECT,
1888            ANALYTICS_SELECT,
1889            MONITOR_REDACTED_SELECT,
1890            MONITOR_SELECT,
1891        ],
1892        ontology: None,
1893    });
1894
1895pub static MZ_SQL_TEXT: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
1896    name: "mz_sql_text",
1897    schema: MZ_INTERNAL_SCHEMA,
1898    oid: oid::SOURCE_MZ_SQL_TEXT_OID,
1899    desc: MZ_SQL_TEXT_DESC.clone(),
1900    data_source: IntrospectionType::SqlText.into(),
1901    column_comments: BTreeMap::new(),
1902    is_retained_metrics_object: false,
1903    access: vec![MONITOR_SELECT],
1904    ontology: Some(Ontology {
1905        entity_name: "sql_text",
1906        description: "Raw SQL text of executed statements",
1907        links: &const { [] },
1908        column_semantic_types: &[],
1909    }),
1910});
1911
1912pub static MZ_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
1913    name: "mz_sql_text_redacted",
1914    schema: MZ_INTERNAL_SCHEMA,
1915    oid: oid::VIEW_MZ_SQL_TEXT_REDACTED_OID,
1916    desc: RelationDesc::builder()
1917        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
1918        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
1919        .finish(),
1920    column_comments: BTreeMap::new(),
1921    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_sql_text",
1922    access: vec![
1923        MONITOR_SELECT,
1924        MONITOR_REDACTED_SELECT,
1925        SUPPORT_SELECT,
1926        ANALYTICS_SELECT,
1927    ],
1928    ontology: None,
1929});
1930
1931pub static MZ_RECENT_SQL_TEXT: LazyLock<BuiltinView> = LazyLock::new(|| {
1932    BuiltinView {
1933        name: "mz_recent_sql_text",
1934        schema: MZ_INTERNAL_SCHEMA,
1935        oid: oid::VIEW_MZ_RECENT_SQL_TEXT_OID,
1936        // This should always be 1 day more than the interval in
1937        // `MZ_RECENT_THINNED_ACTIVITY_LOG` , because `prepared_day`
1938        // is rounded down to the nearest day.  Thus something that actually happened three days ago
1939        // could have a `prepared day` anywhere from 3 to 4 days back.
1940        desc: RelationDesc::builder()
1941            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
1942            .with_column("sql", SqlScalarType::String.nullable(false))
1943            .with_column("redacted_sql", SqlScalarType::String.nullable(false))
1944            .with_key(vec![0, 1, 2])
1945            .finish(),
1946        column_comments: BTreeMap::new(),
1947        sql: "SELECT DISTINCT sql_hash, sql, redacted_sql FROM mz_internal.mz_sql_text WHERE prepared_day + INTERVAL '4 days' >= mz_now()",
1948        access: vec![MONITOR_SELECT],
1949        ontology: Some(Ontology {
1950            entity_name: "recent_sql_text",
1951            description: "Recent SQL text (indexed, last ~3-4 days)",
1952            links: &const { [] },
1953            column_semantic_types: &[("sql", SemanticType::SqlDefinition)],
1954        }),
1955    }
1956});
1957
1958pub static MZ_RECENT_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
1959    name: "mz_recent_sql_text_redacted",
1960    schema: MZ_INTERNAL_SCHEMA,
1961    oid: oid::VIEW_MZ_RECENT_SQL_TEXT_REDACTED_OID,
1962    desc: RelationDesc::builder()
1963        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
1964        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
1965        .finish(),
1966    column_comments: BTreeMap::new(),
1967    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_recent_sql_text",
1968    access: vec![
1969        MONITOR_SELECT,
1970        MONITOR_REDACTED_SELECT,
1971        SUPPORT_SELECT,
1972        ANALYTICS_SELECT,
1973    ],
1974    ontology: None,
1975});
1976
1977pub static MZ_RECENT_SQL_TEXT_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
1978    name: "mz_recent_sql_text_ind",
1979    schema: MZ_INTERNAL_SCHEMA,
1980    oid: oid::INDEX_MZ_RECENT_SQL_TEXT_IND_OID,
1981    sql: "IN CLUSTER mz_catalog_server ON mz_internal.mz_recent_sql_text (sql_hash)",
1982    is_retained_metrics_object: false,
1983});
1984
1985pub static MZ_SESSION_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
1986    name: "mz_session_history",
1987    schema: MZ_INTERNAL_SCHEMA,
1988    oid: oid::SOURCE_MZ_SESSION_HISTORY_OID,
1989    data_source: IntrospectionType::SessionHistory.into(),
1990    desc: MZ_SESSION_HISTORY_DESC.clone(),
1991    column_comments: BTreeMap::from_iter([
1992        (
1993            "session_id",
1994            "The globally unique ID of the session. Corresponds to `mz_sessions.id`.",
1995        ),
1996        (
1997            "connected_at",
1998            "The time at which the session was established.",
1999        ),
2000        (
2001            "initial_application_name",
2002            "The `application_name` session metadata field.",
2003        ),
2004        (
2005            "authenticated_user",
2006            "The name of the user for which the session was established.",
2007        ),
2008    ]),
2009    is_retained_metrics_object: false,
2010    access: vec![PUBLIC_SELECT],
2011    ontology: Some(Ontology {
2012        entity_name: "session",
2013        description: "Historical session connection events",
2014        links: &const {
2015            [OntologyLink {
2016                name: "active_as",
2017                target: "active_session",
2018                properties: LinkProperties::fk_nullable("session_id", "id", Cardinality::ManyToOne),
2019            }]
2020        },
2021        column_semantic_types: &[("connected_at", SemanticType::WallclockTimestamp)],
2022    }),
2023});
2024
2025pub static MZ_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
2026    BuiltinView {
2027        name: "mz_activity_log_thinned",
2028        schema: MZ_INTERNAL_SCHEMA,
2029        oid: oid::VIEW_MZ_ACTIVITY_LOG_THINNED_OID,
2030        desc: RelationDesc::builder()
2031            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
2032            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
2033            .with_column("cluster_id", SqlScalarType::String.nullable(true))
2034            .with_column("application_name", SqlScalarType::String.nullable(false))
2035            .with_column("cluster_name", SqlScalarType::String.nullable(true))
2036            .with_column("database_name", SqlScalarType::String.nullable(false))
2037            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
2038            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
2039            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
2040            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
2041            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
2042            .with_column("mz_version", SqlScalarType::String.nullable(false))
2043            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
2044            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
2045            .with_column("finished_status", SqlScalarType::String.nullable(true))
2046            .with_column("error_message", SqlScalarType::String.nullable(true))
2047            .with_column("result_size", SqlScalarType::Int64.nullable(true))
2048            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
2049            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
2050            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
2051            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
2052            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
2053            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
2054            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
2055            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
2056            .with_column("statement_type", SqlScalarType::String.nullable(true))
2057            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
2058            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
2059            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
2060            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
2061            .finish(),
2062        column_comments: BTreeMap::new(),
2063        sql: "
2064SELECT mseh.id AS execution_id, sample_rate, cluster_id, application_name, cluster_name, database_name, search_path,
2065transaction_isolation, execution_timestamp, transient_index_id, params, mz_version, began_at, finished_at, finished_status,
2066error_message, result_size, rows_returned, execution_strategy, transaction_id,
2067mpsh.id AS prepared_statement_id, sql_hash, mpsh.name AS prepared_statement_name,
2068mpsh.session_id, prepared_at, statement_type, throttled_count,
2069connected_at, initial_application_name, authenticated_user
2070FROM mz_internal.mz_statement_execution_history mseh,
2071     mz_internal.mz_prepared_statement_history mpsh,
2072     mz_internal.mz_session_history msh
2073WHERE mseh.prepared_statement_id = mpsh.id
2074AND mpsh.session_id = msh.session_id",
2075        access: vec![MONITOR_SELECT],
2076        ontology: None,
2077    }
2078});
2079
2080pub static MZ_RECENT_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
2081    BuiltinView {
2082        name: "mz_recent_activity_log_thinned",
2083        schema: MZ_INTERNAL_SCHEMA,
2084        oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_THINNED_OID,
2085        desc: RelationDesc::builder()
2086            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
2087            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
2088            .with_column("cluster_id", SqlScalarType::String.nullable(true))
2089            .with_column("application_name", SqlScalarType::String.nullable(false))
2090            .with_column("cluster_name", SqlScalarType::String.nullable(true))
2091            .with_column("database_name", SqlScalarType::String.nullable(false))
2092            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
2093            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
2094            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
2095            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
2096            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
2097            .with_column("mz_version", SqlScalarType::String.nullable(false))
2098            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
2099            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
2100            .with_column("finished_status", SqlScalarType::String.nullable(true))
2101            .with_column("error_message", SqlScalarType::String.nullable(true))
2102            .with_column("result_size", SqlScalarType::Int64.nullable(true))
2103            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
2104            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
2105            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
2106            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
2107            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
2108            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
2109            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
2110            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
2111            .with_column("statement_type", SqlScalarType::String.nullable(true))
2112            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
2113            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
2114            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
2115            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
2116            .finish(),
2117        column_comments: BTreeMap::new(),
2118        // We use a temporal window of 2 days rather than 1 day for `mz_session_history`'s `connected_at` since a statement execution at
2119        // the edge of the 1 day temporal window could've been executed in a session that was established an hour before the 1 day window.
2120        sql:
2121        "SELECT * FROM mz_internal.mz_activity_log_thinned WHERE prepared_at + INTERVAL '1 day' > mz_now()
2122AND began_at + INTERVAL '1 day' > mz_now() AND connected_at + INTERVAL '2 days' > mz_now()",
2123        access: vec![MONITOR_SELECT],
2124        ontology: None,
2125    }
2126});
2127
2128pub static MZ_RECENT_ACTIVITY_LOG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
2129    name: "mz_recent_activity_log",
2130    schema: MZ_INTERNAL_SCHEMA,
2131    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_OID,
2132    desc: RelationDesc::builder()
2133        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
2134        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
2135        .with_column("cluster_id", SqlScalarType::String.nullable(true))
2136        .with_column("application_name", SqlScalarType::String.nullable(false))
2137        .with_column("cluster_name", SqlScalarType::String.nullable(true))
2138        .with_column("database_name", SqlScalarType::String.nullable(false))
2139        .with_column(
2140            "search_path",
2141            SqlScalarType::List {
2142                element_type: Box::new(SqlScalarType::String),
2143                custom_id: None,
2144            }
2145            .nullable(false),
2146        )
2147        .with_column(
2148            "transaction_isolation",
2149            SqlScalarType::String.nullable(false),
2150        )
2151        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
2152        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
2153        .with_column(
2154            "params",
2155            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
2156        )
2157        .with_column("mz_version", SqlScalarType::String.nullable(false))
2158        .with_column(
2159            "began_at",
2160            SqlScalarType::TimestampTz { precision: None }.nullable(false),
2161        )
2162        .with_column(
2163            "finished_at",
2164            SqlScalarType::TimestampTz { precision: None }.nullable(true),
2165        )
2166        .with_column("finished_status", SqlScalarType::String.nullable(true))
2167        .with_column("error_message", SqlScalarType::String.nullable(true))
2168        .with_column("result_size", SqlScalarType::Int64.nullable(true))
2169        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
2170        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
2171        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
2172        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
2173        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
2174        .with_column(
2175            "prepared_statement_name",
2176            SqlScalarType::String.nullable(false),
2177        )
2178        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
2179        .with_column(
2180            "prepared_at",
2181            SqlScalarType::TimestampTz { precision: None }.nullable(false),
2182        )
2183        .with_column("statement_type", SqlScalarType::String.nullable(true))
2184        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
2185        .with_column(
2186            "connected_at",
2187            SqlScalarType::TimestampTz { precision: None }.nullable(false),
2188        )
2189        .with_column(
2190            "initial_application_name",
2191            SqlScalarType::String.nullable(false),
2192        )
2193        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
2194        .with_column("sql", SqlScalarType::String.nullable(false))
2195        .finish(),
2196    column_comments: BTreeMap::from_iter([
2197        (
2198            "execution_id",
2199            "An ID that is unique for each executed statement.",
2200        ),
2201        (
2202            "sample_rate",
2203            "The actual rate at which the statement was sampled.",
2204        ),
2205        (
2206            "cluster_id",
2207            "The ID of the cluster the statement execution was directed to. Corresponds to mz_clusters.id.",
2208        ),
2209        (
2210            "application_name",
2211            "The value of the `application_name` configuration parameter at execution time.",
2212        ),
2213        (
2214            "cluster_name",
2215            "The name of the cluster with ID `cluster_id` at execution time.",
2216        ),
2217        (
2218            "database_name",
2219            "The value of the `database` configuration parameter at execution time.",
2220        ),
2221        (
2222            "search_path",
2223            "The value of the `search_path` configuration parameter at execution time.",
2224        ),
2225        (
2226            "transaction_isolation",
2227            "The value of the `transaction_isolation` configuration parameter at execution time.",
2228        ),
2229        (
2230            "execution_timestamp",
2231            "The logical timestamp at which execution was scheduled.",
2232        ),
2233        (
2234            "transient_index_id",
2235            "The internal index of the compute dataflow created for the query, if any.",
2236        ),
2237        (
2238            "params",
2239            "The parameters with which the statement was executed.",
2240        ),
2241        (
2242            "mz_version",
2243            "The version of Materialize that was running when the statement was executed.",
2244        ),
2245        (
2246            "began_at",
2247            "The wall-clock time at which the statement began executing.",
2248        ),
2249        (
2250            "finished_at",
2251            "The wall-clock time at which the statement finished executing.",
2252        ),
2253        (
2254            "finished_status",
2255            "The final status of the statement (e.g., `success`, `canceled`, `error`, or `aborted`). \
2256            `aborted` means that the client disconnected before the statement finished executing.",
2257        ),
2258        (
2259            "error_message",
2260            "The error message, if the statement failed.",
2261        ),
2262        (
2263            "result_size",
2264            "The size in bytes of the result, for statements that return rows.",
2265        ),
2266        (
2267            "rows_returned",
2268            "The number of rows returned, for statements that return rows.",
2269        ),
2270        (
2271            "execution_strategy",
2272            "For `SELECT` statements (and similar statement types), the strategy for executing the query. \
2273             `standard` means computed by a temporary dataflow, \
2274             `fast-path` means read by a cluster directly from an in-memory index, \
2275             `persist-fast-path` means read a source, table, or materialized view from blob storage (without an index or dataflow), \
2276             and `constant` means computed in the control plane without the involvement of a cluster. \
2277             (It's `NULL` for statements that errored/canceled/aborted and for non-query-like statement types.)",
2278        ),
2279        (
2280            "transaction_id",
2281            "The ID of the transaction that the statement was part of. Note that transaction IDs are only unique per session.",
2282        ),
2283        (
2284            "prepared_statement_id",
2285            "An ID that is unique for each prepared statement. For example, if a statement is prepared once and then executed multiple times, all executions will have the same value for this column (but different values for `execution_id`).",
2286        ),
2287        (
2288            "sql_hash",
2289            "An opaque value uniquely identifying the text of the query.",
2290        ),
2291        (
2292            "prepared_statement_name",
2293            "The name given by the client library to the prepared statement.",
2294        ),
2295        (
2296            "session_id",
2297            "An ID that is unique for each session. Corresponds to mz_sessions.id.",
2298        ),
2299        (
2300            "prepared_at",
2301            "The time at which the statement was prepared.",
2302        ),
2303        (
2304            "statement_type",
2305            "The _type_ of the statement, e.g. `select` for a `SELECT` query, or `NULL` if the statement was empty.",
2306        ),
2307        (
2308            "throttled_count",
2309            "The number of statement executions dropped due to throttling between the previously logged statement and this one. If you have a very high volume of queries and need to log them without throttling, contact our team.",
2310        ),
2311        (
2312            "connected_at",
2313            "The time at which the session was established.",
2314        ),
2315        (
2316            "initial_application_name",
2317            "The initial value of `application_name` at the beginning of the session.",
2318        ),
2319        (
2320            "authenticated_user",
2321            "The name of the user for which the session was established.",
2322        ),
2323        ("sql", "The SQL text of the statement."),
2324    ]),
2325    sql: "SELECT mralt.*, mrst.sql
2326FROM mz_internal.mz_recent_activity_log_thinned mralt,
2327     mz_internal.mz_recent_sql_text mrst
2328WHERE mralt.sql_hash = mrst.sql_hash",
2329    access: vec![MONITOR_SELECT],
2330    ontology: Some(Ontology {
2331        entity_name: "activity_log",
2332        description: "Recent query activity with execution stats",
2333        links: &const {
2334            [
2335                OntologyLink {
2336                    name: "in_session",
2337                    target: "session",
2338                    properties: LinkProperties::fk("session_id", "id", Cardinality::ManyToOne),
2339                },
2340                OntologyLink {
2341                    name: "in_active_session",
2342                    target: "active_session",
2343                    properties: LinkProperties::fk_nullable(
2344                        "session_id",
2345                        "id",
2346                        Cardinality::ManyToOne,
2347                    ),
2348                },
2349                OntologyLink {
2350                    name: "ran_on_cluster",
2351                    target: "cluster",
2352                    properties: LinkProperties::fk_nullable(
2353                        "cluster_id",
2354                        "id",
2355                        Cardinality::ManyToOne,
2356                    ),
2357                },
2358                OntologyLink {
2359                    name: "used_transient_index",
2360                    target: "object",
2361                    properties: LinkProperties::ForeignKey {
2362                        source_column: "transient_index_id",
2363                        target_column: "id",
2364                        cardinality: Cardinality::ManyToOne,
2365                        source_id_type: Some(mz_repr::SemanticType::GlobalId),
2366                        requires_mapping: Some("mz_internal.mz_object_global_ids"),
2367                        nullable: true,
2368                        note: None,
2369                        extra_key_columns: None,
2370                    },
2371                },
2372            ]
2373        },
2374        column_semantic_types: &const {
2375            [
2376                ("cluster_id", SemanticType::ClusterId),
2377                ("execution_timestamp", SemanticType::MzTimestamp),
2378                ("transient_index_id", SemanticType::GlobalId),
2379                ("began_at", SemanticType::WallclockTimestamp),
2380                ("finished_at", SemanticType::WallclockTimestamp),
2381                ("prepared_at", SemanticType::WallclockTimestamp),
2382                ("connected_at", SemanticType::WallclockTimestamp),
2383                ("sql", SemanticType::SqlDefinition),
2384            ]
2385        },
2386    }),
2387});
2388
2389pub static MZ_RECENT_ACTIVITY_LOG_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
2390    BuiltinView {
2391    name: "mz_recent_activity_log_redacted",
2392    schema: MZ_INTERNAL_SCHEMA,
2393    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_REDACTED_OID,
2394    // Includes all the columns in mz_recent_activity_log_thinned except 'error_message'.
2395    desc: RelationDesc::builder()
2396        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
2397        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
2398        .with_column("cluster_id", SqlScalarType::String.nullable(true))
2399        .with_column("application_name", SqlScalarType::String.nullable(false))
2400        .with_column("cluster_name", SqlScalarType::String.nullable(true))
2401        .with_column("database_name", SqlScalarType::String.nullable(false))
2402        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
2403        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
2404        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
2405        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
2406        .with_column("mz_version", SqlScalarType::String.nullable(false))
2407        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
2408        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
2409        .with_column("finished_status", SqlScalarType::String.nullable(true))
2410        .with_column("result_size", SqlScalarType::Int64.nullable(true))
2411        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
2412        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
2413        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
2414        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
2415        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
2416        .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
2417        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
2418        .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
2419        .with_column("statement_type", SqlScalarType::String.nullable(true))
2420        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
2421        .with_column("initial_application_name", SqlScalarType::String.nullable(false))
2422        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
2423        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
2424        .finish(),
2425    column_comments: BTreeMap::new(),
2426    sql: "SELECT mralt.execution_id, mralt.sample_rate, mralt.cluster_id, mralt.application_name,
2427    mralt.cluster_name, mralt.database_name, mralt.search_path, mralt.transaction_isolation, mralt.execution_timestamp,
2428    mralt.transient_index_id, mralt.mz_version, mralt.began_at, mralt.finished_at,
2429    mralt.finished_status, mralt.result_size, mralt.rows_returned, mralt.execution_strategy, mralt.transaction_id,
2430    mralt.prepared_statement_id, mralt.sql_hash, mralt.prepared_statement_name, mralt.session_id,
2431    mralt.prepared_at, mralt.statement_type, mralt.throttled_count,
2432    mralt.initial_application_name, mralt.authenticated_user,
2433    mrst.redacted_sql
2434FROM mz_internal.mz_recent_activity_log_thinned mralt,
2435     mz_internal.mz_recent_sql_text mrst
2436WHERE mralt.sql_hash = mrst.sql_hash",
2437    access: vec![MONITOR_SELECT, MONITOR_REDACTED_SELECT, SUPPORT_SELECT, ANALYTICS_SELECT],
2438    ontology: None,
2439}
2440});
2441
2442pub static MZ_STATEMENT_LIFECYCLE_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
2443    BuiltinSource {
2444        name: "mz_statement_lifecycle_history",
2445        schema: MZ_INTERNAL_SCHEMA,
2446        oid: oid::SOURCE_MZ_STATEMENT_LIFECYCLE_HISTORY_OID,
2447        desc: RelationDesc::builder()
2448            .with_column("statement_id", SqlScalarType::Uuid.nullable(false))
2449            .with_column("event_type", SqlScalarType::String.nullable(false))
2450            .with_column(
2451                "occurred_at",
2452                SqlScalarType::TimestampTz { precision: None }.nullable(false),
2453            )
2454            .finish(),
2455        data_source: IntrospectionType::StatementLifecycleHistory.into(),
2456        column_comments: BTreeMap::from_iter([
2457            (
2458                "statement_id",
2459                "The ID of the execution event. Corresponds to `mz_recent_activity_log.execution_id`",
2460            ),
2461            (
2462                "event_type",
2463                "The type of lifecycle event, e.g. `'execution-began'`, `'storage-dependencies-finished'`, `'compute-dependencies-finished'`, or `'execution-finished'`",
2464            ),
2465            ("occurred_at", "The time at which the event took place."),
2466        ]),
2467        is_retained_metrics_object: false,
2468        // TODO[btv]: Maybe this should be public instead of
2469        // `MONITOR_REDACTED`, but since that would be a backwards-compatible
2470        // change, we probably don't need to worry about it now.
2471        access: vec![
2472            SUPPORT_SELECT,
2473            ANALYTICS_SELECT,
2474            MONITOR_REDACTED_SELECT,
2475            MONITOR_SELECT,
2476        ],
2477        ontology: Some(Ontology {
2478            entity_name: "statement_lifecycle_event",
2479            description: "Statement lifecycle events (parse, bind, execute)",
2480            links: &const {
2481                [OntologyLink {
2482                    name: "for_execution",
2483                    target: "activity_log",
2484                    properties: LinkProperties::fk(
2485                        "statement_id",
2486                        "execution_id",
2487                        Cardinality::ManyToOne,
2488                    ),
2489                }]
2490            },
2491            column_semantic_types: &[],
2492        }),
2493    }
2494});
2495
2496pub static MZ_SOURCE_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
2497    name: "mz_source_statuses",
2498    schema: MZ_INTERNAL_SCHEMA,
2499    oid: oid::VIEW_MZ_SOURCE_STATUSES_OID,
2500    desc: RelationDesc::builder()
2501        .with_column("id", SqlScalarType::String.nullable(false))
2502        .with_column("name", SqlScalarType::String.nullable(false))
2503        .with_column("type", SqlScalarType::String.nullable(false))
2504        .with_column(
2505            "last_status_change_at",
2506            SqlScalarType::TimestampTz { precision: None }.nullable(true),
2507        )
2508        .with_column("status", SqlScalarType::String.nullable(false))
2509        .with_column("error", SqlScalarType::String.nullable(true))
2510        .with_column("details", SqlScalarType::Jsonb.nullable(true))
2511        .finish(),
2512    column_comments: BTreeMap::from_iter([
2513        (
2514            "id",
2515            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
2516        ),
2517        ("name", "The name of the source."),
2518        ("type", "The type of the source."),
2519        (
2520            "last_status_change_at",
2521            "Wall-clock timestamp of the source status change.",
2522        ),
2523        (
2524            "status",
2525            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, or `dropped`.",
2526        ),
2527        (
2528            "error",
2529            "If the source is in an error state, the error message.",
2530        ),
2531        (
2532            "details",
2533            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
2534        ),
2535    ]),
2536    sql: "
2537    WITH
2538    -- The status history contains per-replica events and source-global events.
2539    -- For the latter, replica_id is NULL. We turn these into '<source>', so that
2540    -- we can treat them uniformly below.
2541    uniform_status_history AS
2542    (
2543        SELECT
2544            s.source_id,
2545            COALESCE(s.replica_id, '<source>') as replica_id,
2546            s.occurred_at,
2547            s.status,
2548            s.error,
2549            s.details
2550        FROM mz_internal.mz_source_status_history s
2551    ),
2552    -- For getting the latest events, we first determine the latest per-replica
2553    -- events here and then apply precedence rules below.
2554    --
2555    -- We ignore per-replica events from replicas that no longer exist. A dropped
2556    -- replica's last reported status is stale: without this filter a defunct
2557    -- replica's lingering 'running' can outrank (see precedence below) a live
2558    -- replica's 'stalled', hiding a genuinely broken source. We always retain
2559    -- source-global events ('<source>' is the sentinel for replica_id NULL)
2560    -- and 'paused' events. A per-replica 'paused' is only written when the
2561    -- replica is dropped, so it is a terminal drop marker, not a stale report.
2562    --
2563    -- The pick carries only key columns and the join fetches error and details
2564    -- for the picked rows, since every TopK level stores the rows it carries.
2565    latest_per_replica_status AS
2566    (
2567        SELECT DISTINCT ON (source_id, replica_id)
2568            source_id, replica_id, occurred_at, status
2569        FROM uniform_status_history
2570        WHERE replica_id = '<source>'
2571            OR replica_id IN (SELECT id FROM mz_catalog.mz_cluster_replicas)
2572            OR status = 'paused'
2573        -- NOTE: Sized for about a day of restart loop (3 rows every ~5 s per
2574        -- replica), since `partially_truncate_status_history` trims only at
2575        -- startup. Past the hint each update rereads group size / 4096 rows.
2576        -- Smaller hints, like the advice view's for healthy histories, reread more.
2577        OPTIONS (DISTINCT ON INPUT GROUP SIZE = 65535)
2578        ORDER BY source_id, replica_id, occurred_at DESC
2579    ),
2580    latest_per_replica_events AS
2581    (
2582        SELECT occurred_at, source_id, replica_id, status, error, details
2583        FROM latest_per_replica_status
2584        JOIN uniform_status_history USING (source_id, replica_id, occurred_at, status)
2585    ),
2586    -- We have a precedence list that determines the overall status in case
2587    -- there is differing per-replica (including source-global) statuses. If
2588    -- there is no 'dropped' status, and any replica reports 'running', the
2589    -- overall status is 'running' even if there might be some replica that has
2590    -- errors or is paused. Precedence ties are broken by recency, so a dropped
2591    -- replica's 'paused' wins over an older source-global 'paused'.
2592    latest_events AS
2593    (
2594       SELECT DISTINCT ON (source_id)
2595            source_id,
2596            occurred_at,
2597            status,
2598            error,
2599            details
2600        FROM latest_per_replica_events
2601        OPTIONS (DISTINCT ON INPUT GROUP SIZE = 255)
2602        ORDER BY source_id, CASE status
2603                    WHEN 'dropped' THEN 1
2604                    WHEN 'running' THEN 2
2605                    WHEN 'stalled' THEN 3
2606                    WHEN 'starting' THEN 4
2607                    WHEN 'paused' THEN 5
2608                    WHEN 'ceased' THEN 6
2609                    ELSE 7  -- For any other status values
2610                END, occurred_at DESC
2611    ),
2612    -- Determine which sources are subsources and which are parent sources
2613    subsources AS
2614    (
2615        SELECT subsources.id AS self, sources.id AS parent
2616        FROM
2617            mz_catalog.mz_sources AS subsources
2618                JOIN
2619                    mz_internal.mz_object_dependencies AS deps
2620                    ON subsources.id = deps.object_id
2621                JOIN mz_catalog.mz_sources AS sources ON sources.id = deps.referenced_object_id
2622    ),
2623    -- Determine which sources are source tables
2624    tables AS
2625    (
2626        SELECT tables.id AS self, tables.source_id AS parent, tables.name
2627        FROM mz_catalog.mz_tables AS tables
2628        WHERE tables.source_id IS NOT NULL
2629    ),
2630    -- Determine which collection's ID to use for the status
2631    id_of_status_to_use AS
2632    (
2633        SELECT
2634            self_events.source_id,
2635            -- If self not errored, but parent is, use parent; else self
2636            CASE
2637                WHEN
2638                    self_events.status <> 'ceased' AND
2639                    parent_events.status = 'stalled'
2640                THEN parent_events.source_id
2641                ELSE self_events.source_id
2642            END AS id_to_use
2643        FROM
2644            latest_events AS self_events
2645                LEFT JOIN subsources ON self_events.source_id = subsources.self
2646                LEFT JOIN tables ON self_events.source_id = tables.self
2647                LEFT JOIN
2648                    latest_events AS parent_events
2649                    ON parent_events.source_id = COALESCE(subsources.parent, tables.parent)
2650    ),
2651    -- Swap out events for the ID of the event we plan to use instead
2652    latest_events_to_use AS
2653    (
2654        SELECT occurred_at, s.source_id, status, error, details
2655        FROM
2656            id_of_status_to_use AS s
2657                JOIN latest_events AS e ON e.source_id = s.id_to_use
2658    ),
2659    combined AS (
2660        SELECT
2661            mz_sources.id,
2662            mz_sources.name,
2663            mz_sources.type,
2664            occurred_at,
2665            status,
2666            error,
2667            details
2668        FROM
2669            mz_catalog.mz_sources
2670            LEFT JOIN latest_events_to_use AS e ON mz_sources.id = e.source_id
2671        UNION ALL
2672        SELECT
2673            tables.self AS id,
2674            tables.name,
2675            'table' AS type,
2676            occurred_at,
2677            status,
2678            error,
2679            details
2680        FROM
2681            tables
2682            LEFT JOIN latest_events_to_use AS e ON tables.self = e.source_id
2683    )
2684SELECT
2685    id,
2686    name,
2687    type,
2688    occurred_at AS last_status_change_at,
2689    -- TODO(parkmycar): Report status of webhook source once database-issues#5986 is closed.
2690    CASE
2691        WHEN
2692            type = 'webhook' OR
2693            type = 'progress'
2694        THEN 'running'
2695        ELSE COALESCE(status, 'created')
2696    END AS status,
2697    error,
2698    details
2699FROM combined
2700WHERE id NOT LIKE 's%';",
2701    access: vec![PUBLIC_SELECT],
2702    ontology: Some(Ontology {
2703        entity_name: "source_status",
2704        description: "Current source status (running, stalled, etc.)",
2705        links: &const {
2706            [OntologyLink {
2707                name: "status_of_source",
2708                target: "source",
2709                properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
2710            }]
2711        },
2712        column_semantic_types: &const {
2713            [
2714                ("id", SemanticType::CatalogItemId),
2715                ("type", SemanticType::SourceType),
2716                ("last_status_change_at", SemanticType::WallclockTimestamp),
2717            ]
2718        },
2719    }),
2720});
2721
2722pub static MZ_SINK_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
2723    name: "mz_sink_status_history",
2724    schema: MZ_INTERNAL_SCHEMA,
2725    oid: oid::SOURCE_MZ_SINK_STATUS_HISTORY_OID,
2726    data_source: IntrospectionType::SinkStatusHistory.into(),
2727    desc: MZ_SINK_STATUS_HISTORY_DESC.clone(),
2728    column_comments: BTreeMap::from_iter([
2729        (
2730            "occurred_at",
2731            "Wall-clock timestamp of the sink status change.",
2732        ),
2733        (
2734            "sink_id",
2735            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
2736        ),
2737        (
2738            "status",
2739            "The status of the sink: one of `starting`, `running`, `paused`, `stalled`, or `dropped`.",
2740        ),
2741        (
2742            "error",
2743            "If the sink is in an error state, the error message.",
2744        ),
2745        (
2746            "details",
2747            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
2748        ),
2749        (
2750            "replica_id",
2751            "The ID of the replica that an instance of a sink is running on.",
2752        ),
2753    ]),
2754    is_retained_metrics_object: false,
2755    access: vec![PUBLIC_SELECT],
2756    ontology: Some(Ontology {
2757        entity_name: "sink_status_event",
2758        description: "Historical sink status events",
2759        links: &const {
2760            [
2761                OntologyLink {
2762                    name: "status_event_of_sink",
2763                    target: "sink",
2764                    properties: LinkProperties::fk_mapped(
2765                        "sink_id",
2766                        "id",
2767                        Cardinality::ManyToOne,
2768                        mz_repr::SemanticType::GlobalId,
2769                        "mz_internal.mz_object_global_ids",
2770                    ),
2771                },
2772                OntologyLink {
2773                    name: "on_replica",
2774                    target: "replica",
2775                    properties: LinkProperties::fk_nullable(
2776                        "replica_id",
2777                        "id",
2778                        Cardinality::ManyToOne,
2779                    ),
2780                },
2781            ]
2782        },
2783        column_semantic_types: &const {
2784            [
2785                ("occurred_at", SemanticType::WallclockTimestamp),
2786                ("sink_id", SemanticType::GlobalId),
2787                ("replica_id", SemanticType::ReplicaId),
2788            ]
2789        },
2790    }),
2791});
2792
2793pub static MZ_SINK_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
2794    name: "mz_sink_statuses",
2795    schema: MZ_INTERNAL_SCHEMA,
2796    oid: oid::VIEW_MZ_SINK_STATUSES_OID,
2797    desc: RelationDesc::builder()
2798        .with_column("id", SqlScalarType::String.nullable(false))
2799        .with_column("name", SqlScalarType::String.nullable(false))
2800        .with_column("type", SqlScalarType::String.nullable(false))
2801        .with_column(
2802            "last_status_change_at",
2803            SqlScalarType::TimestampTz { precision: None }.nullable(true),
2804        )
2805        .with_column("status", SqlScalarType::String.nullable(false))
2806        .with_column("error", SqlScalarType::String.nullable(true))
2807        .with_column("details", SqlScalarType::Jsonb.nullable(true))
2808        .finish(),
2809    column_comments: BTreeMap::from_iter([
2810        (
2811            "id",
2812            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
2813        ),
2814        ("name", "The name of the sink."),
2815        ("type", "The type of the sink."),
2816        (
2817            "last_status_change_at",
2818            "Wall-clock timestamp of the sink status change.",
2819        ),
2820        (
2821            "status",
2822            "The status of the sink: one of `created`, `starting`, `running`, `paused`, `stalled`, or `dropped`.",
2823        ),
2824        (
2825            "error",
2826            "If the sink is in an error state, the error message.",
2827        ),
2828        (
2829            "details",
2830            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
2831        ),
2832    ]),
2833    sql: "
2834WITH
2835-- The status history contains per-replica events and sink-global events.
2836-- For the latter, replica_id is NULL. We turn these into '<sink>', so that
2837-- we can treat them uniformly below.
2838uniform_status_history AS
2839(
2840    SELECT
2841        s.sink_id,
2842        COALESCE(s.replica_id, '<sink>') as replica_id,
2843        s.occurred_at,
2844        s.status,
2845        s.error,
2846        s.details
2847    FROM mz_internal.mz_sink_status_history s
2848),
2849-- For getting the latest events, we first determine the latest per-replica
2850-- events here and then apply precedence rules below.
2851--
2852-- We ignore per-replica events from replicas that no longer exist. A dropped
2853-- replica's last reported status is stale: without this filter a defunct
2854-- replica's lingering 'running' can outrank (see precedence below) a live
2855-- replica's 'stalled', hiding a genuinely broken sink. We always retain
2856-- sink-global events ('<sink>' is the sentinel for replica_id NULL)
2857-- and 'paused' events. A per-replica 'paused' is only written when the
2858-- replica is dropped, so it is a terminal drop marker, not a stale report.
2859--
2860-- The pick carries only key columns and the join fetches error and details
2861-- for the picked rows, since every TopK level stores the rows it carries.
2862latest_per_replica_status AS
2863(
2864    SELECT DISTINCT ON (sink_id, replica_id)
2865        sink_id, replica_id, occurred_at, status
2866    FROM uniform_status_history
2867    WHERE replica_id = '<sink>'
2868        OR replica_id IN (SELECT id FROM mz_catalog.mz_cluster_replicas)
2869        OR status = 'paused'
2870    -- NOTE: Sized for about a day of restart loop (3 rows every ~5 s per
2871    -- replica), since `partially_truncate_status_history` trims only at
2872    -- startup. Past the hint each update rereads group size / 4096 rows.
2873    -- Smaller hints, like the advice view's for healthy histories, reread more.
2874    OPTIONS (DISTINCT ON INPUT GROUP SIZE = 65535)
2875    ORDER BY sink_id, replica_id, occurred_at DESC
2876),
2877latest_per_replica_events AS
2878(
2879    SELECT occurred_at, sink_id, replica_id, status, error, details
2880    FROM latest_per_replica_status
2881    JOIN uniform_status_history USING (sink_id, replica_id, occurred_at, status)
2882),
2883-- We have a precedence list that determines the overall status in case
2884-- there is differing per-replica (including sink-global) statuses. If
2885-- there is no 'dropped' status, and any replica reports 'running', the
2886-- overall status is 'running' even if there might be some replica that has
2887-- errors or is paused. Precedence ties are broken by recency, so a dropped
2888-- replica's 'paused' wins over an older sink-global 'paused'.
2889latest_events AS
2890(
2891    SELECT DISTINCT ON (sink_id)
2892        sink_id,
2893        occurred_at,
2894        status,
2895        error,
2896        details
2897    FROM latest_per_replica_events
2898    OPTIONS (DISTINCT ON INPUT GROUP SIZE = 255)
2899    ORDER BY sink_id, CASE status
2900                WHEN 'dropped' THEN 1
2901                WHEN 'running' THEN 2
2902                WHEN 'stalled' THEN 3
2903                WHEN 'starting' THEN 4
2904                WHEN 'paused' THEN 5
2905                WHEN 'ceased' THEN 6
2906                ELSE 7  -- For any other status values
2907            END, occurred_at DESC
2908)
2909SELECT
2910    mz_sinks.id,
2911    name,
2912    mz_sinks.type,
2913    occurred_at as last_status_change_at,
2914    coalesce(status, 'created') as status,
2915    error,
2916    details
2917FROM mz_catalog.mz_sinks
2918LEFT JOIN latest_events ON mz_sinks.id = latest_events.sink_id
2919WHERE
2920    -- This is a convenient way to filter out system sinks, like the status_history table itself.
2921    mz_sinks.id NOT LIKE 's%'",
2922    access: vec![PUBLIC_SELECT],
2923    ontology: Some(Ontology {
2924        entity_name: "sink_status",
2925        description: "Current sink status",
2926        links: &const {
2927            [OntologyLink {
2928                name: "status_of_sink",
2929                target: "sink",
2930                properties: LinkProperties::fk_typed(
2931                    "id",
2932                    "id",
2933                    Cardinality::OneToOne,
2934                    mz_repr::SemanticType::CatalogItemId,
2935                ),
2936            }]
2937        },
2938        column_semantic_types: &const {
2939            [
2940                ("id", SemanticType::CatalogItemId),
2941                ("last_status_change_at", SemanticType::WallclockTimestamp),
2942            ]
2943        },
2944    }),
2945});
2946
2947pub static MZ_STORAGE_USAGE_BY_SHARD: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2948    name: "mz_storage_usage_by_shard",
2949    schema: MZ_INTERNAL_SCHEMA,
2950    oid: oid::TABLE_MZ_STORAGE_USAGE_BY_SHARD_OID,
2951    desc: RelationDesc::builder()
2952        .with_column("id", SqlScalarType::UInt64.nullable(false))
2953        .with_column("shard_id", SqlScalarType::String.nullable(true))
2954        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
2955        .with_column(
2956            "collection_timestamp",
2957            SqlScalarType::TimestampTz { precision: None }.nullable(false),
2958        )
2959        .finish(),
2960    column_comments: BTreeMap::new(),
2961    is_retained_metrics_object: false,
2962    access: vec![PUBLIC_SELECT],
2963    ontology: Some(Ontology {
2964        entity_name: "storage_usage_by_shard",
2965        description: "Storage usage broken down by shard",
2966        links: &const { [] },
2967        column_semantic_types: &const {
2968            [
2969                ("shard_id", SemanticType::ShardId),
2970                ("size_bytes", SemanticType::ByteCount),
2971                ("collection_timestamp", SemanticType::WallclockTimestamp),
2972            ]
2973        },
2974    }),
2975});
2976
2977// Reads Item rows from `mz_catalog_raw`, pulls the create_sql-derived fields
2978// (endpoint, region, credentials, assume-role options) out via
2979// `parse_connection_details`, and keeps only aws connections. The three
2980// context-derived columns (principal, external_id, example_trust_policy) apply
2981// to assume-role connections only and are reconstructed here from the plan-time
2982// AWS context functions, because they depend on the environment, not on
2983// create_sql. On an environment without the AWS context an assume-role
2984// connection is dropped entirely (see the WHERE guard below), matching the
2985// packer this view replaces, which bailed and wrote no row in that case. This
2986// is not the same as folding the columns to NULL: `example_trust_policy` uses
2987// `jsonb_build_object`, which keeps null values, so a context-less row would
2988// carry a non-NULL policy object full of nulls rather than SQL NULL.
2989pub static MZ_AWS_CONNECTIONS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
2990    BuiltinMaterializedView {
2991        name: "mz_aws_connections",
2992        schema: MZ_INTERNAL_SCHEMA,
2993        oid: oid::MV_MZ_AWS_CONNECTIONS_OID,
2994        desc: RelationDesc::builder()
2995            .with_column("id", SqlScalarType::String.nullable(false))
2996            .with_column("endpoint", SqlScalarType::String.nullable(true))
2997            .with_column("region", SqlScalarType::String.nullable(true))
2998            .with_column("access_key_id", SqlScalarType::String.nullable(true))
2999            .with_column(
3000                "access_key_id_secret_id",
3001                SqlScalarType::String.nullable(true),
3002            )
3003            .with_column(
3004                "secret_access_key_secret_id",
3005                SqlScalarType::String.nullable(true),
3006            )
3007            .with_column("session_token", SqlScalarType::String.nullable(true))
3008            .with_column(
3009                "session_token_secret_id",
3010                SqlScalarType::String.nullable(true),
3011            )
3012            .with_column("assume_role_arn", SqlScalarType::String.nullable(true))
3013            .with_column(
3014                "assume_role_session_name",
3015                SqlScalarType::String.nullable(true),
3016            )
3017            .with_column("principal", SqlScalarType::String.nullable(true))
3018            .with_column("external_id", SqlScalarType::String.nullable(true))
3019            .with_column("example_trust_policy", SqlScalarType::Jsonb.nullable(true))
3020            .with_key(vec![0])
3021            .finish(),
3022        column_comments: BTreeMap::from_iter([
3023            ("id", "The ID of the connection."),
3024            ("endpoint", "The value of the `ENDPOINT` option, if set."),
3025            ("region", "The value of the `REGION` option, if set."),
3026            (
3027                "access_key_id",
3028                "The value of the `ACCESS KEY ID` option, if provided in line.",
3029            ),
3030            (
3031                "access_key_id_secret_id",
3032                "The ID of the secret referenced by the `ACCESS KEY ID` option, if provided via a secret.",
3033            ),
3034            (
3035                "secret_access_key_secret_id",
3036                "The ID of the secret referenced by the `SECRET ACCESS KEY` option, if set.",
3037            ),
3038            (
3039                "session_token",
3040                "The value of the `SESSION TOKEN` option, if provided in line.",
3041            ),
3042            (
3043                "session_token_secret_id",
3044                "The ID of the secret referenced by the `SESSION TOKEN` option, if provided via a secret.",
3045            ),
3046            (
3047                "assume_role_arn",
3048                "The value of the `ASSUME ROLE ARN` option, if set.",
3049            ),
3050            (
3051                "assume_role_session_name",
3052                "The value of the `ASSUME ROLE SESSION NAME` option, if set.",
3053            ),
3054            (
3055                "principal",
3056                "The ARN of the AWS principal Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
3057            ),
3058            (
3059                "external_id",
3060                "The external ID Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
3061            ),
3062            (
3063                "example_trust_policy",
3064                "An example of an IAM role trust policy that allows this connection's principal and external ID to assume the role.",
3065            ),
3066        ]),
3067        // `external_id` reproduces `AwsAssumeRole::external_id` and
3068        // `example_trust_policy` reproduces `AwsAssumeRole::example_trust_policy`
3069        // (both in src/storage-types/src/connections/aws.rs). Keep them in sync.
3070        sql: "
3071IN CLUSTER mz_catalog_server
3072WITH (
3073    ASSERT NOT NULL id
3074) AS
3075SELECT
3076    mz_internal.parse_catalog_id(r.data->'key'->'gid') AS id,
3077    details->>'endpoint' AS endpoint,
3078    details->>'region' AS region,
3079    details->>'access_key_id' AS access_key_id,
3080    details->>'access_key_id_secret_id' AS access_key_id_secret_id,
3081    details->>'secret_access_key_secret_id' AS secret_access_key_secret_id,
3082    details->>'session_token' AS session_token,
3083    details->>'session_token_secret_id' AS session_token_secret_id,
3084    details->>'assume_role_arn' AS assume_role_arn,
3085    details->>'assume_role_session_name' AS assume_role_session_name,
3086    CASE WHEN details->>'auth_kind' = 'assume-role'
3087        THEN mz_aws_connection_role_arn()
3088    END AS principal,
3089    CASE WHEN details->>'auth_kind' = 'assume-role'
3090        THEN 'mz_' || mz_aws_external_id_prefix() || '_'
3091            || mz_internal.parse_catalog_id(r.data->'key'->'gid')
3092    END AS external_id,
3093    CASE WHEN details->>'auth_kind' = 'assume-role'
3094        THEN jsonb_build_object(
3095            'Version', '2012-10-17',
3096            'Statement', jsonb_build_array(jsonb_build_object(
3097                'Effect', 'Allow',
3098                'Principal', jsonb_build_object('AWS', mz_aws_connection_role_arn()),
3099                'Action', 'sts:AssumeRole',
3100                'Condition', jsonb_build_object(
3101                    'StringEquals', jsonb_build_object(
3102                        'sts:ExternalId',
3103                        'mz_' || mz_aws_external_id_prefix() || '_'
3104                            || mz_internal.parse_catalog_id(r.data->'key'->'gid')
3105                    )
3106                )
3107            ))
3108        )
3109    END AS example_trust_policy
3110FROM
3111    mz_internal.mz_catalog_raw r,
3112    LATERAL (
3113        SELECT mz_internal.parse_connection_details(
3114            r.data->'value'->'definition'->'V1'->>'create_sql')
3115    ) AS d(details)
3116WHERE
3117    r.data->>'kind' = 'Item' AND
3118    -- The connection_type filter selects the kind. A non-matching row yields a
3119    -- NULL connection_type and is dropped here, so no `details IS NOT NULL` is
3120    -- needed (parse_connection_details returns jsonb null, which passes it).
3121    mz_internal.parse_catalog_create_sql(
3122        r.data->'value'->'definition'->'V1'->>'create_sql')->>'connection_type' = 'aws' AND
3123    -- Drop assume-role connections when the AWS context is absent, matching the
3124    -- packer this view replaces. `AwsAssumeRole::external_id` needs the external
3125    -- ID prefix and `example_trust_policy` needs the connection role ARN. Either
3126    -- one missing made the packer bail and write no row. Without this guard the
3127    -- view would instead emit a row whose `example_trust_policy` is a non-NULL
3128    -- JSON object full of nulls, because `jsonb_build_object` keeps null values.
3129    (
3130        details->>'auth_kind' IS DISTINCT FROM 'assume-role' OR (
3131            mz_aws_external_id_prefix() IS NOT NULL AND
3132            mz_aws_connection_role_arn() IS NOT NULL
3133        )
3134    )",
3135        is_retained_metrics_object: false,
3136        access: vec![PUBLIC_SELECT],
3137        ontology: Some(Ontology {
3138            entity_name: "aws_connection",
3139            description: "AWS connection configuration details",
3140            links: &const {
3141                [OntologyLink {
3142                    name: "details_of",
3143                    target: "connection",
3144                    properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
3145                }]
3146            },
3147            column_semantic_types: &[],
3148        }),
3149    }
3150});
3151
3152pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY: LazyLock<BuiltinSource> =
3153    LazyLock::new(|| BuiltinSource {
3154        name: "mz_cluster_replica_metrics_history",
3155        schema: MZ_INTERNAL_SCHEMA,
3156        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
3157        data_source: IntrospectionType::ReplicaMetricsHistory.into(),
3158        desc: REPLICA_METRICS_HISTORY_DESC.clone(),
3159        column_comments: BTreeMap::from_iter([
3160            ("replica_id", "The ID of a cluster replica."),
3161            ("process_id", "The ID of a process within the replica."),
3162            (
3163                "cpu_nano_cores",
3164                "Approximate CPU usage, in billionths of a vCPU core.",
3165            ),
3166            ("memory_bytes", "Approximate memory usage, in bytes."),
3167            ("disk_bytes", "Approximate disk usage, in bytes."),
3168            (
3169                "occurred_at",
3170                "Wall-clock timestamp at which the event occurred.",
3171            ),
3172            (
3173                "heap_bytes",
3174                "Approximate heap (RAM + swap) usage, in bytes.",
3175            ),
3176            ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
3177            ("swap_bytes", "Approximate swap usage, in bytes."),
3178        ]),
3179        is_retained_metrics_object: false,
3180        access: vec![PUBLIC_SELECT],
3181        ontology: None,
3182    });
3183
3184pub static MZ_CLUSTER_REPLICA_METRICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3185    name: "mz_cluster_replica_metrics",
3186    schema: MZ_INTERNAL_SCHEMA,
3187    oid: oid::VIEW_MZ_CLUSTER_REPLICA_METRICS_OID,
3188    desc: RelationDesc::builder()
3189        .with_column("replica_id", SqlScalarType::String.nullable(false))
3190        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
3191        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(true))
3192        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(true))
3193        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
3194        .with_column("heap_bytes", SqlScalarType::UInt64.nullable(true))
3195        .with_column("heap_limit", SqlScalarType::UInt64.nullable(true))
3196        .with_column("swap_bytes", SqlScalarType::UInt64.nullable(true))
3197        .with_key(vec![0, 1])
3198        .finish(),
3199    column_comments: BTreeMap::from_iter([
3200        ("replica_id", "The ID of a cluster replica."),
3201        ("process_id", "The ID of a process within the replica."),
3202        (
3203            "cpu_nano_cores",
3204            "Approximate CPU usage, in billionths of a vCPU core.",
3205        ),
3206        ("memory_bytes", "Approximate RAM usage, in bytes."),
3207        ("disk_bytes", "Approximate disk usage, in bytes."),
3208        (
3209            "heap_bytes",
3210            "Approximate heap (RAM + swap) usage, in bytes.",
3211        ),
3212        ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
3213        ("swap_bytes", "Approximate swap usage, in bytes."),
3214    ]),
3215    sql: "
3216SELECT
3217    DISTINCT ON (replica_id, process_id)
3218    replica_id,
3219    process_id,
3220    cpu_nano_cores,
3221    memory_bytes,
3222    disk_bytes,
3223    heap_bytes,
3224    heap_limit,
3225    swap_bytes
3226FROM mz_internal.mz_cluster_replica_metrics_history
3227JOIN mz_cluster_replicas r ON r.id = replica_id
3228ORDER BY replica_id, process_id, occurred_at DESC",
3229    access: vec![PUBLIC_SELECT],
3230    ontology: Some(Ontology {
3231        entity_name: "replica_metrics",
3232        description: "CPU and memory metrics per replica",
3233        links: &const {
3234            [OntologyLink {
3235                name: "metrics_of_replica",
3236                target: "replica",
3237                properties: LinkProperties::fk_typed(
3238                    "replica_id",
3239                    "id",
3240                    Cardinality::OneToOne,
3241                    mz_repr::SemanticType::CatalogItemId,
3242                ),
3243            }]
3244        },
3245        column_semantic_types: &const {
3246            [
3247                ("replica_id", SemanticType::ReplicaId),
3248                ("memory_bytes", SemanticType::ByteCount),
3249                ("disk_bytes", SemanticType::ByteCount),
3250                ("heap_bytes", SemanticType::ByteCount),
3251                ("heap_limit", SemanticType::ByteCount),
3252                ("swap_bytes", SemanticType::ByteCount),
3253            ]
3254        },
3255    }),
3256});
3257
3258pub static MZ_FRONTIERS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3259    name: "mz_frontiers",
3260    schema: MZ_INTERNAL_SCHEMA,
3261    oid: oid::SOURCE_MZ_FRONTIERS_OID,
3262    data_source: IntrospectionType::Frontiers.into(),
3263    desc: RelationDesc::builder()
3264        .with_column("object_id", SqlScalarType::String.nullable(false))
3265        .with_column("read_frontier", SqlScalarType::MzTimestamp.nullable(true))
3266        .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
3267        .finish(),
3268    column_comments: BTreeMap::from_iter([
3269        (
3270            "object_id",
3271            "The ID of the source, sink, table, index, materialized view, or subscription.",
3272        ),
3273        (
3274            "read_frontier",
3275            "The earliest timestamp at which the output is still readable.",
3276        ),
3277        (
3278            "write_frontier",
3279            "The next timestamp at which the output may change.",
3280        ),
3281    ]),
3282    is_retained_metrics_object: false,
3283    access: vec![PUBLIC_SELECT],
3284    ontology: Some(Ontology {
3285        entity_name: "frontier",
3286        description: "Current read/write frontiers for sources, sinks, tables, materialized views, indexes, and subscriptions",
3287        links: &const {
3288            [OntologyLink {
3289                name: "frontier_of",
3290                target: "object",
3291                properties: LinkProperties::fk_mapped(
3292                    "object_id",
3293                    "id",
3294                    Cardinality::ManyToOne,
3295                    mz_repr::SemanticType::GlobalId,
3296                    "mz_internal.mz_object_global_ids",
3297                ),
3298            }]
3299        },
3300        column_semantic_types: &const {
3301            [
3302                ("object_id", SemanticType::GlobalId),
3303                ("read_frontier", SemanticType::MzTimestamp),
3304                ("write_frontier", SemanticType::MzTimestamp),
3305            ]
3306        },
3307    }),
3308});
3309
3310/// DEPRECATED and scheduled for removal! Use `mz_frontiers` instead.
3311pub static MZ_GLOBAL_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3312    name: "mz_global_frontiers",
3313    schema: MZ_INTERNAL_SCHEMA,
3314    oid: oid::VIEW_MZ_GLOBAL_FRONTIERS_OID,
3315    desc: RelationDesc::builder()
3316        .with_column("object_id", SqlScalarType::String.nullable(false))
3317        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
3318        .finish(),
3319    column_comments: BTreeMap::new(),
3320    sql: "
3321SELECT object_id, write_frontier AS time
3322FROM mz_internal.mz_frontiers
3323WHERE write_frontier IS NOT NULL",
3324    access: vec![PUBLIC_SELECT],
3325    ontology: None,
3326});
3327
3328pub static MZ_WALLCLOCK_LAG_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
3329    name: "mz_wallclock_lag_history",
3330    schema: MZ_INTERNAL_SCHEMA,
3331    oid: oid::SOURCE_MZ_WALLCLOCK_LAG_HISTORY_OID,
3332    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
3333    data_source: IntrospectionType::WallclockLagHistory.into(),
3334    column_comments: BTreeMap::from_iter([
3335        (
3336            "object_id",
3337            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
3338        ),
3339        (
3340            "replica_id",
3341            "The ID of a replica computing the object, or `NULL` for persistent objects. Corresponds to `mz_cluster_replicas.id`.",
3342        ),
3343        (
3344            "lag",
3345            "The amount of time the object's write frontier lags behind wallclock time.",
3346        ),
3347        (
3348            "occurred_at",
3349            "Wall-clock timestamp at which the event occurred.",
3350        ),
3351    ]),
3352    is_retained_metrics_object: false,
3353    access: vec![PUBLIC_SELECT],
3354    ontology: Some(Ontology {
3355        entity_name: "wallclock_lag_event",
3356        description: "Historical wallclock lag per object",
3357        links: &const {
3358            [
3359                OntologyLink {
3360                    name: "measures_lag_of",
3361                    target: "object",
3362                    properties: LinkProperties::measures_mapped(
3363                        "object_id",
3364                        "id",
3365                        "wallclock_lag",
3366                        mz_repr::SemanticType::GlobalId,
3367                        "mz_internal.mz_object_global_ids",
3368                    ),
3369                },
3370                OntologyLink {
3371                    name: "on_replica",
3372                    target: "replica",
3373                    properties: LinkProperties::fk_nullable(
3374                        "replica_id",
3375                        "id",
3376                        Cardinality::ManyToOne,
3377                    ),
3378                },
3379            ]
3380        },
3381        column_semantic_types: &const {
3382            [
3383                ("object_id", SemanticType::GlobalId),
3384                ("replica_id", SemanticType::ReplicaId),
3385                ("occurred_at", SemanticType::WallclockTimestamp),
3386            ]
3387        },
3388    }),
3389});
3390
3391pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3392    name: "mz_wallclock_global_lag_history",
3393    schema: MZ_INTERNAL_SCHEMA,
3394    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTORY_OID,
3395    desc: RelationDesc::builder()
3396        .with_column("object_id", SqlScalarType::String.nullable(false))
3397        .with_column("lag", SqlScalarType::Interval.nullable(true))
3398        .with_column(
3399            "occurred_at",
3400            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3401        )
3402        .with_key(vec![0, 2])
3403        .finish(),
3404    column_comments: BTreeMap::from_iter([
3405        (
3406            "object_id",
3407            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
3408        ),
3409        (
3410            "lag",
3411            "The minimum wallclock lag observed for the object during the minute.",
3412        ),
3413        (
3414            "occurred_at",
3415            "The minute-aligned timestamp of the observation.",
3416        ),
3417    ]),
3418    sql: "
3419WITH times_binned AS (
3420    SELECT
3421        object_id,
3422        lag,
3423        date_trunc('minute', occurred_at) AS occurred_at
3424    FROM mz_internal.mz_wallclock_lag_history
3425)
3426SELECT
3427    object_id,
3428    min(lag) AS lag,
3429    occurred_at
3430FROM times_binned
3431GROUP BY object_id, occurred_at
3432OPTIONS (AGGREGATE INPUT GROUP SIZE = 1)",
3433    access: vec![PUBLIC_SELECT],
3434    ontology: Some(Ontology {
3435        entity_name: "wallclock_global_lag_event",
3436        description: "Historical global wallclock lag",
3437        links: &const {
3438            [OntologyLink {
3439                name: "lag_of",
3440                target: "object_global_id",
3441                properties: LinkProperties::fk("object_id", "global_id", Cardinality::ManyToOne),
3442            }]
3443        },
3444        column_semantic_types: &const {
3445            [
3446                ("object_id", SemanticType::GlobalId),
3447                ("occurred_at", SemanticType::WallclockTimestamp),
3448            ]
3449        },
3450    }),
3451});
3452
3453pub static MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| {
3454    BuiltinView {
3455        name: "mz_wallclock_global_lag_recent_history",
3456        schema: MZ_INTERNAL_SCHEMA,
3457        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_OID,
3458        desc: RelationDesc::builder()
3459            .with_column("object_id", SqlScalarType::String.nullable(false))
3460            .with_column("lag", SqlScalarType::Interval.nullable(true))
3461            .with_column(
3462                "occurred_at",
3463                SqlScalarType::TimestampTz { precision: None }.nullable(false),
3464            )
3465            .with_key(vec![0, 2])
3466            .finish(),
3467        column_comments: BTreeMap::from_iter([
3468            (
3469                "object_id",
3470                "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
3471            ),
3472            (
3473                "lag",
3474                "The minimum wallclock lag observed for the object during the minute.",
3475            ),
3476            (
3477                "occurred_at",
3478                "The minute-aligned timestamp of the observation.",
3479            ),
3480        ]),
3481        sql: "
3482SELECT object_id, lag, occurred_at
3483FROM mz_internal.mz_wallclock_global_lag_history
3484WHERE occurred_at + '1 day' > mz_now()",
3485        access: vec![PUBLIC_SELECT],
3486        ontology: None,
3487    }
3488});
3489
3490pub static MZ_WALLCLOCK_GLOBAL_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3491    name: "mz_wallclock_global_lag",
3492    schema: MZ_INTERNAL_SCHEMA,
3493    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_OID,
3494    desc: RelationDesc::builder()
3495        .with_column("object_id", SqlScalarType::String.nullable(false))
3496        .with_column("lag", SqlScalarType::Interval.nullable(true))
3497        .with_key(vec![0])
3498        .finish(),
3499    column_comments: BTreeMap::from_iter([
3500        (
3501            "object_id",
3502            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
3503        ),
3504        (
3505            "lag",
3506            "The amount of time the object's write frontier lags behind wallclock time.",
3507        ),
3508    ]),
3509    sql: "
3510SELECT DISTINCT ON (object_id) object_id, lag
3511FROM mz_internal.mz_wallclock_global_lag_recent_history
3512WHERE occurred_at + '5 minutes' > mz_now()
3513ORDER BY object_id, occurred_at DESC",
3514    access: vec![PUBLIC_SELECT],
3515    ontology: Some(Ontology {
3516        entity_name: "wallclock_global_lag",
3517        description: "Current wallclock lag aggregated across replicas",
3518        links: &const {
3519            [OntologyLink {
3520                name: "measures_global_lag_of",
3521                target: "object",
3522                properties: LinkProperties::measures_mapped(
3523                    "object_id",
3524                    "id",
3525                    "wallclock_lag_global",
3526                    mz_repr::SemanticType::GlobalId,
3527                    "mz_internal.mz_object_global_ids",
3528                ),
3529            }]
3530        },
3531        column_semantic_types: &[("object_id", SemanticType::GlobalId)],
3532    }),
3533});
3534
3535pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW: LazyLock<BuiltinSource> =
3536    LazyLock::new(|| BuiltinSource {
3537        name: "mz_wallclock_global_lag_histogram_raw",
3538        schema: MZ_INTERNAL_SCHEMA,
3539        oid: oid::SOURCE_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_OID,
3540        desc: WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC.clone(),
3541        column_comments: BTreeMap::new(),
3542        data_source: IntrospectionType::WallclockLagHistogram.into(),
3543        is_retained_metrics_object: false,
3544        access: vec![PUBLIC_SELECT],
3545        ontology: None,
3546    });
3547
3548pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM: LazyLock<BuiltinView> =
3549    LazyLock::new(|| BuiltinView {
3550        name: "mz_wallclock_global_lag_histogram",
3551        schema: MZ_INTERNAL_SCHEMA,
3552        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_OID,
3553        desc: RelationDesc::builder()
3554            .with_column(
3555                "period_start",
3556                SqlScalarType::TimestampTz { precision: None }.nullable(false),
3557            )
3558            .with_column(
3559                "period_end",
3560                SqlScalarType::TimestampTz { precision: None }.nullable(false),
3561            )
3562            .with_column("object_id", SqlScalarType::String.nullable(false))
3563            .with_column("lag_seconds", SqlScalarType::UInt64.nullable(true))
3564            .with_column("labels", SqlScalarType::Jsonb.nullable(false))
3565            .with_column("count", SqlScalarType::Int64.nullable(false))
3566            .with_key(vec![0, 1, 2, 3, 4])
3567            .finish(),
3568        column_comments: BTreeMap::new(),
3569        sql: "
3570SELECT *, count(*) AS count
3571FROM mz_internal.mz_wallclock_global_lag_histogram_raw
3572GROUP BY period_start, period_end, object_id, lag_seconds, labels",
3573        access: vec![PUBLIC_SELECT],
3574        ontology: None,
3575    });
3576
3577pub static MZ_MATERIALIZED_VIEW_REFRESHES: LazyLock<BuiltinSource> = LazyLock::new(|| {
3578    BuiltinSource {
3579        name: "mz_materialized_view_refreshes",
3580        schema: MZ_INTERNAL_SCHEMA,
3581        oid: oid::SOURCE_MZ_MATERIALIZED_VIEW_REFRESHES_OID,
3582        data_source: DataSourceDesc::Introspection(
3583            IntrospectionType::ComputeMaterializedViewRefreshes,
3584        ),
3585        desc: RelationDesc::builder()
3586            .with_column(
3587                "materialized_view_id",
3588                SqlScalarType::String.nullable(false),
3589            )
3590            .with_column(
3591                "last_completed_refresh",
3592                SqlScalarType::MzTimestamp.nullable(true),
3593            )
3594            .with_column("next_refresh", SqlScalarType::MzTimestamp.nullable(true))
3595            .finish(),
3596        column_comments: BTreeMap::from_iter([
3597            (
3598                "materialized_view_id",
3599                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
3600            ),
3601            (
3602                "last_completed_refresh",
3603                "The time of the last successfully completed refresh. `NULL` if the materialized view hasn't completed any refreshes yet.",
3604            ),
3605            (
3606                "next_refresh",
3607                "The time of the next scheduled refresh. `NULL` if the materialized view has no future scheduled refreshes.",
3608            ),
3609        ]),
3610        is_retained_metrics_object: false,
3611        access: vec![PUBLIC_SELECT],
3612        ontology: None,
3613    }
3614});
3615
3616pub static MZ_SUBSCRIPTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3617    name: "mz_subscriptions",
3618    schema: MZ_INTERNAL_SCHEMA,
3619    oid: oid::TABLE_MZ_SUBSCRIPTIONS_OID,
3620    desc: RelationDesc::builder()
3621        .with_column("id", SqlScalarType::String.nullable(false))
3622        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
3623        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3624        .with_column(
3625            "created_at",
3626            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3627        )
3628        .with_column(
3629            "referenced_object_ids",
3630            SqlScalarType::List {
3631                element_type: Box::new(SqlScalarType::String),
3632                custom_id: None,
3633            }
3634            .nullable(false),
3635        )
3636        .finish(),
3637    column_comments: BTreeMap::from_iter([
3638        ("id", "The ID of the subscription."),
3639        (
3640            "session_id",
3641            "The ID of the session that runs the subscription. Corresponds to `mz_sessions.id`.",
3642        ),
3643        (
3644            "cluster_id",
3645            "The ID of the cluster on which the subscription is running. Corresponds to `mz_clusters.id`.",
3646        ),
3647        (
3648            "created_at",
3649            "The time at which the subscription was created.",
3650        ),
3651        (
3652            "referenced_object_ids",
3653            "The IDs of objects referenced by the subscription. Corresponds to `mz_objects.id`",
3654        ),
3655    ]),
3656    is_retained_metrics_object: false,
3657    access: vec![PUBLIC_SELECT],
3658    ontology: Some(Ontology {
3659        entity_name: "subscription",
3660        description: "Active SUBSCRIBE operations",
3661        links: &const {
3662            [
3663                OntologyLink {
3664                    name: "uses_session",
3665                    target: "session",
3666                    properties: LinkProperties::fk("session_id", "id", Cardinality::ManyToOne),
3667                },
3668                OntologyLink {
3669                    name: "in_active_session",
3670                    target: "active_session",
3671                    properties: LinkProperties::fk_nullable(
3672                        "session_id",
3673                        "id",
3674                        Cardinality::ManyToOne,
3675                    ),
3676                },
3677                OntologyLink {
3678                    name: "belongs_to_cluster",
3679                    target: "cluster",
3680                    properties: LinkProperties::fk("cluster_id", "id", Cardinality::ManyToOne),
3681                },
3682            ]
3683        },
3684        column_semantic_types: &const {
3685            [
3686                ("id", SemanticType::CatalogItemId),
3687                ("cluster_id", SemanticType::ClusterId),
3688            ]
3689        },
3690    }),
3691});
3692
3693pub static MZ_SESSIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3694    name: "mz_sessions",
3695    schema: MZ_INTERNAL_SCHEMA,
3696    oid: oid::TABLE_MZ_SESSIONS_OID,
3697    desc: RelationDesc::builder()
3698        .with_column("id", SqlScalarType::Uuid.nullable(false))
3699        .with_column("connection_id", SqlScalarType::UInt32.nullable(false))
3700        .with_column("role_id", SqlScalarType::String.nullable(false))
3701        .with_column("client_ip", SqlScalarType::String.nullable(true))
3702        .with_column(
3703            "connected_at",
3704            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3705        )
3706        .finish(),
3707    column_comments: BTreeMap::from_iter([
3708        ("id", "The globally unique ID of the session."),
3709        (
3710            "connection_id",
3711            "The connection ID of the session. Unique only for active sessions and can be recycled. Corresponds to `pg_backend_pid()`.",
3712        ),
3713        (
3714            "role_id",
3715            "The role ID of the role that the session is logged in as. Corresponds to `mz_catalog.mz_roles`.",
3716        ),
3717        (
3718            "client_ip",
3719            "The IP address of the client that initiated the session.",
3720        ),
3721        (
3722            "connected_at",
3723            "The time at which the session connected to the system.",
3724        ),
3725    ]),
3726    is_retained_metrics_object: false,
3727    access: vec![PUBLIC_SELECT],
3728    ontology: Some(Ontology {
3729        entity_name: "active_session",
3730        description: "Currently active sessions",
3731        links: &const {
3732            [OntologyLink {
3733                name: "logged_in_as",
3734                target: "role",
3735                properties: LinkProperties::fk("role_id", "id", Cardinality::ManyToOne),
3736            }]
3737        },
3738        column_semantic_types: &[("role_id", SemanticType::RoleId)],
3739    }),
3740});
3741
3742pub static MZ_OVERRIDDEN_SYSTEM_PARAMETERS: LazyLock<BuiltinMaterializedView> =
3743    LazyLock::new(|| BuiltinMaterializedView {
3744        name: "mz_overridden_system_parameters",
3745        schema: MZ_INTERNAL_SCHEMA,
3746        oid: oid::MV_MZ_OVERRIDDEN_SYSTEM_PARAMETERS_OID,
3747        desc: RelationDesc::builder()
3748            .with_column("name", SqlScalarType::String.nullable(false))
3749            .with_column("value", SqlScalarType::String.nullable(false))
3750            .finish(),
3751        column_comments: BTreeMap::from_iter([
3752            ("name", "The name of the system parameter."),
3753            (
3754                "value",
3755                "The environment-wide value of the system parameter.",
3756            ),
3757        ]),
3758        // Projects the durable `system_configurations` collection (the
3759        // `ALTER SYSTEM` set) out of `mz_catalog_raw` (the durable catalog as
3760        // JSON): the key is `{name}` and the value is `{value}`. This surfaces
3761        // only parameters with an explicit environment-wide override, mirroring
3762        // the cluster- and replica-scoped views. Parameters left at their
3763        // default are absent.
3764        sql: "
3765IN CLUSTER mz_catalog_server
3766WITH (
3767    ASSERT NOT NULL name,
3768    ASSERT NOT NULL value
3769) AS
3770SELECT
3771    data->'key'->>'name' AS name,
3772    data->'value'->>'value' AS value
3773FROM mz_internal.mz_catalog_raw
3774WHERE data->>'kind' = 'ServerConfiguration'",
3775        is_retained_metrics_object: false,
3776        access: vec![PUBLIC_SELECT],
3777        ontology: Some(Ontology {
3778            entity_name: "system_parameter",
3779            description: "Environment-wide system parameter overrides",
3780            links: &const { [] },
3781            column_semantic_types: &[],
3782        }),
3783    });
3784
3785pub static MZ_CLUSTER_SYSTEM_PARAMETERS: LazyLock<BuiltinMaterializedView> =
3786    LazyLock::new(|| BuiltinMaterializedView {
3787        name: "mz_cluster_system_parameters",
3788        schema: MZ_INTERNAL_SCHEMA,
3789        oid: oid::MV_MZ_CLUSTER_SYSTEM_PARAMETERS_OID,
3790        desc: RelationDesc::builder()
3791            .with_column("cluster_id", SqlScalarType::String.nullable(false))
3792            .with_column("name", SqlScalarType::String.nullable(false))
3793            .with_column("value", SqlScalarType::String.nullable(false))
3794            .finish(),
3795        column_comments: BTreeMap::from_iter([
3796            (
3797                "cluster_id",
3798                "The ID of the cluster. Corresponds to `mz_clusters.id`.",
3799            ),
3800            ("name", "The name of the cluster-coherent system parameter."),
3801            ("value", "The cluster-scoped value of the system parameter."),
3802        ]),
3803        // Projects the durable `cluster_system_configurations` collection out of
3804        // `mz_catalog_raw` (the durable catalog as JSON): the key is
3805        // `{cluster_id, name}` and the value is `{value}`.
3806        sql: "
3807IN CLUSTER mz_catalog_server
3808WITH (
3809    ASSERT NOT NULL cluster_id,
3810    ASSERT NOT NULL name,
3811    ASSERT NOT NULL value
3812) AS
3813SELECT
3814    mz_internal.parse_catalog_id(data->'key'->'cluster_id') AS cluster_id,
3815    data->'key'->>'name' AS name,
3816    data->'value'->>'value' AS value
3817FROM mz_internal.mz_catalog_raw
3818WHERE data->>'kind' = 'ClusterSystemConfiguration'",
3819        is_retained_metrics_object: false,
3820        access: vec![PUBLIC_SELECT],
3821        ontology: Some(Ontology {
3822            entity_name: "cluster_system_parameter",
3823            description: "Cluster-coherent system parameter overrides",
3824            links: &const {
3825                [OntologyLink {
3826                    name: "scoped_to_cluster",
3827                    target: "cluster",
3828                    properties: LinkProperties::fk_typed(
3829                        "cluster_id",
3830                        "id",
3831                        Cardinality::ManyToOne,
3832                        mz_repr::SemanticType::ClusterId,
3833                    ),
3834                }]
3835            },
3836            column_semantic_types: &[("cluster_id", SemanticType::ClusterId)],
3837        }),
3838    });
3839
3840pub static MZ_REPLICA_SYSTEM_PARAMETERS: LazyLock<BuiltinMaterializedView> =
3841    LazyLock::new(|| BuiltinMaterializedView {
3842        name: "mz_replica_system_parameters",
3843        schema: MZ_INTERNAL_SCHEMA,
3844        oid: oid::MV_MZ_REPLICA_SYSTEM_PARAMETERS_OID,
3845        desc: RelationDesc::builder()
3846            .with_column("replica_id", SqlScalarType::String.nullable(false))
3847            .with_column("name", SqlScalarType::String.nullable(false))
3848            .with_column("value", SqlScalarType::String.nullable(false))
3849            .finish(),
3850        column_comments: BTreeMap::from_iter([
3851            (
3852                "replica_id",
3853                "The ID of the cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3854            ),
3855            ("name", "The name of the replica-local system parameter."),
3856            ("value", "The replica-scoped value of the system parameter."),
3857        ]),
3858        // Projects the durable `replica_system_configurations` collection out of
3859        // `mz_catalog_raw` (the durable catalog as JSON): the key is
3860        // `{replica_id, name}` and the value is `{value}`.
3861        sql: "
3862IN CLUSTER mz_catalog_server
3863WITH (
3864    ASSERT NOT NULL replica_id,
3865    ASSERT NOT NULL name,
3866    ASSERT NOT NULL value
3867) AS
3868SELECT
3869    mz_internal.parse_catalog_id(data->'key'->'replica_id') AS replica_id,
3870    data->'key'->>'name' AS name,
3871    data->'value'->>'value' AS value
3872FROM mz_internal.mz_catalog_raw
3873WHERE data->>'kind' = 'ReplicaSystemConfiguration'",
3874        is_retained_metrics_object: false,
3875        access: vec![PUBLIC_SELECT],
3876        ontology: Some(Ontology {
3877            entity_name: "replica_system_parameter",
3878            description: "Replica-local system parameter overrides",
3879            links: &const {
3880                [OntologyLink {
3881                    name: "scoped_to_replica",
3882                    target: "replica",
3883                    properties: LinkProperties::fk_typed(
3884                        "replica_id",
3885                        "id",
3886                        Cardinality::ManyToOne,
3887                        mz_repr::SemanticType::ReplicaId,
3888                    ),
3889                }]
3890            },
3891            column_semantic_types: &[("replica_id", SemanticType::ReplicaId)],
3892        }),
3893    });
3894
3895pub static MZ_COMMENTS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3896    BuiltinMaterializedView {
3897        name: "mz_comments",
3898        schema: MZ_INTERNAL_SCHEMA,
3899        oid: oid::MV_MZ_COMMENTS_OID,
3900        desc: RelationDesc::builder()
3901            .with_column("id", SqlScalarType::String.nullable(false))
3902            .with_column("object_type", SqlScalarType::String.nullable(false))
3903            .with_column("object_sub_id", SqlScalarType::Int32.nullable(true))
3904            .with_column("comment", SqlScalarType::String.nullable(false))
3905            .finish(),
3906        column_comments: BTreeMap::from_iter([
3907            (
3908                "id",
3909                "The ID of the object. Corresponds to `mz_objects.id`.",
3910            ),
3911            (
3912                "object_type",
3913                "The type of object the comment is associated with.",
3914            ),
3915            (
3916                "object_sub_id",
3917                "For a comment on a column of a relation, the column number. `NULL` for other object types.",
3918            ),
3919            ("comment", "The comment itself."),
3920        ]),
3921        // Variant keys ('Table', 'View', etc.) are the serde JSON form of
3922        // `proto::CommentObject` (in `mz-catalog-protos`). `object_type`
3923        // values are the kebab-case `Display` of `audit_log::ObjectType`.
3924        //
3925        // Schema and ClusterReplica are nested structs in `mz_catalog_raw`.
3926        // We reach one level deeper for them: Schema picks `schema.Id` and
3927        // drops the database, ClusterReplica picks `replica_id` and drops
3928        // the cluster. That matches what `mz_objects.id` holds for those
3929        // rows.
3930        //
3931        // New variants on `proto::CommentObject` need branches in both CASE
3932        // expressions below.
3933        sql: "
3934IN CLUSTER mz_catalog_server
3935WITH (
3936    ASSERT NOT NULL id,
3937    ASSERT NOT NULL object_type,
3938    ASSERT NOT NULL comment
3939) AS
3940WITH commented AS (
3941    SELECT data->'key'->'object' AS obj,
3942           data->'key'->'sub_component' AS sub,
3943           data->'value'->>'comment' AS comment
3944    FROM mz_internal.mz_catalog_raw
3945    WHERE data->>'kind' = 'Comment'
3946)
3947SELECT
3948    CASE
3949        WHEN obj ? 'Table'            THEN mz_internal.parse_catalog_id(obj->'Table')
3950        WHEN obj ? 'View'             THEN mz_internal.parse_catalog_id(obj->'View')
3951        WHEN obj ? 'MaterializedView' THEN mz_internal.parse_catalog_id(obj->'MaterializedView')
3952        WHEN obj ? 'Source'           THEN mz_internal.parse_catalog_id(obj->'Source')
3953        WHEN obj ? 'Sink'             THEN mz_internal.parse_catalog_id(obj->'Sink')
3954        WHEN obj ? 'Index'            THEN mz_internal.parse_catalog_id(obj->'Index')
3955        WHEN obj ? 'Func'             THEN mz_internal.parse_catalog_id(obj->'Func')
3956        WHEN obj ? 'Connection'       THEN mz_internal.parse_catalog_id(obj->'Connection')
3957        WHEN obj ? 'Type'             THEN mz_internal.parse_catalog_id(obj->'Type')
3958        WHEN obj ? 'Secret'           THEN mz_internal.parse_catalog_id(obj->'Secret')
3959        WHEN obj ? 'Role'             THEN mz_internal.parse_catalog_id(obj->'Role')
3960        WHEN obj ? 'Database'         THEN mz_internal.parse_catalog_id(obj->'Database')
3961        WHEN obj ? 'Schema'           THEN mz_internal.parse_catalog_id(obj->'Schema'->'schema'->'Id')
3962        WHEN obj ? 'Cluster'          THEN mz_internal.parse_catalog_id(obj->'Cluster')
3963        WHEN obj ? 'ClusterReplica'   THEN mz_internal.parse_catalog_id(obj->'ClusterReplica'->'replica_id')
3964        WHEN obj ? 'NetworkPolicy'    THEN mz_internal.parse_catalog_id(obj->'NetworkPolicy')
3965        WHEN obj ? 'QueryPolicy'      THEN mz_internal.parse_catalog_id(obj->'QueryPolicy')
3966    END                                                              AS id,
3967    CASE
3968        WHEN obj ? 'Table'            THEN 'table'
3969        WHEN obj ? 'View'             THEN 'view'
3970        WHEN obj ? 'MaterializedView' THEN 'materialized-view'
3971        WHEN obj ? 'Source'           THEN 'source'
3972        WHEN obj ? 'Sink'             THEN 'sink'
3973        WHEN obj ? 'Index'            THEN 'index'
3974        WHEN obj ? 'Func'             THEN 'func'
3975        WHEN obj ? 'Connection'       THEN 'connection'
3976        WHEN obj ? 'Type'             THEN 'type'
3977        WHEN obj ? 'Secret'           THEN 'secret'
3978        WHEN obj ? 'Role'             THEN 'role'
3979        WHEN obj ? 'Database'         THEN 'database'
3980        WHEN obj ? 'Schema'           THEN 'schema'
3981        WHEN obj ? 'Cluster'          THEN 'cluster'
3982        WHEN obj ? 'ClusterReplica'   THEN 'cluster-replica'
3983        WHEN obj ? 'NetworkPolicy'    THEN 'network-policy'
3984        WHEN obj ? 'QueryPolicy'      THEN 'query-policy'
3985    END                                                              AS object_type,
3986    (sub->'ColumnPos')::int4                                          AS object_sub_id,
3987    comment
3988FROM commented",
3989        is_retained_metrics_object: false,
3990        access: vec![PUBLIC_SELECT],
3991        ontology: Some(Ontology {
3992            entity_name: "comment",
3993            description: "A COMMENT ON annotation for a catalog object or column",
3994            links: &const {
3995                [OntologyLink {
3996                    name: "comment_on",
3997                    target: "object",
3998                    properties: LinkProperties::fk_typed(
3999                        "id",
4000                        "id",
4001                        Cardinality::ManyToOne,
4002                        mz_repr::SemanticType::CatalogItemId,
4003                    ),
4004                }]
4005            },
4006            column_semantic_types: &const {
4007                [
4008                    ("id", SemanticType::CatalogItemId),
4009                    ("object_type", SemanticType::ObjectType),
4010                ]
4011            },
4012        }),
4013    }
4014});
4015
4016pub static MZ_SOURCE_REFERENCES: LazyLock<BuiltinMaterializedView> =
4017    LazyLock::new(|| BuiltinMaterializedView {
4018        name: "mz_source_references",
4019        schema: MZ_INTERNAL_SCHEMA,
4020        oid: oid::MV_MZ_SOURCE_REFERENCES_OID,
4021        desc: RelationDesc::builder()
4022            .with_column("source_id", SqlScalarType::String.nullable(false))
4023            .with_column("namespace", SqlScalarType::String.nullable(true))
4024            .with_column("name", SqlScalarType::String.nullable(false))
4025            .with_column(
4026                "updated_at",
4027                SqlScalarType::TimestampTz { precision: None }.nullable(false),
4028            )
4029            .with_column(
4030                "columns",
4031                SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
4032            )
4033            .finish(),
4034        column_comments: BTreeMap::new(),
4035        sql: "
4036IN CLUSTER mz_catalog_server
4037WITH (
4038    ASSERT NOT NULL source_id,
4039    ASSERT NOT NULL name,
4040    ASSERT NOT NULL updated_at
4041) AS
4042-- `refs` projects away usage of the `data` column before the `columns` subquery.
4043-- Without the CTE, each row would need a copy of `data` which contains all source
4044-- references, leading to memory growing quadratically.
4045WITH refs AS (
4046    SELECT
4047        mz_internal.parse_catalog_id(data->'key'->'source') AS source_id,
4048        -- `updated_at` is an `EpochMillis`, serialized as `{\"millis\": <u64>}`
4049        to_timestamp(((data->'value'->'updated_at'->>'millis')::double) / 1000.0) AS updated_at,
4050        reference
4051    FROM
4052        mz_internal.mz_catalog_raw,
4053        jsonb_array_elements(data->'value'->'references') AS reference
4054    WHERE data->>'kind' = 'SourceReferences'
4055)
4056SELECT
4057    source_id,
4058    reference->>'namespace' AS namespace,
4059    reference->>'name' AS name,
4060    updated_at,
4061    (
4062        SELECT array_agg(c.value ORDER BY c.ord)
4063        FROM jsonb_array_elements_text(reference->'columns')
4064             WITH ORDINALITY AS c(value, ord)
4065    ) AS columns
4066FROM refs",
4067        is_retained_metrics_object: false,
4068        access: vec![PUBLIC_SELECT],
4069        ontology: Some(Ontology {
4070            entity_name: "source_reference",
4071            description: "External references tracked by sources",
4072            links: &const {
4073                [OntologyLink {
4074                    name: "references_source",
4075                    target: "source",
4076                    properties: LinkProperties::fk("source_id", "id", Cardinality::ManyToOne),
4077                }]
4078            },
4079            column_semantic_types: &[("source_id", SemanticType::CatalogItemId)],
4080        }),
4081    });
4082
4083pub static MZ_WEBHOOKS_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4084    name: "mz_webhook_sources",
4085    schema: MZ_INTERNAL_SCHEMA,
4086    oid: oid::TABLE_MZ_WEBHOOK_SOURCES_OID,
4087    desc: RelationDesc::builder()
4088        .with_column("id", SqlScalarType::String.nullable(false))
4089        .with_column("name", SqlScalarType::String.nullable(false))
4090        .with_column("url", SqlScalarType::String.nullable(false))
4091        .finish(),
4092    column_comments: BTreeMap::from_iter([
4093        (
4094            "id",
4095            "The ID of the webhook source. Corresponds to `mz_sources.id`.",
4096        ),
4097        ("name", "The name of the webhook source."),
4098        (
4099            "url",
4100            "The URL which can be used to send events to the source.",
4101        ),
4102    ]),
4103    is_retained_metrics_object: false,
4104    access: vec![PUBLIC_SELECT],
4105    ontology: Some(Ontology {
4106        entity_name: "webhook_source",
4107        description: "Webhook source configuration",
4108        links: &const {
4109            [OntologyLink {
4110                name: "details_of",
4111                target: "source",
4112                properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
4113            }]
4114        },
4115        column_semantic_types: &[("id", SemanticType::CatalogItemId)],
4116    }),
4117});
4118
4119pub static MZ_METRIC_SINKS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
4120    BuiltinMaterializedView {
4121        name: "mz_metric_sinks",
4122        schema: MZ_INTERNAL_SCHEMA,
4123        oid: oid::MV_MZ_METRIC_SINKS_OID,
4124        desc: RelationDesc::builder()
4125            .with_column("id", SqlScalarType::String.nullable(false))
4126            .with_column("oid", SqlScalarType::Oid.nullable(false))
4127            .with_column("schema_id", SqlScalarType::String.nullable(false))
4128            .with_column("name", SqlScalarType::String.nullable(false))
4129            .with_column("from_id", SqlScalarType::String.nullable(false))
4130            .with_column("cluster_id", SqlScalarType::String.nullable(false))
4131            .with_column("owner_id", SqlScalarType::String.nullable(false))
4132            .with_key(vec![0])
4133            .with_key(vec![1])
4134            .finish(),
4135        column_comments: BTreeMap::from_iter([
4136            ("id", "Materialize's unique ID for the metric sink."),
4137            ("oid", "A PostgreSQL-compatible OID for the metric sink."),
4138            (
4139                "schema_id",
4140                "The ID of the schema to which the metric sink belongs. Corresponds to `mz_schemas.id`.",
4141            ),
4142            ("name", "The name of the metric sink."),
4143            (
4144                "from_id",
4145                "The ID of the relation the metric sink reads. Corresponds to `mz_objects.id`.",
4146            ),
4147            (
4148                "cluster_id",
4149                "The ID of the cluster maintaining the metric sink. Corresponds to `mz_clusters.id`.",
4150            ),
4151            (
4152                "owner_id",
4153                "The role ID of the owner of the metric sink. Corresponds to `mz_roles.id`.",
4154            ),
4155        ]),
4156        sql: "
4157IN CLUSTER mz_catalog_server
4158WITH (
4159    ASSERT NOT NULL id,
4160    ASSERT NOT NULL oid,
4161    ASSERT NOT NULL schema_id,
4162    ASSERT NOT NULL name,
4163    ASSERT NOT NULL from_id,
4164    ASSERT NOT NULL cluster_id,
4165    ASSERT NOT NULL owner_id
4166) AS
4167SELECT
4168    mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
4169    (data->'value'->>'oid')::oid AS oid,
4170    mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,
4171    data->'value'->>'name' AS name,
4172    parsed->>'from_id' AS from_id,
4173    parsed->>'cluster_id' AS cluster_id,
4174    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id
4175FROM
4176    mz_internal.mz_catalog_raw
4177    CROSS JOIN LATERAL (
4178        SELECT mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')
4179    ) AS l(parsed)
4180WHERE
4181    data->>'kind' = 'Item' AND
4182    parsed->>'type' = 'metric-sink'",
4183        is_retained_metrics_object: false,
4184        access: vec![PUBLIC_SELECT],
4185        ontology: Some(Ontology {
4186            entity_name: "metric-sink",
4187            description: "A sink that exports metrics about a relation",
4188            links: &const {
4189                [
4190                    OntologyLink {
4191                        name: "in_schema",
4192                        target: "schema",
4193                        properties: LinkProperties::fk("schema_id", "id", Cardinality::ManyToOne),
4194                    },
4195                    OntologyLink {
4196                        name: "reads_relation",
4197                        target: "relation",
4198                        properties: LinkProperties::fk("from_id", "id", Cardinality::ManyToOne),
4199                    },
4200                    OntologyLink {
4201                        name: "runs_on_cluster",
4202                        target: "cluster",
4203                        properties: LinkProperties::fk("cluster_id", "id", Cardinality::ManyToOne),
4204                    },
4205                    OntologyLink {
4206                        name: "owned_by",
4207                        target: "role",
4208                        properties: LinkProperties::fk("owner_id", "id", Cardinality::ManyToOne),
4209                    },
4210                ]
4211            },
4212            column_semantic_types: &const {
4213                [
4214                    ("id", SemanticType::CatalogItemId),
4215                    ("oid", SemanticType::OID),
4216                    ("schema_id", SemanticType::SchemaId),
4217                    ("from_id", SemanticType::CatalogItemId),
4218                    ("cluster_id", SemanticType::ClusterId),
4219                    ("owner_id", SemanticType::RoleId),
4220                ]
4221            },
4222        }),
4223    }
4224});
4225
4226pub const MZ_METRIC_SINKS_IND: BuiltinIndex = BuiltinIndex {
4227    name: "mz_metric_sinks_ind",
4228    schema: MZ_INTERNAL_SCHEMA,
4229    oid: oid::INDEX_MZ_METRIC_SINKS_IND_OID,
4230    sql: "IN CLUSTER mz_catalog_server
4231ON mz_internal.mz_metric_sinks (id)",
4232    is_retained_metrics_object: false,
4233};
4234
4235pub static MZ_HISTORY_RETENTION_STRATEGIES: LazyLock<BuiltinMaterializedView> = LazyLock::new(
4236    || {
4237        // Both defaults are compiled in and inlined into the SQL, so changing either
4238        // moves this view's fingerprint and needs a replacement migration step.
4239        let default_window_millis = u64::from(CompactionWindow::Default.comparable_timestamp());
4240        let metrics_retention_millis = METRICS_RETENTION
4241            .default_value()
4242            .as_any()
4243            .downcast_ref::<Duration>()
4244            .expect("metrics_retention is a duration")
4245            .as_millis();
4246        BuiltinMaterializedView {
4247            name: "mz_history_retention_strategies",
4248            schema: MZ_INTERNAL_SCHEMA,
4249            oid: oid::MV_MZ_HISTORY_RETENTION_STRATEGIES_OID,
4250            desc: RelationDesc::builder()
4251                .with_column("id", SqlScalarType::String.nullable(false))
4252                .with_column("strategy", SqlScalarType::String.nullable(false))
4253                .with_column("value", SqlScalarType::Jsonb.nullable(false))
4254                .finish(),
4255            column_comments: BTreeMap::from_iter([
4256                ("id", "The ID of the object."),
4257                (
4258                    "strategy",
4259                    "The strategy. `FOR` is the only strategy, and means the object's compaction window is the duration of the `value` field.",
4260                ),
4261                (
4262                    "value",
4263                    "The value of the strategy. For `FOR`, is a number of milliseconds.",
4264                ),
4265            ]),
4266            sql: Box::leak(format!("
4267IN CLUSTER mz_catalog_server
4268WITH (
4269    ASSERT NOT NULL id,
4270    ASSERT NOT NULL strategy,
4271    ASSERT NOT NULL value
4272) AS
4273WITH
4274    items AS (
4275        SELECT id, details->'retain_history_millis' AS millis
4276        FROM (
4277            SELECT
4278                mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
4279                mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql') AS details
4280            FROM mz_internal.mz_catalog_raw
4281            WHERE data->>'kind' = 'Item'
4282        )
4283        WHERE details->>'type' IN ('table', 'source', 'subsource', 'index', 'materialized-view')
4284    ),
4285    builtins AS (
4286        SELECT object_type, schema_name, name, is_retained_metrics_object FROM mz_internal.mz_builtin_tables
4287        UNION ALL SELECT object_type, schema_name, name, is_retained_metrics_object FROM mz_internal.mz_builtin_sources WHERE type <> 'log'
4288        UNION ALL SELECT object_type, schema_name, name, is_retained_metrics_object FROM mz_internal.mz_builtin_indexes
4289        UNION ALL SELECT object_type, schema_name, name, is_retained_metrics_object FROM mz_internal.mz_builtin_materialized_views
4290    ),
4291    builtin_windows AS (
4292        /*
4293        A builtin has no `create_sql`: it follows the `metrics_retention` system
4294        parameter when flagged as a retained-metrics object, and has the default
4295        window otherwise. Only a durable override of `metrics_retention` is
4296        visible here, one set through `ALTER SYSTEM` or the system parameter
4297        sync. A value passed as `--system-parameter-default` never reaches
4298        `mz_overridden_system_parameters`, so retained-metrics builtins then
4299        report the compiled-in default. No relation exposes effective parameter
4300        values yet, see SQL-757.
4301        */
4302        SELECT
4303            's' || (gm.data->'value'->>'catalog_id') AS id,
4304            CASE
4305                WHEN b.is_retained_metrics_object THEN coalesce(
4306                    (
4307                        SELECT floor(EXTRACT(EPOCH FROM value::interval) * 1000)::int8
4308                        FROM mz_internal.mz_overridden_system_parameters
4309                        WHERE name = 'metrics_retention'
4310                    ),
4311                    {metrics_retention_millis}
4312                )
4313                ELSE {default_window_millis}::int8
4314            END AS millis
4315        FROM builtins b
4316        JOIN mz_internal.mz_catalog_raw gm ON
4317            gm.data->>'kind' = 'GidMapping' AND
4318            gm.data->'key'->>'object_type' = b.object_type AND
4319            gm.data->'key'->>'schema_name' = b.schema_name AND
4320            gm.data->'key'->>'object_name' = b.name
4321    ),
4322    introspection_indexes AS (
4323        SELECT 'si' || (data->'value'->>'catalog_id') AS id
4324        FROM mz_internal.mz_catalog_raw
4325        WHERE data->>'kind' = 'ClusterIntrospectionSourceIndex'
4326    )
4327-- FOR is the only strategy at the moment. We may introduce FROM or others later.
4328SELECT id, 'FOR' AS strategy, coalesce(millis, to_jsonb({default_window_millis}::int8)) AS value FROM items
4329UNION ALL SELECT id, 'FOR', to_jsonb(millis) FROM builtin_windows
4330-- An introspection source index always has the default window.
4331UNION ALL SELECT id, 'FOR', to_jsonb({default_window_millis}::int8) FROM introspection_indexes").into_boxed_str()),
4332            is_retained_metrics_object: false,
4333            access: vec![PUBLIC_SELECT],
4334            ontology: Some(Ontology {
4335                entity_name: "history_retention",
4336                description: "History retention strategy for an object",
4337                links: &const { [] },
4338                column_semantic_types: &[("id", SemanticType::CatalogItemId)],
4339            }),
4340        }
4341    },
4342);
4343
4344pub static MZ_LICENSE_KEYS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4345    name: "mz_license_keys",
4346    schema: MZ_INTERNAL_SCHEMA,
4347    oid: oid::TABLE_MZ_LICENSE_KEYS_OID,
4348    desc: RelationDesc::builder()
4349        .with_column("id", SqlScalarType::String.nullable(false))
4350        .with_column("organization", SqlScalarType::String.nullable(false))
4351        .with_column("environment_id", SqlScalarType::String.nullable(false))
4352        .with_column(
4353            "expiration",
4354            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4355        )
4356        .with_column(
4357            "not_before",
4358            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4359        )
4360        .finish(),
4361    column_comments: BTreeMap::from_iter([
4362        ("id", "The identifier of the license key."),
4363        (
4364            "organization",
4365            "The name of the organization that this license key was issued to.",
4366        ),
4367        (
4368            "environment_id",
4369            "The environment ID that this license key was issued for.",
4370        ),
4371        (
4372            "expiration",
4373            "The date and time when this license key expires.",
4374        ),
4375        (
4376            "not_before",
4377            "The start of the validity period for this license key.",
4378        ),
4379    ]),
4380    is_retained_metrics_object: false,
4381    access: vec![PUBLIC_SELECT],
4382    ontology: Some(Ontology {
4383        entity_name: "license_key",
4384        description: "License key metadata",
4385        links: &const { [] },
4386        column_semantic_types: &[("id", SemanticType::CatalogItemId)],
4387    }),
4388});
4389
4390pub static MZ_REPLACEMENTS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
4391    BuiltinMaterializedView {
4392        name: "mz_replacements",
4393        schema: MZ_INTERNAL_SCHEMA,
4394        oid: oid::MV_MZ_REPLACEMENTS_OID,
4395        desc: RelationDesc::builder()
4396            .with_column("id", SqlScalarType::String.nullable(false))
4397            .with_column("target_id", SqlScalarType::String.nullable(false))
4398            .finish(),
4399        column_comments: BTreeMap::from_iter([
4400            (
4401                "id",
4402                "The ID of the replacement object. Corresponds to `mz_objects.id`.",
4403            ),
4404            (
4405                "target_id",
4406                "The ID of the replacement target. Corresponds to `mz_objects.id`.",
4407            ),
4408        ]),
4409        // A replacement object records its target as `REPLACEMENT FOR <id>` in its
4410        // `create_sql`. Use `parse_catalog_create_sql` to extract `target_id`.
4411        sql: "
4412IN CLUSTER mz_catalog_server
4413WITH (
4414    ASSERT NOT NULL id,
4415    ASSERT NOT NULL target_id
4416) AS
4417SELECT
4418    mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
4419    parsed->>'replacement_target' AS target_id
4420FROM
4421    mz_internal.mz_catalog_raw
4422    CROSS JOIN LATERAL (
4423        SELECT mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')
4424    ) AS l(parsed)
4425WHERE
4426    data->>'kind' = 'Item' AND
4427    parsed->>'replacement_target' IS NOT NULL",
4428    is_retained_metrics_object: false,
4429    access: vec![PUBLIC_SELECT],
4430    ontology: Some(Ontology {
4431        entity_name: "replacement",
4432        description: "A record of an object replacement (ALTER ... SWAP)",
4433        links: &const {
4434            [
4435                OntologyLink {
4436                    name: "replacement_object",
4437                    target: "object",
4438                    properties: LinkProperties::fk("id", "id", Cardinality::ManyToOne),
4439                },
4440                OntologyLink {
4441                    name: "replacement_target",
4442                    target: "object",
4443                    properties: LinkProperties::fk("target_id", "id", Cardinality::ManyToOne),
4444                },
4445            ]
4446        },
4447        column_semantic_types: &[("id", SemanticType::CatalogItemId)],
4448    }),
4449}
4450});
4451
4452// These will be replaced with per-replica tables once source/sink multiplexing on
4453// a single cluster is supported.
4454pub static MZ_SOURCE_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4455    name: "mz_source_statistics_raw",
4456    schema: MZ_INTERNAL_SCHEMA,
4457    oid: oid::SOURCE_MZ_SOURCE_STATISTICS_RAW_OID,
4458    data_source: IntrospectionType::StorageSourceStatistics.into(),
4459    desc: MZ_SOURCE_STATISTICS_RAW_DESC.clone(),
4460    column_comments: BTreeMap::new(),
4461    is_retained_metrics_object: true,
4462    access: vec![PUBLIC_SELECT],
4463    ontology: None,
4464});
4465pub static MZ_SINK_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4466    name: "mz_sink_statistics_raw",
4467    schema: MZ_INTERNAL_SCHEMA,
4468    oid: oid::SOURCE_MZ_SINK_STATISTICS_RAW_OID,
4469    data_source: IntrospectionType::StorageSinkStatistics.into(),
4470    desc: MZ_SINK_STATISTICS_RAW_DESC.clone(),
4471    column_comments: BTreeMap::new(),
4472    is_retained_metrics_object: true,
4473    access: vec![PUBLIC_SELECT],
4474    ontology: None,
4475});
4476
4477pub static MZ_STORAGE_SHARDS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4478    name: "mz_storage_shards",
4479    schema: MZ_INTERNAL_SCHEMA,
4480    oid: oid::SOURCE_MZ_STORAGE_SHARDS_OID,
4481    data_source: IntrospectionType::ShardMapping.into(),
4482    desc: RelationDesc::builder()
4483        .with_column("object_id", SqlScalarType::String.nullable(false))
4484        .with_column("shard_id", SqlScalarType::String.nullable(false))
4485        .finish(),
4486    column_comments: BTreeMap::new(),
4487    is_retained_metrics_object: false,
4488    access: vec![PUBLIC_SELECT],
4489    ontology: Some(Ontology {
4490        entity_name: "storage_shard",
4491        description: "Persist shards used by storage objects",
4492        links: &const {
4493            [OntologyLink {
4494                name: "shard_of",
4495                target: "object",
4496                properties: LinkProperties::fk_mapped(
4497                    "object_id",
4498                    "id",
4499                    Cardinality::ManyToOne,
4500                    mz_repr::SemanticType::GlobalId,
4501                    "mz_internal.mz_object_global_ids",
4502                ),
4503            }]
4504        },
4505        column_semantic_types: &const {
4506            [
4507                ("object_id", SemanticType::GlobalId),
4508                ("shard_id", SemanticType::ShardId),
4509            ]
4510        },
4511    }),
4512});
4513
4514pub static MZ_OBJECTS_ID_NAMESPACE_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4515    name: "mz_objects_id_namespace_types",
4516    schema: MZ_INTERNAL_SCHEMA,
4517    oid: oid::VIEW_MZ_OBJECTS_ID_NAMESPACE_TYPES_OID,
4518    desc: RelationDesc::builder()
4519        .with_column("object_type", SqlScalarType::String.nullable(false))
4520        .with_key(vec![0])
4521        .finish(),
4522    column_comments: BTreeMap::new(),
4523    sql: r#"SELECT *
4524    FROM (
4525        VALUES
4526            ('table'),
4527            ('view'),
4528            ('materialized-view'),
4529            ('source'),
4530            ('sink'),
4531            ('metric-sink'),
4532            ('index'),
4533            ('connection'),
4534            ('type'),
4535            ('function'),
4536            ('secret')
4537    )
4538    AS _ (object_type)"#,
4539    access: vec![PUBLIC_SELECT],
4540    ontology: None,
4541});
4542
4543/// Object dependency edges. Each row `(object_id, dependency_id)` means
4544/// `object_id` depends on `dependency_id`.
4545///
4546/// Unions the dataflow dependencies between maintained objects (index,
4547/// materialized view, sink, source, table) with the source-to-subsource and
4548/// source-to-table edges that connect a source to the children carrying its
4549/// data. Indexed on `mz_catalog_server` so the console surfaces that walk the
4550/// dependency graph read one maintained arrangement instead of recomputing the
4551/// union per request: the object workflow graph, critical-path freshness
4552/// analysis, and impact/dependents views.
4553pub static MZ_OBJECT_GRAPH_EDGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4554    name: "mz_object_graph_edges",
4555    schema: MZ_INTERNAL_SCHEMA,
4556    oid: oid::VIEW_MZ_OBJECT_GRAPH_EDGES_OID,
4557    desc: RelationDesc::builder()
4558        .with_column("object_id", SqlScalarType::String.nullable(false))
4559        .with_column("dependency_id", SqlScalarType::String.nullable(false))
4560        .with_key(vec![0, 1])
4561        .finish(),
4562    column_comments: BTreeMap::from_iter([
4563        (
4564            "object_id",
4565            "The ID of the dependent object. Corresponds to `mz_objects.id`.",
4566        ),
4567        (
4568            "dependency_id",
4569            "The ID of the object it depends on. Corresponds to `mz_objects.id`.",
4570        ),
4571    ]),
4572    sql: "
4573SELECT md.object_id, md.dependency_id
4574FROM mz_internal.mz_materialization_dependencies md
4575JOIN mz_catalog.mz_objects po ON po.id = md.dependency_id
4576    AND po.type IN ('index', 'materialized-view', 'sink', 'source', 'table')
4577JOIN mz_catalog.mz_objects co ON co.id = md.object_id
4578    AND co.type IN ('index', 'materialized-view', 'sink', 'source', 'table')
4579UNION
4580-- Subsource -> parent-source edges: a subsource depends on the (user) source it
4581-- belongs to, an edge mz_materialization_dependencies doesn't carry.
4582SELECT od.object_id, od.referenced_object_id
4583FROM mz_internal.mz_object_dependencies od
4584JOIN mz_catalog.mz_sources ps ON ps.id = od.referenced_object_id
4585JOIN mz_catalog.mz_sources cs ON cs.id = od.object_id
4586-- Progress collections are deliberately left out: their dependency edge points
4587-- source -> progress, and they only exist for old-syntax sources, which the
4588-- source-table migration is removing.
4589WHERE ps.id LIKE 'u%' AND cs.type = 'subsource'
4590UNION
4591-- Select the (non-null) source id from the join rather than the nullable
4592-- mz_tables.source_id, so dependency_id is non-null across all branches.
4593SELECT t.id, ps.id
4594FROM mz_catalog.mz_tables t
4595JOIN mz_catalog.mz_sources ps ON ps.id = t.source_id",
4596    access: vec![PUBLIC_SELECT],
4597    // No ontology entity: these edges are already in the ontology via the
4598    // DependsOn links of mz_object_dependencies and
4599    // mz_materialization_dependencies. An entity here would duplicate them.
4600    ontology: None,
4601});
4602
4603pub static MZ_OBJECT_OID_ALIAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4604    name: "mz_object_oid_alias",
4605    schema: MZ_INTERNAL_SCHEMA,
4606    oid: oid::VIEW_MZ_OBJECT_OID_ALIAS_OID,
4607    desc: RelationDesc::builder()
4608        .with_column("object_type", SqlScalarType::String.nullable(false))
4609        .with_column("oid_alias", SqlScalarType::String.nullable(false))
4610        .with_key(vec![0])
4611        .finish(),
4612    column_comments: BTreeMap::new(),
4613    sql: "SELECT object_type, oid_alias
4614    FROM (
4615        VALUES
4616            (
4617                'table'::pg_catalog.text,
4618                'regclass'::pg_catalog.text
4619            ),
4620            ('source', 'regclass'),
4621            ('view', 'regclass'),
4622            ('materialized-view', 'regclass'),
4623            ('index', 'regclass'),
4624            ('type', 'regtype'),
4625            ('function', 'regproc')
4626    )
4627    AS _ (object_type, oid_alias);",
4628    access: vec![PUBLIC_SELECT],
4629    ontology: None,
4630});
4631
4632pub static MZ_OBJECT_FULLY_QUALIFIED_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4633    name: "mz_object_fully_qualified_names",
4634    schema: MZ_INTERNAL_SCHEMA,
4635    oid: oid::VIEW_MZ_OBJECT_FULLY_QUALIFIED_NAMES_OID,
4636    desc: RelationDesc::builder()
4637        .with_column("id", SqlScalarType::String.nullable(false))
4638        .with_column("name", SqlScalarType::String.nullable(false))
4639        .with_column("object_type", SqlScalarType::String.nullable(false))
4640        .with_column("schema_id", SqlScalarType::String.nullable(false))
4641        .with_column("schema_name", SqlScalarType::String.nullable(false))
4642        .with_column("database_id", SqlScalarType::String.nullable(true))
4643        .with_column("database_name", SqlScalarType::String.nullable(true))
4644        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4645        .finish(),
4646    column_comments: BTreeMap::from_iter([
4647        ("id", "Materialize's unique ID for the object."),
4648        ("name", "The name of the object."),
4649        (
4650            "object_type",
4651            "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
4652        ),
4653        (
4654            "schema_id",
4655            "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`.",
4656        ),
4657        (
4658            "schema_name",
4659            "The name of the schema to which the object belongs. Corresponds to `mz_schemas.name`.",
4660        ),
4661        (
4662            "database_id",
4663            "The ID of the database to which the object belongs. Corresponds to `mz_databases.id`.",
4664        ),
4665        (
4666            "database_name",
4667            "The name of the database to which the object belongs. Corresponds to `mz_databases.name`.",
4668        ),
4669        (
4670            "cluster_id",
4671            "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types.",
4672        ),
4673    ]),
4674    sql: "
4675    SELECT o.id,
4676        o.name,
4677        o.type as object_type,
4678        sc.id as schema_id,
4679        sc.name as schema_name,
4680        db.id as database_id,
4681        db.name as database_name,
4682        o.cluster_id
4683    FROM mz_catalog.mz_objects o
4684    INNER JOIN mz_catalog.mz_schemas sc ON sc.id = o.schema_id
4685    -- LEFT JOIN accounts for objects in the ambient database.
4686    LEFT JOIN mz_catalog.mz_databases db ON db.id = sc.database_id",
4687    access: vec![PUBLIC_SELECT],
4688    ontology: Some(Ontology {
4689        entity_name: "object_fqn",
4690        description: "Fully qualified name (database.schema.name) for objects",
4691        links: &const {
4692            [
4693                OntologyLink {
4694                    name: "details_of",
4695                    target: "object",
4696                    properties: LinkProperties::fk("id", "id", Cardinality::OneToOne),
4697                },
4698                OntologyLink {
4699                    name: "in_schema",
4700                    target: "schema",
4701                    properties: LinkProperties::fk("schema_id", "id", Cardinality::ManyToOne),
4702                },
4703                OntologyLink {
4704                    name: "in_database",
4705                    target: "database",
4706                    properties: LinkProperties::fk("database_id", "id", Cardinality::ManyToOne),
4707                },
4708                OntologyLink {
4709                    name: "belongs_to_cluster",
4710                    target: "cluster",
4711                    properties: LinkProperties::fk("cluster_id", "id", Cardinality::ManyToOne),
4712                },
4713            ]
4714        },
4715        column_semantic_types: &const {
4716            [
4717                ("id", SemanticType::CatalogItemId),
4718                ("object_type", SemanticType::ObjectType),
4719                ("schema_id", SemanticType::SchemaId),
4720                ("database_id", SemanticType::DatabaseId),
4721                ("cluster_id", SemanticType::ClusterId),
4722            ]
4723        },
4724    }),
4725});
4726
4727pub static MZ_OBJECT_GLOBAL_IDS: LazyLock<BuiltinMaterializedView> =
4728    LazyLock::new(|| BuiltinMaterializedView {
4729        name: "mz_object_global_ids",
4730        schema: MZ_INTERNAL_SCHEMA,
4731        oid: oid::MV_MZ_OBJECT_GLOBAL_IDS_OID,
4732        desc: RelationDesc::builder()
4733            .with_column("id", SqlScalarType::String.nullable(false))
4734            .with_column("global_id", SqlScalarType::String.nullable(false))
4735            .finish(),
4736        column_comments: BTreeMap::from_iter([
4737            (
4738                "id",
4739                "The ID of the object. Corresponds to `mz_objects.id`.",
4740            ),
4741            ("global_id", "The global ID of the object."),
4742        ]),
4743        sql: Box::leak(
4744            format!(
4745                "
4746IN CLUSTER mz_catalog_server
4747WITH (
4748    ASSERT NOT NULL id,
4749    ASSERT NOT NULL global_id
4750) AS
4751WITH
4752    -- `Item` rows carry user items, temporary items, and runtime-alterable builtins
4753    items AS (
4754        SELECT
4755            mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
4756            mz_internal.parse_catalog_id(data->'value'->'global_id') AS global_id,
4757            data->'value'->'extra_versions' AS extra_versions
4758        FROM mz_internal.mz_catalog_raw
4759        WHERE data->>'kind' = 'Item'
4760    ),
4761    -- Create a one to many mapping between an object and its global IDs. Tables and
4762    -- materialized views are the only objects with multiple global IDs.
4763    item_versions AS (
4764        SELECT i.id, mz_internal.parse_catalog_id(v.version->'global_id') AS global_id
4765        FROM items i
4766        CROSS JOIN LATERAL jsonb_array_elements(i.extra_versions) AS v(version)
4767    ),
4768    builtin_mappings AS (
4769        SELECT
4770            's' || (data->'value'->>'catalog_id') AS id,
4771            's' || (data->'value'->>'global_id') AS global_id
4772        FROM mz_internal.mz_catalog_raw
4773        WHERE
4774            data->>'kind' = 'GidMapping' AND
4775            -- Exclude runtime-alterable builtins since they're already included in `items`
4776            data->'value'->>'fingerprint' != '{RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL}'
4777    ),
4778    introspection_source_indexes AS (
4779        SELECT
4780            'si' || (data->'value'->>'catalog_id') AS id,
4781            'si' || (data->'value'->>'global_id') AS global_id
4782        FROM mz_internal.mz_catalog_raw
4783        WHERE data->>'kind' = 'ClusterIntrospectionSourceIndex'
4784    )
4785SELECT id, global_id FROM items
4786UNION ALL
4787SELECT id, global_id FROM item_versions
4788UNION ALL
4789SELECT id, global_id FROM builtin_mappings
4790UNION ALL
4791SELECT id, global_id FROM introspection_source_indexes"
4792            )
4793            .into_boxed_str(),
4794        ),
4795        is_retained_metrics_object: false,
4796        access: vec![PUBLIC_SELECT],
4797        ontology: Some(Ontology {
4798            entity_name: "object_global_id",
4799            description: "Mapping between CatalogItemId (SQL layer) and GlobalId (runtime layer)",
4800            links: &const {
4801                [OntologyLink {
4802                    name: "id_references",
4803                    target: "object",
4804                    properties: LinkProperties::fk("id", "id", Cardinality::ManyToOne),
4805                }]
4806            },
4807            column_semantic_types: &[("id", SemanticType::CatalogItemId)],
4808        }),
4809    });
4810
4811// TODO (SangJunBak): Remove once mz_object_history is released and used in the Console https://github.com/MaterializeInc/console/issues/3342
4812pub static MZ_OBJECT_LIFETIMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4813    name: "mz_object_lifetimes",
4814    schema: MZ_INTERNAL_SCHEMA,
4815    oid: oid::VIEW_MZ_OBJECT_LIFETIMES_OID,
4816    desc: RelationDesc::builder()
4817        .with_column("id", SqlScalarType::String.nullable(true))
4818        .with_column("previous_id", SqlScalarType::String.nullable(true))
4819        .with_column("object_type", SqlScalarType::String.nullable(false))
4820        .with_column("event_type", SqlScalarType::String.nullable(false))
4821        .with_column(
4822            "occurred_at",
4823            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4824        )
4825        .finish(),
4826    column_comments: BTreeMap::from_iter([
4827        ("id", "Materialize's unique ID for the object."),
4828        ("previous_id", "The object's previous ID, if one exists."),
4829        (
4830            "object_type",
4831            "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
4832        ),
4833        (
4834            "event_type",
4835            "The lifetime event, either `create` or `drop`.",
4836        ),
4837        (
4838            "occurred_at",
4839            "Wall-clock timestamp of when the event occurred.",
4840        ),
4841    ]),
4842    sql: "
4843    SELECT
4844        CASE
4845            WHEN a.object_type = 'cluster-replica' THEN a.details ->> 'replica_id'
4846            ELSE a.details ->> 'id'
4847        END id,
4848        a.details ->> 'previous_id' as previous_id,
4849        a.object_type,
4850        a.event_type,
4851        a.occurred_at
4852    FROM mz_catalog.mz_audit_events a
4853    WHERE a.event_type = 'create' OR a.event_type = 'drop'",
4854    access: vec![PUBLIC_SELECT],
4855    ontology: Some(Ontology {
4856        entity_name: "object_lifetime_event",
4857        description: "Create or drop lifecycle event for a catalog object",
4858        links: &const {
4859            [OntologyLink {
4860                name: "lifetime_event_of",
4861                target: "object",
4862                properties: LinkProperties::fk_typed(
4863                    "id",
4864                    "id",
4865                    Cardinality::ManyToOne,
4866                    mz_repr::SemanticType::CatalogItemId,
4867                ),
4868            }]
4869        },
4870        column_semantic_types: &const {
4871            [
4872                ("id", SemanticType::CatalogItemId),
4873                ("object_type", SemanticType::ObjectType),
4874            ]
4875        },
4876    }),
4877});
4878
4879pub static MZ_OBJECT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4880    name: "mz_object_history",
4881    schema: MZ_INTERNAL_SCHEMA,
4882    oid: oid::VIEW_MZ_OBJECT_HISTORY_OID,
4883    desc: RelationDesc::builder()
4884        .with_column("id", SqlScalarType::String.nullable(true))
4885        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4886        .with_column("object_type", SqlScalarType::String.nullable(false))
4887        .with_column(
4888            "created_at",
4889            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4890        )
4891        .with_column(
4892            "dropped_at",
4893            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4894        )
4895        .finish(),
4896    column_comments: BTreeMap::from_iter([
4897        ("id", "Materialize's unique ID for the object."),
4898        (
4899            "cluster_id",
4900            "The object's cluster ID. `NULL` if the object has no associated cluster.",
4901        ),
4902        (
4903            "object_type",
4904            "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
4905        ),
4906        (
4907            "created_at",
4908            "Wall-clock timestamp of when the object was created. `NULL` for built in system objects.",
4909        ),
4910        (
4911            "dropped_at",
4912            "Wall-clock timestamp of when the object was dropped. `NULL` for built in system objects or if the object hasn't been dropped.",
4913        ),
4914    ]),
4915    sql: r#"
4916    WITH
4917        creates AS
4918        (
4919            SELECT
4920                details ->> 'id' AS id,
4921                -- We need to backfill cluster_id since older object create events don't include the cluster ID in the audit log
4922                COALESCE(details ->> 'cluster_id', objects.cluster_id) AS cluster_id,
4923                object_type,
4924                occurred_at
4925            FROM
4926                mz_catalog.mz_audit_events AS events
4927                    LEFT JOIN mz_catalog.mz_objects AS objects ON details ->> 'id' = objects.id
4928            WHERE event_type = 'create' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
4929        ),
4930        drops AS
4931        (
4932            SELECT details ->> 'id' AS id, occurred_at
4933            FROM mz_catalog.mz_audit_events
4934            WHERE event_type = 'drop' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
4935        ),
4936        user_object_history AS
4937        (
4938            SELECT
4939                creates.id,
4940                creates.cluster_id,
4941                creates.object_type,
4942                creates.occurred_at AS created_at,
4943                drops.occurred_at AS dropped_at
4944            FROM creates LEFT JOIN drops ON creates.id = drops.id
4945            WHERE creates.id LIKE 'u%'
4946        ),
4947        -- We need to union built in objects since they aren't in the audit log
4948        built_in_objects AS
4949        (
4950            -- Functions that accept different arguments have different oids but the same id. We deduplicate in this case.
4951            SELECT DISTINCT ON (objects.id)
4952                objects.id,
4953                objects.cluster_id,
4954                objects.type AS object_type,
4955                NULL::timestamptz AS created_at,
4956                NULL::timestamptz AS dropped_at
4957            FROM mz_catalog.mz_objects AS objects
4958            WHERE objects.id LIKE 's%'
4959        )
4960    SELECT * FROM user_object_history UNION ALL (SELECT * FROM built_in_objects)"#,
4961    access: vec![PUBLIC_SELECT],
4962    ontology: Some(Ontology {
4963        entity_name: "object_history",
4964        description: "Historical record of object creation and drops",
4965        links: &const {
4966            [OntologyLink {
4967                name: "history_of",
4968                target: "object",
4969                properties: LinkProperties::fk("id", "id", Cardinality::ManyToOne),
4970            }]
4971        },
4972        column_semantic_types: &[("id", SemanticType::CatalogItemId)],
4973    }),
4974});
4975
4976pub static MZ_OBJECT_TRANSITIVE_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| {
4977    BuiltinView {
4978        name: "mz_object_transitive_dependencies",
4979        schema: MZ_INTERNAL_SCHEMA,
4980        oid: oid::VIEW_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_OID,
4981        desc: RelationDesc::builder()
4982            .with_column("object_id", SqlScalarType::String.nullable(false))
4983            .with_column(
4984                "referenced_object_id",
4985                SqlScalarType::String.nullable(false),
4986            )
4987            .with_key(vec![0, 1])
4988            .finish(),
4989        column_comments: BTreeMap::from_iter([
4990            (
4991                "object_id",
4992                "The ID of the dependent object. Corresponds to `mz_objects.id`.",
4993            ),
4994            (
4995                "referenced_object_id",
4996                "The ID of the (possibly transitively) referenced object. Corresponds to `mz_objects.id`.",
4997            ),
4998        ]),
4999        sql: "
5000WITH MUTUALLY RECURSIVE
5001  reach(object_id text, referenced_object_id text) AS (
5002    SELECT object_id, referenced_object_id FROM mz_internal.mz_object_dependencies
5003    UNION
5004    SELECT x, z FROM reach r1(x, y) JOIN reach r2(y, z) USING(y)
5005  )
5006SELECT object_id, referenced_object_id FROM reach;",
5007        access: vec![PUBLIC_SELECT],
5008        ontology: Some(Ontology {
5009            entity_name: "transitive_dependency",
5010            description: "Transitive closure of object dependencies — all direct and indirect dependencies",
5011            links: &const {
5012                [
5013                    OntologyLink {
5014                        name: "depends_on",
5015                        target: "object",
5016                        properties: LinkProperties::DependsOn {
5017                            source_column: "object_id",
5018                            target_column: "id",
5019                            source_id_type: Some(mz_repr::SemanticType::CatalogItemId),
5020                            requires_mapping: None,
5021                        },
5022                    },
5023                    OntologyLink {
5024                        name: "dependency_is",
5025                        target: "object",
5026                        properties: LinkProperties::DependsOn {
5027                            source_column: "referenced_object_id",
5028                            target_column: "id",
5029                            source_id_type: Some(mz_repr::SemanticType::CatalogItemId),
5030                            requires_mapping: None,
5031                        },
5032                    },
5033                ]
5034            },
5035            column_semantic_types: &const {
5036                [
5037                    ("object_id", SemanticType::CatalogItemId),
5038                    ("referenced_object_id", SemanticType::CatalogItemId),
5039                ]
5040            },
5041        }),
5042    }
5043});
5044
5045/// Peeled version of `PG_NAMESPACE`:
5046/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
5047///   in order to make this view indexable.
5048/// - This has the database name as an extra column, so that downstream views can check it against
5049///  `current_database()`.
5050pub static PG_NAMESPACE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5051    name: "pg_namespace_all_databases",
5052    schema: MZ_INTERNAL_SCHEMA,
5053    oid: oid::VIEW_PG_NAMESPACE_ALL_DATABASES_OID,
5054    desc: RelationDesc::builder()
5055        .with_column("oid", SqlScalarType::Oid.nullable(false))
5056        .with_column("nspname", SqlScalarType::String.nullable(false))
5057        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
5058        .with_column(
5059            "nspacl",
5060            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
5061        )
5062        .with_column("database_name", SqlScalarType::String.nullable(true))
5063        .finish(),
5064    column_comments: BTreeMap::new(),
5065    sql: "
5066SELECT
5067    s.oid AS oid,
5068    s.name AS nspname,
5069    role_owner.oid AS nspowner,
5070    NULL::pg_catalog.text[] AS nspacl,
5071    d.name as database_name
5072FROM mz_catalog.mz_schemas s
5073LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
5074JOIN mz_catalog.mz_roles role_owner ON role_owner.id = s.owner_id",
5075    access: vec![PUBLIC_SELECT],
5076    ontology: None,
5077});
5078
5079pub const PG_NAMESPACE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
5080    name: "pg_namespace_all_databases_ind",
5081    schema: MZ_INTERNAL_SCHEMA,
5082    oid: oid::INDEX_PG_NAMESPACE_ALL_DATABASES_IND_OID,
5083    sql: "IN CLUSTER mz_catalog_server
5084ON mz_internal.pg_namespace_all_databases (nspname)",
5085    is_retained_metrics_object: false,
5086};
5087
5088/// Peeled version of `PG_CLASS`:
5089/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
5090///   in order to make this view indexable.
5091/// - This has the database name as an extra column, so that downstream views can check it against
5092///  `current_database()`.
5093pub static PG_CLASS_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
5094    BuiltinView {
5095        name: "pg_class_all_databases",
5096        schema: MZ_INTERNAL_SCHEMA,
5097        oid: oid::VIEW_PG_CLASS_ALL_DATABASES_OID,
5098        desc: RelationDesc::builder()
5099            .with_column("oid", SqlScalarType::Oid.nullable(false))
5100            .with_column("relname", SqlScalarType::String.nullable(false))
5101            .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
5102            .with_column("reloftype", SqlScalarType::Oid.nullable(false))
5103            .with_column("relowner", SqlScalarType::Oid.nullable(false))
5104            .with_column("relam", SqlScalarType::Oid.nullable(false))
5105            .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
5106            .with_column("relpages", SqlScalarType::Int32.nullable(false))
5107            .with_column("reltuples", SqlScalarType::Float32.nullable(false))
5108            .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
5109            .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
5110            .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
5111            .with_column("relkind", SqlScalarType::String.nullable(true))
5112            .with_column("relnatts", SqlScalarType::Int16.nullable(false))
5113            .with_column("relchecks", SqlScalarType::Int16.nullable(false))
5114            .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
5115            .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
5116            .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
5117            .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
5118            .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
5119            .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
5120            .with_column("relispartition", SqlScalarType::Bool.nullable(false))
5121            .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
5122            .with_column("reloptions", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true))
5123            .with_column("database_name", SqlScalarType::String.nullable(true))
5124            .finish(),
5125        column_comments: BTreeMap::new(),
5126        sql: "
5127SELECT
5128    class_objects.oid,
5129    class_objects.name AS relname,
5130    mz_schemas.oid AS relnamespace,
5131    -- MZ doesn't support typed tables so reloftype is filled with 0
5132    0::pg_catalog.oid AS reloftype,
5133    role_owner.oid AS relowner,
5134    0::pg_catalog.oid AS relam,
5135    -- MZ doesn't have tablespaces so reltablespace is filled in with 0 implying the default tablespace
5136    0::pg_catalog.oid AS reltablespace,
5137    -- MZ doesn't track relation sizes in pages. Postgres reports 0 for a relation
5138    -- that has never been vacuumed or analyzed, which matches reltuples = -1 below.
5139    0::pg_catalog.int4 AS relpages,
5140    -- MZ doesn't support (estimated) row counts currently.
5141    -- Postgres defines a value of -1 as unknown.
5142    -1::float4 as reltuples,
5143    -- MZ doesn't use TOAST tables so reltoastrelid is filled with 0
5144    0::pg_catalog.oid AS reltoastrelid,
5145    EXISTS (SELECT id, oid, name, on_id, cluster_id FROM mz_catalog.mz_indexes where mz_indexes.on_id = class_objects.id) AS relhasindex,
5146    -- MZ doesn't have unlogged tables and because of (https://github.com/MaterializeInc/database-issues/issues/2689)
5147    -- temporary objects don't show up here, so relpersistence is filled with 'p' for permanent.
5148    -- TODO(jkosh44): update this column when issue is resolved.
5149    'p'::pg_catalog.\"char\" AS relpersistence,
5150    CASE
5151        WHEN class_objects.type = 'table' THEN 'r'
5152        WHEN class_objects.type = 'source' THEN 'r'
5153        WHEN class_objects.type = 'index' THEN 'i'
5154        WHEN class_objects.type = 'view' THEN 'v'
5155        WHEN class_objects.type = 'materialized-view' THEN 'm'
5156    END relkind,
5157    CASE
5158        WHEN class_objects.type = 'index' THEN COALESCE(
5159            (
5160                SELECT count(*)::pg_catalog.int2
5161                FROM mz_catalog.mz_index_columns
5162                WHERE mz_index_columns.index_id = class_objects.id
5163            ),
5164            0::pg_catalog.int2
5165        )
5166        ELSE COALESCE(
5167            (
5168                SELECT count(*)::pg_catalog.int2
5169                FROM mz_catalog.mz_columns
5170                WHERE mz_columns.id = class_objects.id
5171            ),
5172            0::pg_catalog.int2
5173        )
5174    END AS relnatts,
5175    -- MZ doesn't support CHECK constraints so relchecks is filled with 0
5176    0::pg_catalog.int2 AS relchecks,
5177    -- MZ doesn't support creating rules so relhasrules is filled with false
5178    false AS relhasrules,
5179    -- MZ doesn't support creating triggers so relhastriggers is filled with false
5180    false AS relhastriggers,
5181    -- MZ doesn't support table inheritance or partitions so relhassubclass is filled with false
5182    false AS relhassubclass,
5183    -- MZ doesn't have row level security so relrowsecurity and relforcerowsecurity is filled with false
5184    false AS relrowsecurity,
5185    false AS relforcerowsecurity,
5186    -- MZ doesn't support replication so relreplident is filled with 'd' for default
5187    'd'::pg_catalog.\"char\" AS relreplident,
5188    -- MZ doesn't support table partitioning so relispartition is filled with false
5189    false AS relispartition,
5190    -- PG removed relhasoids in v12 so it's filled with false
5191    false AS relhasoids,
5192    -- MZ doesn't support options for relations
5193    NULL::pg_catalog.text[] as reloptions,
5194    d.name as database_name
5195FROM (
5196    -- pg_class catalogs relations and indexes
5197    SELECT id, oid, schema_id, name, type, owner_id FROM mz_catalog.mz_relations
5198    UNION ALL
5199        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type, mz_indexes.owner_id
5200        FROM mz_catalog.mz_indexes
5201        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
5202) AS class_objects
5203JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
5204LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
5205JOIN mz_catalog.mz_roles role_owner ON role_owner.id = class_objects.owner_id",
5206        access: vec![PUBLIC_SELECT],
5207        ontology: None,
5208    }
5209});
5210
5211pub const PG_CLASS_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
5212    name: "pg_class_all_databases_ind",
5213    schema: MZ_INTERNAL_SCHEMA,
5214    oid: oid::INDEX_PG_CLASS_ALL_DATABASES_IND_OID,
5215    sql: "IN CLUSTER mz_catalog_server
5216ON mz_internal.pg_class_all_databases (relname)",
5217    is_retained_metrics_object: false,
5218};
5219
5220/// Peeled version of `PG_DESCRIPTION`:
5221/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
5222///   in order to make this view indexable.
5223/// - This has 2 extra columns for the database names, so that downstream views can check them
5224///   against `current_database()`.
5225pub static PG_DESCRIPTION_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
5226    BuiltinView {
5227        name: "pg_description_all_databases",
5228        schema: MZ_INTERNAL_SCHEMA,
5229        oid: oid::VIEW_PG_DESCRIPTION_ALL_DATABASES_OID,
5230        desc: RelationDesc::builder()
5231            .with_column("objoid", SqlScalarType::Oid.nullable(false))
5232            .with_column("classoid", SqlScalarType::Oid.nullable(true))
5233            .with_column("objsubid", SqlScalarType::Int32.nullable(false))
5234            .with_column("description", SqlScalarType::String.nullable(false))
5235            .with_column("oid_database_name", SqlScalarType::String.nullable(true))
5236            .with_column("class_database_name", SqlScalarType::String.nullable(true))
5237            .finish(),
5238        column_comments: BTreeMap::new(),
5239        sql: "
5240(
5241    -- The classoid of a comment is the oid of the pg_catalog system catalog
5242    -- that conceptually stores the commented object: pg_class for relations,
5243    -- pg_type for types, pg_namespace for schemas. We scope the lookup to the
5244    -- pg_catalog schema; otherwise a user-created object named e.g. `pg_class`
5245    -- makes the scalar subqueries below match multiple rows and the whole view
5246    -- errors for everyone. PostgreSQL's pg_description is a real catalog table
5247    -- and is unaffected by such user objects, and so are we.
5248    WITH pg_catalog_class AS (
5249        SELECT oid, relname, database_name
5250        FROM mz_internal.pg_class_all_databases
5251        WHERE relnamespace = (
5252            SELECT oid FROM mz_internal.pg_namespace_all_databases WHERE nspname = 'pg_catalog'
5253        )
5254    ),
5255    -- Gather all of the class oid's for objects that can have comments.
5256    pg_classoids AS (
5257        SELECT oid, database_name as oid_database_name,
5258          (SELECT oid FROM pg_catalog_class WHERE relname = 'pg_class') AS classoid,
5259          (SELECT database_name FROM pg_catalog_class WHERE relname = 'pg_class') AS class_database_name
5260        FROM mz_internal.pg_class_all_databases
5261        UNION ALL
5262        SELECT oid, database_name as oid_database_name,
5263          (SELECT oid FROM pg_catalog_class WHERE relname = 'pg_type') AS classoid,
5264          (SELECT database_name FROM pg_catalog_class WHERE relname = 'pg_type') AS class_database_name
5265        FROM mz_internal.pg_type_all_databases
5266        UNION ALL
5267        SELECT oid, database_name as oid_database_name,
5268          (SELECT oid FROM pg_catalog_class WHERE relname = 'pg_namespace') AS classoid,
5269          (SELECT database_name FROM pg_catalog_class WHERE relname = 'pg_namespace') AS class_database_name
5270        FROM mz_internal.pg_namespace_all_databases
5271    ),
5272
5273    -- Gather all of the MZ ids for objects that can have comments.
5274    mz_objects AS (
5275        SELECT id, oid, type FROM mz_catalog.mz_objects
5276        UNION ALL
5277        SELECT id, oid, 'schema' AS type FROM mz_catalog.mz_schemas
5278    )
5279    SELECT
5280        pg_classoids.oid AS objoid,
5281        pg_classoids.classoid as classoid,
5282        COALESCE(cmt.object_sub_id, 0) AS objsubid,
5283        cmt.comment AS description,
5284        -- Columns added because of the peeling. (Note that there are 2 of these here.)
5285        oid_database_name,
5286        class_database_name
5287    FROM
5288        pg_classoids
5289    JOIN
5290        mz_objects ON pg_classoids.oid = mz_objects.oid
5291    JOIN
5292        mz_internal.mz_comments AS cmt ON mz_objects.id = cmt.id AND lower(mz_objects.type) = lower(cmt.object_type)
5293)",
5294        access: vec![PUBLIC_SELECT],
5295        ontology: None,
5296    }
5297});
5298
5299pub const PG_DESCRIPTION_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
5300    name: "pg_description_all_databases_ind",
5301    schema: MZ_INTERNAL_SCHEMA,
5302    oid: oid::INDEX_PG_DESCRIPTION_ALL_DATABASES_IND_OID,
5303    sql: "IN CLUSTER mz_catalog_server
5304ON mz_internal.pg_description_all_databases (objoid, classoid, objsubid, description, oid_database_name, class_database_name)",
5305    is_retained_metrics_object: false,
5306};
5307
5308/// Peeled version of `PG_TYPE`:
5309/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
5310///   in order to make this view indexable.
5311/// - This has the database name as an extra column, so that downstream views can check it against
5312///  `current_database()`.
5313pub static PG_TYPE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
5314    BuiltinView {
5315        name: "pg_type_all_databases",
5316        schema: MZ_INTERNAL_SCHEMA,
5317        oid: oid::VIEW_PG_TYPE_ALL_DATABASES_OID,
5318        desc: RelationDesc::builder()
5319            .with_column("oid", SqlScalarType::Oid.nullable(false))
5320            .with_column("typname", SqlScalarType::String.nullable(false))
5321            .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
5322            .with_column("typowner", SqlScalarType::Oid.nullable(false))
5323            .with_column("typlen", SqlScalarType::Int16.nullable(true))
5324            .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
5325            .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
5326            .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
5327            .with_column("typrelid", SqlScalarType::Oid.nullable(false))
5328            .with_column("typelem", SqlScalarType::Oid.nullable(false))
5329            .with_column("typarray", SqlScalarType::Oid.nullable(false))
5330            .with_column("typinput", SqlScalarType::RegProc.nullable(true))
5331            .with_column("typreceive", SqlScalarType::Oid.nullable(false))
5332            .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
5333            .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
5334            .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
5335            .with_column("typcollation", SqlScalarType::Oid.nullable(false))
5336            .with_column("typdefault", SqlScalarType::String.nullable(true))
5337            .with_column("database_name", SqlScalarType::String.nullable(true))
5338            .with_column("typsend", SqlScalarType::RegProc.nullable(false))
5339            .finish(),
5340        column_comments: BTreeMap::new(),
5341        sql: "
5342SELECT
5343    mz_types.oid,
5344    mz_types.name AS typname,
5345    mz_schemas.oid AS typnamespace,
5346    role_owner.oid AS typowner,
5347    mz_internal.mz_type_pg_metadata.typlen,
5348    -- 'a' is used internally to denote an array type, but in postgres they show up
5349    -- as 'b'.
5350    (CASE mztype WHEN 'a' THEN 'b' ELSE mztype END)::pg_catalog.char AS typtype,
5351    (CASE category
5352        WHEN 'array' THEN 'A'
5353        WHEN 'bit-string' THEN 'V'
5354        WHEN 'boolean' THEN 'B'
5355        WHEN 'composite' THEN 'C'
5356        WHEN 'date-time' THEN 'D'
5357        WHEN 'enum' THEN 'E'
5358        WHEN 'geometric' THEN 'G'
5359        WHEN 'list' THEN 'U' -- List types are user-defined from PostgreSQL's perspective.
5360        WHEN 'network-address' THEN 'I'
5361        WHEN 'numeric' THEN 'N'
5362        WHEN 'pseudo' THEN 'P'
5363        WHEN 'string' THEN 'S'
5364        WHEN 'timespan' THEN 'T'
5365        WHEN 'user-defined' THEN 'U'
5366        WHEN 'unknown' THEN 'X'
5367    END)::pg_catalog.char AS typcategory,
5368    -- In pg only the 'box' type is not ','.
5369    ','::pg_catalog.char AS typdelim,
5370    0::pg_catalog.oid AS typrelid,
5371    coalesce(
5372        (
5373            SELECT t.oid
5374            FROM mz_catalog.mz_array_types a
5375            JOIN mz_catalog.mz_types t ON a.element_id = t.id
5376            WHERE a.id = mz_types.id
5377        ),
5378        (
5379            SELECT t.oid
5380            FROM mz_catalog.mz_list_types l
5381            JOIN mz_catalog.mz_types t ON l.element_id = t.id
5382            WHERE l.id = mz_types.id
5383        ),
5384        0
5385    ) AS typelem,
5386    coalesce(
5387        (
5388            SELECT
5389                t.oid
5390            FROM
5391                mz_catalog.mz_array_types AS a
5392                JOIN mz_catalog.mz_types AS t ON a.id = t.id
5393            WHERE
5394                a.element_id = mz_types.id
5395        ),
5396        0
5397    )
5398        AS typarray,
5399    mz_internal.mz_type_pg_metadata.typinput::pg_catalog.regproc AS typinput,
5400    COALESCE(mz_internal.mz_type_pg_metadata.typreceive, 0) AS typreceive,
5401    false::pg_catalog.bool AS typnotnull,
5402    0::pg_catalog.oid AS typbasetype,
5403    -1::pg_catalog.int4 AS typtypmod,
5404    -- MZ doesn't support COLLATE so typcollation is filled with 0
5405    0::pg_catalog.oid AS typcollation,
5406    NULL::pg_catalog.text AS typdefault,
5407    d.name as database_name,
5408    COALESCE(mz_internal.mz_type_pg_metadata.typsend, 0)::pg_catalog.regproc AS typsend
5409FROM
5410    mz_catalog.mz_types
5411    LEFT JOIN mz_internal.mz_type_pg_metadata ON mz_catalog.mz_types.id = mz_internal.mz_type_pg_metadata.id
5412    JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_types.schema_id
5413    JOIN (
5414            -- 'a' is not a supported typtype, but we use it to denote an array. It is
5415            -- converted to the correct value above.
5416            SELECT id, 'a' AS mztype FROM mz_catalog.mz_array_types
5417            UNION ALL SELECT id, 'b' FROM mz_catalog.mz_base_types
5418            UNION ALL SELECT id, 'l' FROM mz_catalog.mz_list_types
5419            UNION ALL SELECT id, 'm' FROM mz_catalog.mz_map_types
5420            UNION ALL SELECT id, 'p' FROM mz_catalog.mz_pseudo_types
5421        )
5422            AS t ON mz_types.id = t.id
5423    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
5424    JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_types.owner_id",
5425        access: vec![PUBLIC_SELECT],
5426        ontology: None,
5427    }
5428});
5429
5430pub const PG_TYPE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
5431    name: "pg_type_all_databases_ind",
5432    schema: MZ_INTERNAL_SCHEMA,
5433    oid: oid::INDEX_PG_TYPE_ALL_DATABASES_IND_OID,
5434    sql: "IN CLUSTER mz_catalog_server
5435ON mz_internal.pg_type_all_databases (oid)",
5436    is_retained_metrics_object: false,
5437};
5438
5439/// Peeled version of `PG_ATTRIBUTE`:
5440/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
5441///   in order to make this view indexable.
5442/// - This has 2 extra columns for the database names, so that downstream views can check them
5443///   against `current_database()`.
5444pub static PG_ATTRIBUTE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
5445    BuiltinView {
5446        name: "pg_attribute_all_databases",
5447        schema: MZ_INTERNAL_SCHEMA,
5448        oid: oid::VIEW_PG_ATTRIBUTE_ALL_DATABASES_OID,
5449        desc: RelationDesc::builder()
5450            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
5451            .with_column("attname", SqlScalarType::String.nullable(false))
5452            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
5453            .with_column("attlen", SqlScalarType::Int16.nullable(true))
5454            .with_column("attnum", SqlScalarType::Int16.nullable(false))
5455            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
5456            .with_column("attndims", SqlScalarType::Int16.nullable(false))
5457            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
5458            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
5459            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
5460            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
5461            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
5462            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
5463            .with_column("database_name", SqlScalarType::String.nullable(true))
5464            .with_column("pg_type_database_name", SqlScalarType::String.nullable(true))
5465            .finish(),
5466        column_comments: BTreeMap::new(),
5467        sql: "
5468SELECT
5469    class_objects.oid as attrelid,
5470    mz_columns.name as attname,
5471    mz_columns.type_oid AS atttypid,
5472    pg_type_all_databases.typlen AS attlen,
5473    position::int8::int2 as attnum,
5474    mz_columns.type_mod as atttypmod,
5475    -- dummy value, just to make go-jet's workaround work for now. Discussion:
5476    -- https://github.com/MaterializeInc/materialize/pull/34649#issuecomment-3714291409
5477    0::int2 as attndims,
5478    NOT nullable as attnotnull,
5479    mz_columns.default IS NOT NULL as atthasdef,
5480    ''::pg_catalog.\"char\" as attidentity,
5481    -- MZ doesn't support generated columns so attgenerated is filled with ''
5482    ''::pg_catalog.\"char\" as attgenerated,
5483    FALSE as attisdropped,
5484    -- MZ doesn't support COLLATE so attcollation is filled with 0
5485    0::pg_catalog.oid as attcollation,
5486    -- Columns added because of the peeling. (Note that there are 2 of these here.)
5487    d.name as database_name,
5488    pg_type_all_databases.database_name as pg_type_database_name
5489FROM (
5490    -- pg_attribute catalogs columns on relations and indexes
5491    SELECT id, oid, schema_id, name, type FROM mz_catalog.mz_relations
5492    UNION ALL
5493        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type
5494        FROM mz_catalog.mz_indexes
5495        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
5496) AS class_objects
5497JOIN mz_catalog.mz_columns ON class_objects.id = mz_columns.id
5498JOIN mz_internal.pg_type_all_databases ON pg_type_all_databases.oid = mz_columns.type_oid
5499JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
5500LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id",
5501        // Since this depends on pg_type, its id must be higher due to initialization
5502        // ordering.
5503        access: vec![PUBLIC_SELECT],
5504        ontology: None,
5505    }
5506});
5507
5508pub const PG_ATTRIBUTE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
5509    name: "pg_attribute_all_databases_ind",
5510    schema: MZ_INTERNAL_SCHEMA,
5511    oid: oid::INDEX_PG_ATTRIBUTE_ALL_DATABASES_IND_OID,
5512    sql: "IN CLUSTER mz_catalog_server
5513ON mz_internal.pg_attribute_all_databases (attrelid)",
5514    is_retained_metrics_object: false,
5515};
5516
5517/// Peeled version of `PG_ATTRDEF`:
5518/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
5519///   in order to make this view indexable.
5520pub static PG_ATTRDEF_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5521    name: "pg_attrdef_all_databases",
5522    schema: MZ_INTERNAL_SCHEMA,
5523    oid: oid::VIEW_PG_ATTRDEF_ALL_DATABASES_OID,
5524    desc: RelationDesc::builder()
5525        .with_column("oid", SqlScalarType::Oid.nullable(true))
5526        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
5527        .with_column("adnum", SqlScalarType::Int64.nullable(false))
5528        .with_column("adbin", SqlScalarType::String.nullable(false))
5529        .with_column("adsrc", SqlScalarType::String.nullable(false))
5530        .finish(),
5531    column_comments: BTreeMap::new(),
5532    sql: "
5533SELECT
5534    NULL::pg_catalog.oid AS oid,
5535    mz_objects.oid AS adrelid,
5536    mz_columns.position::int8 AS adnum,
5537    mz_columns.default AS adbin,
5538    mz_columns.default AS adsrc
5539FROM mz_catalog.mz_columns
5540    JOIN mz_catalog.mz_objects ON mz_columns.id = mz_objects.id
5541WHERE default IS NOT NULL",
5542    access: vec![PUBLIC_SELECT],
5543    ontology: None,
5544});
5545
5546pub const PG_ATTRDEF_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
5547    name: "pg_attrdef_all_databases_ind",
5548    schema: MZ_INTERNAL_SCHEMA,
5549    oid: oid::INDEX_PG_ATTRDEF_ALL_DATABASES_IND_OID,
5550    sql: "IN CLUSTER mz_catalog_server
5551ON mz_internal.pg_attrdef_all_databases (oid, adrelid, adnum, adbin, adsrc)",
5552    is_retained_metrics_object: false,
5553};
5554
5555pub static MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED: LazyLock<BuiltinSource> =
5556    LazyLock::new(|| BuiltinSource {
5557        // TODO(database-issues#8173): Rename this source to `mz_compute_error_counts_raw`.
5558        // Currently this causes a naming conflict because the resolver stumbles over the
5559        // source with the same name in `mz_introspection` due to the automatic schema
5560        // translation.
5561        name: "mz_compute_error_counts_raw_unified",
5562        schema: MZ_INTERNAL_SCHEMA,
5563        oid: oid::SOURCE_MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED_OID,
5564        desc: RelationDesc::builder()
5565            .with_column("replica_id", SqlScalarType::String.nullable(false))
5566            .with_column("object_id", SqlScalarType::String.nullable(false))
5567            .with_column(
5568                "count",
5569                SqlScalarType::Numeric { max_scale: None }.nullable(false),
5570            )
5571            .finish(),
5572        data_source: IntrospectionType::ComputeErrorCounts.into(),
5573        column_comments: BTreeMap::new(),
5574        is_retained_metrics_object: false,
5575        access: vec![PUBLIC_SELECT],
5576        ontology: None,
5577    });
5578
5579pub static MZ_COMPUTE_HYDRATION_TIMES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5580    name: "mz_compute_hydration_times",
5581    schema: MZ_INTERNAL_SCHEMA,
5582    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_TIMES_OID,
5583    desc: RelationDesc::builder()
5584        .with_column("replica_id", SqlScalarType::String.nullable(false))
5585        .with_column("object_id", SqlScalarType::String.nullable(false))
5586        .with_column("time_ns", SqlScalarType::UInt64.nullable(true))
5587        .finish(),
5588    data_source: IntrospectionType::ComputeHydrationTimes.into(),
5589    column_comments: BTreeMap::new(),
5590    is_retained_metrics_object: true,
5591    access: vec![PUBLIC_SELECT],
5592    ontology: Some(Ontology {
5593        entity_name: "compute_hydration_time",
5594        description: "Time to hydrate compute objects",
5595        links: &const { [] },
5596        column_semantic_types: &const {
5597            [
5598                ("replica_id", SemanticType::ReplicaId),
5599                ("object_id", SemanticType::CatalogItemId),
5600            ]
5601        },
5602    }),
5603});
5604
5605pub static MZ_COMPUTE_HYDRATION_TIMES_IND: LazyLock<BuiltinIndex> =
5606    LazyLock::new(|| BuiltinIndex {
5607        name: "mz_compute_hydration_times_ind",
5608        schema: MZ_INTERNAL_SCHEMA,
5609        oid: oid::INDEX_MZ_COMPUTE_HYDRATION_TIMES_IND_OID,
5610        sql: "IN CLUSTER mz_catalog_server
5611    ON mz_internal.mz_compute_hydration_times (replica_id)",
5612        is_retained_metrics_object: true,
5613    });
5614
5615pub static MZ_OBJECT_ARRANGEMENT_SIZES_UNIFIED: LazyLock<BuiltinSource> = LazyLock::new(|| {
5616    BuiltinSource {
5617        name: "mz_object_arrangement_sizes",
5618        schema: MZ_INTERNAL_SCHEMA,
5619        oid: oid::SOURCE_MZ_OBJECT_ARRANGEMENT_SIZES_OID,
5620        desc: RelationDesc::builder()
5621            .with_column("replica_id", SqlScalarType::String.nullable(false))
5622            .with_column("object_id", SqlScalarType::String.nullable(false))
5623            .with_column("size", SqlScalarType::Int64.nullable(true))
5624            .finish(),
5625        data_source: IntrospectionType::ComputeObjectArrangementSizes.into(),
5626        column_comments: BTreeMap::from_iter([
5627            (
5628                "replica_id",
5629                "The ID of the cluster replica. Corresponds to `mz_cluster_replicas.id`.",
5630            ),
5631            (
5632                "object_id",
5633                "The ID of the compute object (index or materialized view). Corresponds to `mz_objects.id`.",
5634            ),
5635            (
5636                "size",
5637                "The total arrangement heap and batcher size in bytes for this object on this replica, \
5638                 rounded to the nearest 10 MiB boundary to reduce per-byte churn in the differential \
5639                 collection. Objects with less than 5 MiB of arrangements report a size of 0.",
5640            ),
5641        ]),
5642        is_retained_metrics_object: true,
5643        access: vec![PUBLIC_SELECT],
5644        ontology: None,
5645    }
5646});
5647
5648pub static MZ_OBJECT_ARRANGEMENT_SIZES_IND: LazyLock<BuiltinIndex> =
5649    LazyLock::new(|| BuiltinIndex {
5650        name: "mz_object_arrangement_sizes_ind",
5651        schema: MZ_INTERNAL_SCHEMA,
5652        oid: oid::INDEX_MZ_OBJECT_ARRANGEMENT_SIZES_IND_OID,
5653        sql: "IN CLUSTER mz_catalog_server
5654    ON mz_internal.mz_object_arrangement_sizes (replica_id)",
5655        is_retained_metrics_object: true,
5656    });
5657
5658pub static MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY: LazyLock<BuiltinTable> = LazyLock::new(|| {
5659    BuiltinTable {
5660        name: "mz_object_arrangement_size_history",
5661        schema: MZ_INTERNAL_SCHEMA,
5662        oid: oid::TABLE_MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_OID,
5663        desc: RelationDesc::builder()
5664            .with_column("replica_id", SqlScalarType::String.nullable(false))
5665            .with_column("object_id", SqlScalarType::String.nullable(false))
5666            .with_column("size", SqlScalarType::Int64.nullable(false))
5667            .with_column(
5668                "collection_timestamp",
5669                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5670            )
5671            .with_column("hydration_complete", SqlScalarType::Bool.nullable(false))
5672            .finish(),
5673        column_comments: BTreeMap::from_iter([
5674            (
5675                "replica_id",
5676                "The ID of the cluster replica. Corresponds to `mz_cluster_replicas.id`.",
5677            ),
5678            (
5679                "object_id",
5680                "The ID of the compute object (index or materialized view). Corresponds to `mz_objects.id`.",
5681            ),
5682            (
5683                "size",
5684                "The total arrangement heap and batcher size in bytes for this object on this replica \
5685                 at `collection_timestamp`, rounded to the nearest 10 MiB to reduce per-byte churn \
5686                 in the underlying differential collection. Objects with less than 5 MiB of \
5687                 arrangements are not recorded. May reflect a mid-build size if \
5688                 `hydration_complete` is `false`.",
5689            ),
5690            (
5691                "collection_timestamp",
5692                "The timestamp when this snapshot was collected.",
5693            ),
5694            (
5695                "hydration_complete",
5696                "Whether the arrangement had finished its initial hydration on this replica when \
5697                 the snapshot was collected. Filter for `true` to consider only stable, post-build \
5698                 sizes.",
5699            ),
5700        ]),
5701        is_retained_metrics_object: true,
5702        access: vec![PUBLIC_SELECT],
5703        ontology: None,
5704    }
5705});
5706
5707pub static MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_OBJECT_IND: LazyLock<BuiltinIndex> =
5708    LazyLock::new(|| BuiltinIndex {
5709        name: "mz_object_arrangement_size_history_object_ind",
5710        schema: MZ_INTERNAL_SCHEMA,
5711        oid: oid::INDEX_MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_OBJECT_IND_OID,
5712        sql: "IN CLUSTER mz_catalog_server
5713    ON mz_internal.mz_object_arrangement_size_history (object_id)",
5714        is_retained_metrics_object: true,
5715    });
5716
5717pub static MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_TS_IND: LazyLock<BuiltinIndex> =
5718    LazyLock::new(|| BuiltinIndex {
5719        name: "mz_object_arrangement_size_history_ts_ind",
5720        schema: MZ_INTERNAL_SCHEMA,
5721        oid: oid::INDEX_MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_TS_IND_OID,
5722        sql: "IN CLUSTER mz_catalog_server
5723    ON mz_internal.mz_object_arrangement_size_history (collection_timestamp)",
5724        is_retained_metrics_object: true,
5725    });
5726
5727/// Completed hydration episodes, one row per object, replica, and installation.
5728///
5729/// Exempt from the bootstrap reset and from forced shard replacement, since the
5730/// contents cannot be rebuilt from anything else. Schema evolution keeps them and
5731/// applies normally. Clearing them for a schema change is still allowed, see the
5732/// tripwire in `validate_migration_steps`.
5733pub static MZ_OBJECT_HYDRATION_HISTORY: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5734    name: "mz_object_hydration_history",
5735    schema: MZ_INTERNAL_SCHEMA,
5736    oid: oid::TABLE_MZ_OBJECT_HYDRATION_HISTORY_OID,
5737    desc: RelationDesc::builder()
5738        .with_column("object_id", SqlScalarType::String.nullable(false))
5739        .with_column("cluster_id", SqlScalarType::String.nullable(false))
5740        .with_column("replica_id", SqlScalarType::String.nullable(false))
5741        .with_column(
5742            "installed_at",
5743            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5744        )
5745        .with_column(
5746            "started_at",
5747            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5748        )
5749        .with_column(
5750            "hydrated_at",
5751            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5752        )
5753        .with_column("status", SqlScalarType::String.nullable(false))
5754        .finish(),
5755    column_comments: BTreeMap::from_iter([
5756        (
5757            "object_id",
5758            "The ID of the object's dataflow, as reported by the replica. Join `mz_internal.mz_object_global_ids` to reach the index or materialized view while that mapping exists. Dropping the dataflow retracts the mapping, so historical IDs may no longer resolve.",
5759        ),
5760        ("cluster_id", "The ID of the object's cluster."),
5761        (
5762            "replica_id",
5763            "The ID of the cluster replica. May name a replica that no longer exists.",
5764        ),
5765        (
5766            "installed_at",
5767            "When the object's dataflow was installed on the replica.",
5768        ),
5769        (
5770            "started_at",
5771            "When hydration work began, or `NULL` if the replica reported none. A replica that observed no start reports the installation time instead, so a zero interval between the two does not mean the dataflow started immediately.",
5772        ),
5773        ("hydrated_at", "When hydration finished."),
5774        (
5775            "status",
5776            "The terminal status. Currently always `hydrated`.",
5777        ),
5778    ]),
5779    // Not a retained-metrics object: that would pin a 30 day compaction window,
5780    // and our history lives in the rows, which the retention sweep retracts on
5781    // its own schedule. Nothing reads this table at an old timestamp.
5782    is_retained_metrics_object: false,
5783    access: vec![PUBLIC_SELECT],
5784    ontology: Some(Ontology {
5785        entity_name: "object_hydration_event",
5786        description: "Completed hydration of an index or materialized view on a replica",
5787        // NOTE: These references outlive what they point at. A row deliberately
5788        // survives the object and the replica it describes, so resolving one
5789        // against the catalog can come up empty.
5790        links: &const {
5791            [
5792                OntologyLink {
5793                    name: "hydration_of_dataflow",
5794                    target: "object_global_id",
5795                    properties: LinkProperties::fk_typed(
5796                        "object_id",
5797                        "global_id",
5798                        Cardinality::ManyToOne,
5799                        mz_repr::SemanticType::GlobalId,
5800                    ),
5801                },
5802                OntologyLink {
5803                    name: "hydrated_on_cluster",
5804                    target: "cluster",
5805                    properties: LinkProperties::fk("cluster_id", "id", Cardinality::ManyToOne),
5806                },
5807                OntologyLink {
5808                    name: "hydrated_on_replica",
5809                    target: "replica",
5810                    properties: LinkProperties::fk_typed(
5811                        "replica_id",
5812                        "id",
5813                        Cardinality::ManyToOne,
5814                        mz_repr::SemanticType::ReplicaId,
5815                    ),
5816                },
5817            ]
5818        },
5819        column_semantic_types: &[
5820            ("object_id", SemanticType::GlobalId),
5821            ("cluster_id", SemanticType::ClusterId),
5822            ("replica_id", SemanticType::ReplicaId),
5823        ],
5824    }),
5825});
5826
5827/// Successful hydration episodes for cluster replicas.
5828///
5829/// Exempt from the bootstrap reset and from forced shard replacement, since the
5830/// contents cannot be rebuilt from anything else. Schema evolution keeps them and
5831/// applies normally. Clearing them for a schema change is still allowed, see the
5832/// tripwire in `validate_migration_steps`.
5833pub static MZ_REPLICA_HYDRATION_HISTORY: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5834    name: "mz_replica_hydration_history",
5835    schema: MZ_INTERNAL_SCHEMA,
5836    oid: oid::TABLE_MZ_REPLICA_HYDRATION_HISTORY_OID,
5837    desc: RelationDesc::builder()
5838        .with_column("replica_id", SqlScalarType::String.nullable(false))
5839        .with_column("cluster_id", SqlScalarType::String.nullable(false))
5840        .with_column(
5841            "started_at",
5842            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5843        )
5844        .with_column(
5845            "finished_at",
5846            SqlScalarType::TimestampTz { precision: None }.nullable(true),
5847        )
5848        .with_column("object_count", SqlScalarType::UInt64.nullable(false))
5849        .with_column("peak_memory_bytes", SqlScalarType::UInt64.nullable(true))
5850        .with_column("peak_disk_bytes", SqlScalarType::UInt64.nullable(true))
5851        .with_column("status", SqlScalarType::String.nullable(false))
5852        .with_column("process_id", SqlScalarType::UInt64.nullable(true))
5853        .finish(),
5854    column_comments: BTreeMap::from_iter([
5855        (
5856            "replica_id",
5857            "The ID of the cluster replica. May name a replica that no longer exists.",
5858        ),
5859        ("cluster_id", "The ID of the replica's cluster."),
5860        (
5861            "started_at",
5862            "The earliest maintained compute dataflow installation in the hydration episode.",
5863        ),
5864        (
5865            "finished_at",
5866            "The latest maintained compute dataflow hydration in the hydration episode.",
5867        ),
5868        (
5869            "object_count",
5870            "The number of maintained compute dataflows in the hydration episode. Includes the replica's system introspection dataflows, so it exceeds the number of indexes and materialized views you created.",
5871        ),
5872        (
5873            "peak_memory_bytes",
5874            "The process-lifetime cgroup memory high-water mark when the collector recorded the episode. `NULL` if the platform reports no cgroup memory peak.",
5875        ),
5876        (
5877            "peak_disk_bytes",
5878            "The process-lifetime scratch-filesystem or swap high-water mark when the collector recorded the episode. Filesystem peaks are sampled lower bounds. `NULL` if neither measurement is available.",
5879        ),
5880        (
5881            "status",
5882            "The hydration episode's status. Currently always `hydrated`.",
5883        ),
5884        (
5885            "process_id",
5886            "The ID of a process within the replica. Episode timing and object_count are replica-wide and repeated for each process.",
5887        ),
5888    ]),
5889    // Not a retained-metrics object: that would pin a 30 day compaction window,
5890    // and our history lives in the rows, which the retention sweep retracts on
5891    // its own schedule. Nothing reads this table at an old timestamp.
5892    is_retained_metrics_object: false,
5893    access: vec![PUBLIC_SELECT],
5894    ontology: Some(Ontology {
5895        entity_name: "replica_hydration_episode",
5896        description: "Successful hydration episode on a cluster replica",
5897        links: &const {
5898            [
5899                OntologyLink {
5900                    name: "hydrated_on_cluster",
5901                    target: "cluster",
5902                    properties: LinkProperties::ForeignKey {
5903                        source_column: "cluster_id",
5904                        target_column: "id",
5905                        cardinality: Cardinality::ManyToOne,
5906                        source_id_type: None,
5907                        requires_mapping: None,
5908                        nullable: false,
5909                        note: Some(
5910                            "Hydration samples can outlive their cluster, so this reference may not resolve.",
5911                        ),
5912                        extra_key_columns: None,
5913                    },
5914                },
5915                OntologyLink {
5916                    name: "hydrated_on_replica",
5917                    target: "replica",
5918                    properties: LinkProperties::ForeignKey {
5919                        source_column: "replica_id",
5920                        target_column: "id",
5921                        cardinality: Cardinality::ManyToOne,
5922                        source_id_type: Some(mz_repr::SemanticType::ReplicaId),
5923                        requires_mapping: None,
5924                        nullable: false,
5925                        note: Some(
5926                            "Hydration samples can outlive their replica, so this reference may not resolve.",
5927                        ),
5928                        extra_key_columns: None,
5929                    },
5930                },
5931            ]
5932        },
5933        column_semantic_types: &[
5934            ("replica_id", SemanticType::ReplicaId),
5935            ("cluster_id", SemanticType::ClusterId),
5936        ],
5937    }),
5938});
5939
5940pub static MZ_COMPUTE_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5941    name: "mz_compute_hydration_statuses",
5942    schema: MZ_INTERNAL_SCHEMA,
5943    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_STATUSES_OID,
5944    desc: RelationDesc::builder()
5945        .with_column("object_id", SqlScalarType::String.nullable(false))
5946        .with_column("replica_id", SqlScalarType::String.nullable(false))
5947        .with_column("hydrated", SqlScalarType::Bool.nullable(false))
5948        .with_column("hydration_time", SqlScalarType::Interval.nullable(true))
5949        .finish(),
5950    column_comments: BTreeMap::from_iter([
5951        (
5952            "object_id",
5953            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`",
5954        ),
5955        ("replica_id", "The ID of a cluster replica."),
5956        (
5957            "hydrated",
5958            "Whether the compute object is hydrated on the replica.",
5959        ),
5960        (
5961            "hydration_time",
5962            "The amount of time it took for the replica to hydrate the compute object.",
5963        ),
5964    ]),
5965    sql: "
5966WITH
5967    dataflows AS (
5968        SELECT
5969            object_id,
5970            replica_id,
5971            time_ns IS NOT NULL AS hydrated,
5972            ((time_ns / 1000) || 'microseconds')::interval AS hydration_time
5973        FROM mz_internal.mz_compute_hydration_times
5974    ),
5975    -- MVs that have advanced to the empty frontier don't have a dataflow installed anymore and
5976    -- therefore don't show up in `mz_compute_hydration_times`. We still want to show them here to
5977    -- avoid surprises for people joining `mz_materialized_views` against this relation (like the
5978    -- blue-green readiness query does), so we include them as 'hydrated'.
5979    complete_mvs AS (
5980        SELECT
5981            mv.id,
5982            f.replica_id,
5983            true AS hydrated,
5984            NULL::interval AS hydration_time
5985        FROM mz_materialized_views mv
5986        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = mv.id
5987        WHERE f.write_frontier IS NULL
5988    )
5989SELECT * FROM dataflows
5990UNION ALL
5991SELECT * FROM complete_mvs",
5992    access: vec![PUBLIC_SELECT],
5993    ontology: Some(Ontology {
5994        entity_name: "compute_hydration_status_view",
5995        description: "Computed hydration status per compute object",
5996        links: &const { [] },
5997        column_semantic_types: &const {
5998            [
5999                ("object_id", SemanticType::GlobalId),
6000                ("replica_id", SemanticType::ReplicaId),
6001            ]
6002        },
6003    }),
6004});
6005
6006pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES: LazyLock<BuiltinSource> = LazyLock::new(|| {
6007    BuiltinSource {
6008        name: "mz_compute_operator_hydration_statuses",
6009        schema: MZ_INTERNAL_SCHEMA,
6010        oid: oid::SOURCE_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_OID,
6011        desc: RelationDesc::builder()
6012            .with_column("replica_id", SqlScalarType::String.nullable(false))
6013            .with_column("object_id", SqlScalarType::String.nullable(false))
6014            .with_column(
6015                "physical_plan_node_id",
6016                SqlScalarType::UInt64.nullable(false),
6017            )
6018            .with_column("hydrated", SqlScalarType::Bool.nullable(false))
6019            .with_key(vec![0, 1, 2])
6020            .finish(),
6021        data_source: IntrospectionType::ComputeOperatorHydrationStatus.into(),
6022        column_comments: BTreeMap::from_iter([
6023            ("replica_id", "The ID of a cluster replica."),
6024            (
6025                "object_id",
6026                "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`.",
6027            ),
6028            (
6029                "physical_plan_node_id",
6030                "The ID of a node in the physical plan of the compute object. Corresponds to a `node_id` displayed in the output of `EXPLAIN PHYSICAL PLAN WITH (node identifiers)`.",
6031            ),
6032            ("hydrated", "Whether the node is hydrated on the replica."),
6033        ]),
6034        is_retained_metrics_object: false,
6035        access: vec![PUBLIC_SELECT],
6036        ontology: Some(Ontology {
6037            entity_name: "compute_hydration_status",
6038            description: "Hydration status per compute operator",
6039            links: &const { [] },
6040            column_semantic_types: &const {
6041                [
6042                    ("replica_id", SemanticType::ReplicaId),
6043                    ("object_id", SemanticType::CatalogItemId),
6044                ]
6045            },
6046        }),
6047    }
6048});
6049
6050pub static MZ_CLUSTER_REPLICA_UTILIZATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6051    name: "mz_cluster_replica_utilization",
6052    schema: MZ_INTERNAL_SCHEMA,
6053    oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_OID,
6054    desc: RelationDesc::builder()
6055        .with_column("replica_id", SqlScalarType::String.nullable(false))
6056        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
6057        .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
6058        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
6059        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
6060        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
6061        .with_column("swap_percent", SqlScalarType::Float64.nullable(true))
6062        .finish(),
6063    column_comments: BTreeMap::from_iter([
6064        ("replica_id", "The ID of a cluster replica."),
6065        ("process_id", "The ID of a process within the replica."),
6066        (
6067            "cpu_percent",
6068            "Approximate CPU usage, in percent of the total allocation.",
6069        ),
6070        (
6071            "memory_percent",
6072            "Approximate RAM usage, in percent of the total allocation.",
6073        ),
6074        (
6075            "disk_percent",
6076            "Approximate disk usage, in percent of the total allocation.",
6077        ),
6078        (
6079            "heap_percent",
6080            "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
6081        ),
6082        (
6083            "swap_percent",
6084            "Approximate swap usage, in percent of the total heap allocation.",
6085        ),
6086    ]),
6087    sql: "
6088SELECT
6089    r.id AS replica_id,
6090    m.process_id,
6091    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
6092    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
6093    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
6094    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent,
6095    m.swap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS swap_percent
6096FROM
6097    mz_catalog.mz_cluster_replicas AS r
6098        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
6099        JOIN mz_internal.mz_cluster_replica_metrics AS m ON m.replica_id = r.id",
6100    access: vec![PUBLIC_SELECT],
6101    ontology: Some(Ontology {
6102        entity_name: "replica_utilization",
6103        description: "Computed utilization metrics per replica",
6104        links: &const {
6105            [OntologyLink {
6106                name: "utilization_of_replica",
6107                target: "replica",
6108                properties: LinkProperties::fk_typed(
6109                    "replica_id",
6110                    "id",
6111                    Cardinality::OneToOne,
6112                    mz_repr::SemanticType::CatalogItemId,
6113                ),
6114            }]
6115        },
6116        column_semantic_types: &[("replica_id", SemanticType::ReplicaId)],
6117    }),
6118});
6119
6120pub static MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY: LazyLock<BuiltinView> =
6121    LazyLock::new(|| BuiltinView {
6122        name: "mz_cluster_replica_utilization_history",
6123        schema: MZ_INTERNAL_SCHEMA,
6124        oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY_OID,
6125        desc: RelationDesc::builder()
6126            .with_column("replica_id", SqlScalarType::String.nullable(false))
6127            .with_column("process_id", SqlScalarType::UInt64.nullable(false))
6128            .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
6129            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
6130            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
6131            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
6132            .with_column("swap_percent", SqlScalarType::Float64.nullable(true))
6133            .with_column(
6134                "occurred_at",
6135                SqlScalarType::TimestampTz { precision: None }.nullable(false),
6136            )
6137            .finish(),
6138        column_comments: BTreeMap::from_iter([
6139            ("replica_id", "The ID of a cluster replica."),
6140            ("process_id", "The ID of a process within the replica."),
6141            (
6142                "cpu_percent",
6143                "Approximate CPU usage, in percent of the total allocation.",
6144            ),
6145            (
6146                "memory_percent",
6147                "Approximate RAM usage, in percent of the total allocation.",
6148            ),
6149            (
6150                "disk_percent",
6151                "Approximate disk usage, in percent of the total allocation.",
6152            ),
6153            (
6154                "heap_percent",
6155                "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
6156            ),
6157            (
6158                "swap_percent",
6159                "Approximate swap usage, in percent of the total heap allocation.",
6160            ),
6161            (
6162                "occurred_at",
6163                "Wall-clock timestamp at which the event occurred.",
6164            ),
6165        ]),
6166        sql: "
6167SELECT
6168    r.id AS replica_id,
6169    m.process_id,
6170    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
6171    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
6172    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
6173    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent,
6174    m.swap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS swap_percent,
6175    m.occurred_at
6176FROM
6177    mz_catalog.mz_cluster_replicas AS r
6178        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
6179        JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.id",
6180        access: vec![PUBLIC_SELECT],
6181        ontology: None,
6182    });
6183
6184pub static MZ_INDEX_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| {
6185    BuiltinView {
6186        name: "mz_index_advice",
6187        schema: MZ_INTERNAL_SCHEMA,
6188        oid: oid::VIEW_MZ_INDEX_ADVICE_OID,
6189        desc: RelationDesc::builder()
6190            .with_column("object_id", SqlScalarType::String.nullable(true))
6191            .with_column("hint", SqlScalarType::String.nullable(false))
6192            .with_column("details", SqlScalarType::String.nullable(false))
6193            .with_column("referenced_object_ids", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(true))
6194            .finish(),
6195        column_comments: BTreeMap::from_iter([
6196            ("object_id", "The ID of the object. Corresponds to mz_objects.id."),
6197            ("hint", "A suggestion to either change the object (e.g. create an index, turn a materialized view into an indexed view) or keep the object unchanged."),
6198            ("details", "Additional details on why the `hint` was proposed based on the dependencies of the object."),
6199            ("referenced_object_ids", "The IDs of objects referenced by `details`. Corresponds to mz_objects.id."),
6200        ]),
6201        sql: "
6202-- To avoid confusion with sources and sinks in the materialize sense,
6203-- the following uses the terms leafs (instead of sinks) and roots (instead of sources)
6204-- when referring to the object dependency graph.
6205--
6206-- The basic idea is to walk up the dependency graph to propagate the transitive dependencies
6207-- of maintained objected upwards. The leaves of the dependency graph are maintained objects
6208-- that are not depended on by other maintained objects and have a justification why they must
6209-- be maintained (e.g. a materialized view that is depended on by a sink).
6210-- Starting from these leaves, the dependencies are propagated upwards towards the roots according
6211-- to the object dependencies. Whenever there is a node that is being depended on by multiple
6212-- downstream objects, that node is marked to be converted into a maintained object and this
6213-- node is then propagated further up. Once completed, the list of objects that are marked as
6214-- maintained is checked against all objects to generate appropriate recommendations.
6215--
6216-- Note that the recommendations only incorporate dependencies between objects.
6217-- This can lead to bad recommendations, e.g. filters can no longer be pushed into (or close to)
6218-- a sink if an index is added in between the sink and the filter. For very selective filters,
6219-- this can lead to redundant work: the index is computing stuff only to discarded by the selective
6220-- filter later on. But these kind of aspects cannot be understood by merely looking at the
6221-- dependencies.
6222WITH MUTUALLY RECURSIVE
6223    -- for all objects, understand if they have an index on them and on which cluster they are running
6224    -- this avoids having different cases for views with an index and materialized views later on
6225    objects(id text, type text, cluster_id text, indexes text list) AS (
6226        -- views and materialized views without an index
6227        SELECT
6228            o.id,
6229            o.type,
6230            o.cluster_id,
6231            '{}'::text list AS indexes
6232        FROM mz_catalog.mz_objects o
6233        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view') AND NOT EXISTS (
6234            SELECT FROM mz_internal.mz_object_dependencies d
6235            JOIN mz_catalog.mz_objects AS i
6236                ON (i.id = d.object_id AND i.type = 'index')
6237            WHERE (o.id = d.referenced_object_id)
6238        )
6239
6240        UNION ALL
6241
6242        -- views and materialized views with an index
6243        SELECT
6244            o.id,
6245            o.type,
6246            -- o.cluster_id is always NULL for views, so use the cluster of the index instead
6247            COALESCE(o.cluster_id, i.cluster_id) AS cluster_id,
6248            list_agg(i.id) AS indexes
6249        FROM mz_catalog.mz_objects o
6250        JOIN mz_internal.mz_object_dependencies AS d
6251            ON (o.id = d.referenced_object_id)
6252        JOIN mz_catalog.mz_objects AS i
6253            ON (i.id = d.object_id AND i.type = 'index')
6254        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view', 'source')
6255        GROUP BY o.id, o.type, o.cluster_id, i.cluster_id
6256    ),
6257
6258    -- maintained objects that are at the leafs of the dependency graph with respect to a specific cluster
6259    maintained_leafs(id text, justification text) AS (
6260        -- materialized views that are connected to a sink
6261        SELECT
6262            m.id,
6263            s.id AS justification
6264        FROM objects AS m
6265        JOIN mz_internal.mz_object_dependencies AS d
6266            ON (m.id = d.referenced_object_id)
6267        JOIN mz_catalog.mz_objects AS s
6268            ON (s.id = d.object_id AND s.type = 'sink')
6269        WHERE m.type = 'materialized-view'
6270
6271        UNION ALL
6272
6273        -- (materialized) views with an index that are not transitively depend on by maintained objects on the same cluster
6274        SELECT
6275            v.id,
6276            unnest(v.indexes) AS justification
6277        FROM objects AS v
6278        WHERE v.type IN ('view', 'materialized-view', 'source') AND NOT EXISTS (
6279            SELECT FROM mz_internal.mz_object_transitive_dependencies AS d
6280            INNER JOIN mz_catalog.mz_objects AS child
6281                ON (d.object_id = child.id)
6282            WHERE d.referenced_object_id = v.id AND child.type IN ('materialized-view', 'index') AND v.cluster_id = child.cluster_id AND NOT v.indexes @> LIST[child.id]
6283        )
6284    ),
6285
6286    -- this is just a helper cte to union multiple lists as part of an aggregation, which is not directly possible in SQL
6287    agg_maintained_children(id text, maintained_children text list) AS (
6288        SELECT
6289            parent_id AS id,
6290            list_agg(maintained_child) AS maintained_leafs
6291        FROM (
6292            SELECT DISTINCT
6293                d.referenced_object_id AS parent_id,
6294                -- it's not possible to union lists in an aggregation, so we have to unnest the list first
6295                unnest(child.maintained_children) AS maintained_child
6296            FROM propagate_dependencies AS child
6297            INNER JOIN mz_internal.mz_object_dependencies AS d
6298                ON (child.id = d.object_id)
6299        )
6300        GROUP BY parent_id
6301    ),
6302
6303    -- propagate dependencies of maintained objects from the leafs to the roots of the dependency graph and
6304    -- record a justification when an object should be maintained, e.g. when it is depended on by more than one maintained object
6305    -- when an object should be maintained, maintained_children will just contain that object so that further upstream objects refer to it in their maintained_children
6306    propagate_dependencies(id text, maintained_children text list, justification text list) AS (
6307        -- base case: start with the leafs
6308        SELECT DISTINCT
6309            id,
6310            LIST[id] AS maintained_children,
6311            list_agg(justification) AS justification
6312        FROM maintained_leafs
6313        GROUP BY id
6314
6315        UNION
6316
6317        -- recursive case: if there is a child with the same dependencies as the parent,
6318        -- the parent is only reused by a single child
6319        SELECT
6320            parent.id,
6321            child.maintained_children,
6322            NULL::text list AS justification
6323        FROM agg_maintained_children AS parent
6324        INNER JOIN mz_internal.mz_object_dependencies AS d
6325            ON (parent.id = d.referenced_object_id)
6326        INNER JOIN propagate_dependencies AS child
6327            ON (d.object_id = child.id)
6328        WHERE parent.maintained_children = child.maintained_children
6329
6330        UNION
6331
6332        -- recursive case: if there is NO child with the same dependencies as the parent,
6333        -- different children are reusing the parent so maintaining the object is justified by itself
6334        SELECT DISTINCT
6335            parent.id,
6336            LIST[parent.id] AS maintained_children,
6337            parent.maintained_children AS justification
6338        FROM agg_maintained_children AS parent
6339        WHERE NOT EXISTS (
6340            SELECT FROM mz_internal.mz_object_dependencies AS d
6341            INNER JOIN propagate_dependencies AS child
6342                ON (d.object_id = child.id AND d.referenced_object_id = parent.id)
6343            WHERE parent.maintained_children = child.maintained_children
6344        )
6345    ),
6346
6347    objects_with_justification(id text, type text, cluster_id text, maintained_children text list, justification text list, indexes text list) AS (
6348        SELECT
6349            p.id,
6350            o.type,
6351            o.cluster_id,
6352            p.maintained_children,
6353            p.justification,
6354            o.indexes
6355        FROM propagate_dependencies p
6356        JOIN objects AS o
6357            ON (p.id = o.id)
6358    ),
6359
6360    hints(id text, hint text, details text, justification text list) AS (
6361        -- materialized views that are not required
6362        SELECT
6363            id,
6364            'convert to a view' AS hint,
6365            'no dependencies from sinks nor from objects on different clusters' AS details,
6366            justification
6367        FROM objects_with_justification
6368        WHERE type = 'materialized-view' AND justification IS NULL
6369
6370        UNION ALL
6371
6372        -- materialized views that are required because a sink or a maintained object from a different cluster depends on them
6373        SELECT
6374            id,
6375            'keep' AS hint,
6376            'dependencies from sinks or objects on different clusters: ' AS details,
6377            justification
6378        FROM objects_with_justification AS m
6379        WHERE type = 'materialized-view' AND justification IS NOT NULL AND EXISTS (
6380            SELECT FROM unnest(justification) AS dependency
6381            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
6382
6383            UNION ALL
6384
6385            SELECT FROM unnest(justification) AS dependency
6386            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
6387            WHERE d.cluster_id != m.cluster_id
6388        )
6389
6390        UNION ALL
6391
6392        -- materialized views that can be converted to a view with or without an index because NO sink or a maintained object from a different cluster depends on them
6393        SELECT
6394            id,
6395            'convert to a view with an index' AS hint,
6396            'no dependencies from sinks nor from objects on different clusters, but maintained dependencies on the same cluster: ' AS details,
6397            justification
6398        FROM objects_with_justification AS m
6399        WHERE type = 'materialized-view' AND justification IS NOT NULL AND NOT EXISTS (
6400            SELECT FROM unnest(justification) AS dependency
6401            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
6402
6403            UNION ALL
6404
6405            SELECT FROM unnest(justification) AS dependency
6406            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
6407            WHERE d.cluster_id != m.cluster_id
6408        )
6409
6410        UNION ALL
6411
6412        -- views that have indexes on different clusters should be a materialized view
6413        SELECT
6414            o.id,
6415            'convert to materialized view' AS hint,
6416            'dependencies on multiple clusters: ' AS details,
6417            o.justification
6418        FROM objects_with_justification o,
6419            LATERAL unnest(o.justification) j
6420        LEFT JOIN mz_catalog.mz_objects AS m
6421            ON (m.id = j AND m.type IN ('index', 'materialized-view'))
6422        WHERE o.type = 'view' AND o.justification IS NOT NULL
6423        GROUP BY o.id, o.justification
6424        HAVING count(DISTINCT m.cluster_id) >= 2
6425
6426        UNION ALL
6427
6428        -- views without an index that should be maintained
6429        SELECT
6430            id,
6431            'add index' AS hint,
6432            'multiple downstream dependencies: ' AS details,
6433            justification
6434        FROM objects_with_justification
6435        WHERE type = 'view' AND justification IS NOT NULL AND indexes = '{}'::text list
6436
6437        UNION ALL
6438
6439        -- index inside the dependency graph (not a leaf)
6440        SELECT
6441            unnest(indexes) AS id,
6442            'drop unless queried directly' AS hint,
6443            'fewer than two downstream dependencies: ' AS details,
6444            maintained_children AS justification
6445        FROM objects_with_justification
6446        WHERE type = 'view' AND NOT indexes = '{}'::text list AND justification IS NULL
6447
6448        UNION ALL
6449
6450        -- index on a leaf of the dependency graph
6451        SELECT
6452            unnest(indexes) AS id,
6453            'drop unless queried directly' AS hint,
6454            'associated object does not have any dependencies (maintained or not maintained)' AS details,
6455            NULL::text list AS justification
6456        FROM objects_with_justification
6457        -- indexes can only be part of justification for leaf nodes
6458        WHERE type IN ('view', 'materialized-view') AND NOT indexes = '{}'::text list AND justification @> indexes
6459
6460        UNION ALL
6461
6462        -- index on a source
6463        SELECT
6464            unnest(indexes) AS id,
6465            'drop unless queried directly' AS hint,
6466            'sources do not transform data and can expose data directly' AS details,
6467            NULL::text list AS justification
6468        FROM objects_with_justification
6469        -- indexes can only be part of justification for leaf nodes
6470        WHERE type = 'source' AND NOT indexes = '{}'::text list
6471
6472        UNION ALL
6473
6474        -- indexes on views inside the dependency graph
6475        SELECT
6476            unnest(indexes) AS id,
6477            'keep' AS hint,
6478            'multiple downstream dependencies: ' AS details,
6479            justification
6480        FROM objects_with_justification
6481        -- indexes can only be part of justification for leaf nodes
6482        WHERE type = 'view' AND justification IS NOT NULL AND NOT indexes = '{}'::text list AND NOT justification @> indexes
6483    ),
6484
6485    hints_resolved_ids(id text, hint text, details text, justification text list) AS (
6486        SELECT
6487            h.id,
6488            h.hint,
6489            h.details || list_agg(o.name)::text AS details,
6490            h.justification
6491        FROM hints AS h,
6492            LATERAL unnest(h.justification) j
6493        JOIN mz_catalog.mz_objects AS o
6494            ON (o.id = j)
6495        GROUP BY h.id, h.hint, h.details, h.justification
6496
6497        UNION ALL
6498
6499        SELECT
6500            id,
6501            hint,
6502            details,
6503            justification
6504        FROM hints
6505        WHERE justification IS NULL
6506    )
6507
6508SELECT
6509    h.id AS object_id,
6510    h.hint AS hint,
6511    h.details,
6512    h.justification AS referenced_object_ids
6513FROM hints_resolved_ids AS h",
6514        access: vec![PUBLIC_SELECT],
6515        ontology: None,
6516    }
6517});
6518
6519/// Peeled version of `PG_AUTHID`: Excludes the columns rolcreaterole and rolcreatedb, to make this
6520/// view indexable.
6521pub static PG_AUTHID_CORE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6522    name: "pg_authid_core",
6523    schema: MZ_INTERNAL_SCHEMA,
6524    oid: oid::VIEW_PG_AUTHID_CORE_OID,
6525    desc: RelationDesc::builder()
6526        .with_column("oid", SqlScalarType::Oid.nullable(false))
6527        .with_column("rolname", SqlScalarType::String.nullable(false))
6528        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
6529        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
6530        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
6531        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
6532        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
6533        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
6534        .with_column("rolpassword", SqlScalarType::String.nullable(true))
6535        .with_column(
6536            "rolvaliduntil",
6537            SqlScalarType::TimestampTz { precision: None }.nullable(true),
6538        )
6539        .finish(),
6540    column_comments: BTreeMap::new(),
6541    sql: r#"
6542SELECT
6543    r.oid AS oid,
6544    r.name AS rolname,
6545    rolsuper,
6546    inherit AS rolinherit,
6547    COALESCE(r.rolcanlogin, false) AS rolcanlogin,
6548    -- MZ doesn't support replication in the same way Postgres does
6549    false AS rolreplication,
6550    -- MZ doesn't how row level security
6551    false AS rolbypassrls,
6552    -- MZ doesn't have a connection limit
6553    -1 AS rolconnlimit,
6554    a.password_hash AS rolpassword,
6555    NULL::pg_catalog.timestamptz AS rolvaliduntil
6556FROM mz_catalog.mz_roles r
6557LEFT JOIN mz_catalog.mz_role_auth a ON r.oid = a.role_oid"#,
6558    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
6559    ontology: None,
6560});
6561
6562pub const PG_AUTHID_CORE_IND: BuiltinIndex = BuiltinIndex {
6563    name: "pg_authid_core_ind",
6564    schema: MZ_INTERNAL_SCHEMA,
6565    oid: oid::INDEX_PG_AUTHID_CORE_IND_OID,
6566    sql: "IN CLUSTER mz_catalog_server
6567ON mz_internal.pg_authid_core (rolname)",
6568    is_retained_metrics_object: false,
6569};
6570
6571pub static MZ_SHOW_ALL_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6572    name: "mz_show_all_objects",
6573    schema: MZ_INTERNAL_SCHEMA,
6574    oid: oid::VIEW_MZ_SHOW_ALL_OBJECTS_OID,
6575    desc: RelationDesc::builder()
6576        .with_column("schema_id", SqlScalarType::String.nullable(false))
6577        .with_column("name", SqlScalarType::String.nullable(false))
6578        .with_column("type", SqlScalarType::String.nullable(false))
6579        .with_column("comment", SqlScalarType::String.nullable(false))
6580        .finish(),
6581    column_comments: BTreeMap::new(),
6582    sql: "WITH comments AS (
6583        SELECT id, object_type, comment
6584        FROM mz_internal.mz_comments
6585        WHERE object_sub_id IS NULL
6586    )
6587    SELECT schema_id, name, type, COALESCE(comment, '') AS comment
6588    FROM mz_catalog.mz_objects AS objs
6589    LEFT JOIN comments ON objs.id = comments.id AND comments.object_type = objs.type",
6590    access: vec![PUBLIC_SELECT],
6591    ontology: None,
6592});
6593
6594pub static MZ_SHOW_CLUSTERS: LazyLock<BuiltinView> = LazyLock::new(|| {
6595    BuiltinView {
6596    name: "mz_show_clusters",
6597    schema: MZ_INTERNAL_SCHEMA,
6598    oid: oid::VIEW_MZ_SHOW_CLUSTERS_OID,
6599    desc: RelationDesc::builder()
6600        .with_column("name", SqlScalarType::String.nullable(false))
6601        .with_column("replicas", SqlScalarType::String.nullable(true))
6602        // One-line summary of any in-flight reconfiguration or burst, NULL
6603        // when the cluster is steady.
6604        .with_column("activity", SqlScalarType::String.nullable(true))
6605        .with_column("comment", SqlScalarType::String.nullable(false))
6606        .finish(),
6607    column_comments: BTreeMap::new(),
6608    // Settled reconfiguration records are retained, so match only
6609    // `in-progress`. A non-null auto-scaling `state` means a live burst.
6610    // The reconfiguration summary names only the dimensions the record
6611    // actually changes (from `changes`), with values where they read well.
6612    // NOTE: `||` with a NULL operand nulls the whole summary. `burst_size`
6613    // is a non-optional field of its record, keep it that way or COALESCE.
6614    // The NULLIF guards an empty diff (not expected in-progress), which
6615    // otherwise would render a dangling 'reconfiguring'.
6616    // Neither input needs `mz_now()`, keeping this indexed view non-temporal.
6617    sql: "
6618    WITH clusters AS (
6619        SELECT
6620            mc.id,
6621            mc.name,
6622            pg_catalog.string_agg(mcr.name || ' (' || mcr.size || ')', ', ' ORDER BY mcr.name) AS replicas
6623        FROM mz_catalog.mz_clusters mc
6624        LEFT JOIN mz_catalog.mz_cluster_replicas mcr
6625        ON mc.id = mcr.cluster_id
6626        GROUP BY mc.id, mc.name
6627    ),
6628    comments AS (
6629        SELECT id, comment
6630        FROM mz_internal.mz_comments
6631        WHERE object_type = 'cluster' AND object_sub_id IS NULL
6632    ),
6633    reconfigurations AS (
6634        SELECT
6635            cluster_id,
6636            'reconfiguring ' || NULLIF(array_to_string(ARRAY[
6637                'size to ' || (changes->>'size'),
6638                'replication factor to ' || (changes->>'replication_factor'),
6639                CASE WHEN changes->'availability_zones' IS NOT NULL THEN 'availability zones' END,
6640                CASE WHEN changes->'logging' IS NOT NULL THEN 'introspection settings' END,
6641                CASE WHEN changes->'arrangement_compression' IS NOT NULL THEN 'arrangement compression' END
6642            ], ', '), '') AS summary
6643        FROM mz_internal.mz_cluster_reconfigurations
6644        WHERE status = 'in-progress'
6645    )
6646    SELECT
6647        name,
6648        replicas,
6649        CASE
6650            WHEN recon.summary IS NOT NULL AND scaling.state IS NOT NULL
6651                THEN recon.summary
6652                     || '; hydration burst at ' || (scaling.state->'burst'->>'burst_size')
6653            WHEN recon.summary IS NOT NULL
6654                THEN recon.summary
6655            WHEN scaling.state IS NOT NULL
6656                THEN 'hydration burst at ' || (scaling.state->'burst'->>'burst_size')
6657            ELSE NULL
6658        END AS activity,
6659        COALESCE(comment, '') as comment
6660    FROM clusters
6661    LEFT JOIN comments ON clusters.id = comments.id
6662    LEFT JOIN reconfigurations recon
6663        ON clusters.id = recon.cluster_id
6664    LEFT JOIN mz_internal.mz_cluster_auto_scaling_strategies scaling ON clusters.id = scaling.cluster_id",
6665    access: vec![PUBLIC_SELECT],
6666    ontology: None,
6667}
6668});
6669
6670pub static MZ_SHOW_SECRETS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6671    name: "mz_show_secrets",
6672    schema: MZ_INTERNAL_SCHEMA,
6673    oid: oid::VIEW_MZ_SHOW_SECRETS_OID,
6674    desc: RelationDesc::builder()
6675        .with_column("schema_id", SqlScalarType::String.nullable(false))
6676        .with_column("name", SqlScalarType::String.nullable(false))
6677        .with_column("comment", SqlScalarType::String.nullable(false))
6678        .finish(),
6679    column_comments: BTreeMap::new(),
6680    sql: "WITH comments AS (
6681        SELECT id, comment
6682        FROM mz_internal.mz_comments
6683        WHERE object_type = 'secret' AND object_sub_id IS NULL
6684    )
6685    SELECT schema_id, name, COALESCE(comment, '') as comment
6686    FROM mz_catalog.mz_secrets secrets
6687    LEFT JOIN comments ON secrets.id = comments.id",
6688    access: vec![PUBLIC_SELECT],
6689    ontology: None,
6690});
6691
6692pub static MZ_SHOW_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| {
6693    BuiltinView {
6694    name: "mz_show_columns",
6695    schema: MZ_INTERNAL_SCHEMA,
6696    oid: oid::VIEW_MZ_SHOW_COLUMNS_OID,
6697    desc: RelationDesc::builder()
6698        .with_column("id", SqlScalarType::String.nullable(false))
6699        .with_column("name", SqlScalarType::String.nullable(false))
6700        .with_column("nullable", SqlScalarType::Bool.nullable(false))
6701        .with_column("type", SqlScalarType::String.nullable(false))
6702        .with_column("position", SqlScalarType::UInt64.nullable(false))
6703        .with_column("comment", SqlScalarType::String.nullable(false))
6704        .finish(),
6705    column_comments: BTreeMap::new(),
6706    // The `object_type` predicate on the comment join guards against
6707    // stale comment rows that can survive when a builtin's type changes
6708    // but its catalog id is preserved (e.g. a Table → MaterializedView
6709    // schema migration). Without it, a column would match both the old
6710    // and new object_type rows and each row would be emitted twice.
6711    sql: "
6712    SELECT columns.id, columns.name, columns.nullable, columns.type, columns.position, COALESCE(comment, '') as comment
6713    FROM mz_catalog.mz_columns columns
6714    LEFT JOIN mz_catalog.mz_objects obj ON obj.id = columns.id
6715    LEFT JOIN mz_internal.mz_comments comments
6716    ON columns.id = comments.id
6717       AND columns.position = comments.object_sub_id
6718       AND comments.object_type = obj.type",
6719    access: vec![PUBLIC_SELECT],
6720    ontology: None,
6721}
6722});
6723
6724pub static MZ_SHOW_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6725    name: "mz_show_databases",
6726    schema: MZ_INTERNAL_SCHEMA,
6727    oid: oid::VIEW_MZ_SHOW_DATABASES_OID,
6728    desc: RelationDesc::builder()
6729        .with_column("name", SqlScalarType::String.nullable(false))
6730        .with_column("comment", SqlScalarType::String.nullable(false))
6731        .finish(),
6732    column_comments: BTreeMap::new(),
6733    sql: "WITH comments AS (
6734        SELECT id, comment
6735        FROM mz_internal.mz_comments
6736        WHERE object_type = 'database' AND object_sub_id IS NULL
6737    )
6738    SELECT name, COALESCE(comment, '') as comment
6739    FROM mz_catalog.mz_databases databases
6740    LEFT JOIN comments ON databases.id = comments.id",
6741    access: vec![PUBLIC_SELECT],
6742    ontology: None,
6743});
6744
6745pub static MZ_SHOW_SCHEMAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6746    name: "mz_show_schemas",
6747    schema: MZ_INTERNAL_SCHEMA,
6748    oid: oid::VIEW_MZ_SHOW_SCHEMAS_OID,
6749    desc: RelationDesc::builder()
6750        .with_column("database_id", SqlScalarType::String.nullable(true))
6751        .with_column("name", SqlScalarType::String.nullable(false))
6752        .with_column("comment", SqlScalarType::String.nullable(false))
6753        .finish(),
6754    column_comments: BTreeMap::new(),
6755    sql: "WITH comments AS (
6756        SELECT id, comment
6757        FROM mz_internal.mz_comments
6758        WHERE object_type = 'schema' AND object_sub_id IS NULL
6759    )
6760    SELECT database_id, name, COALESCE(comment, '') as comment
6761    FROM mz_catalog.mz_schemas schemas
6762    LEFT JOIN comments ON schemas.id = comments.id",
6763    access: vec![PUBLIC_SELECT],
6764    ontology: None,
6765});
6766
6767pub static MZ_SHOW_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6768    name: "mz_show_roles",
6769    schema: MZ_INTERNAL_SCHEMA,
6770    oid: oid::VIEW_MZ_SHOW_ROLES_OID,
6771    desc: RelationDesc::builder()
6772        .with_column("name", SqlScalarType::String.nullable(false))
6773        .with_column("comment", SqlScalarType::String.nullable(false))
6774        .finish(),
6775    column_comments: BTreeMap::new(),
6776    sql: "WITH comments AS (
6777        SELECT id, comment
6778        FROM mz_internal.mz_comments
6779        WHERE object_type = 'role' AND object_sub_id IS NULL
6780    )
6781    SELECT name, COALESCE(comment, '') as comment
6782    FROM mz_catalog.mz_roles roles
6783    LEFT JOIN comments ON roles.id = comments.id
6784    WHERE roles.id NOT LIKE 's%'
6785      AND roles.id NOT LIKE 'g%'",
6786    access: vec![PUBLIC_SELECT],
6787    ontology: None,
6788});
6789
6790pub static MZ_SHOW_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6791    name: "mz_show_tables",
6792    schema: MZ_INTERNAL_SCHEMA,
6793    oid: oid::VIEW_MZ_SHOW_TABLES_OID,
6794    desc: RelationDesc::builder()
6795        .with_column("schema_id", SqlScalarType::String.nullable(false))
6796        .with_column("name", SqlScalarType::String.nullable(false))
6797        .with_column("comment", SqlScalarType::String.nullable(false))
6798        .with_column("source_id", SqlScalarType::String.nullable(true))
6799        .finish(),
6800    column_comments: BTreeMap::new(),
6801    sql: "WITH comments AS (
6802        SELECT id, comment
6803        FROM mz_internal.mz_comments
6804        WHERE object_type = 'table' AND object_sub_id IS NULL
6805    )
6806    SELECT schema_id, name, COALESCE(comment, '') as comment, source_id
6807    FROM mz_catalog.mz_tables tables
6808    LEFT JOIN comments ON tables.id = comments.id",
6809    access: vec![PUBLIC_SELECT],
6810    ontology: None,
6811});
6812
6813pub static MZ_SHOW_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6814    name: "mz_show_views",
6815    schema: MZ_INTERNAL_SCHEMA,
6816    oid: oid::VIEW_MZ_SHOW_VIEWS_OID,
6817    desc: RelationDesc::builder()
6818        .with_column("schema_id", SqlScalarType::String.nullable(false))
6819        .with_column("name", SqlScalarType::String.nullable(false))
6820        .with_column("comment", SqlScalarType::String.nullable(false))
6821        .finish(),
6822    column_comments: BTreeMap::new(),
6823    sql: "WITH comments AS (
6824        SELECT id, comment
6825        FROM mz_internal.mz_comments
6826        WHERE object_type = 'view' AND object_sub_id IS NULL
6827    )
6828    SELECT schema_id, name, COALESCE(comment, '') as comment
6829    FROM mz_catalog.mz_views views
6830    LEFT JOIN comments ON views.id = comments.id",
6831    access: vec![PUBLIC_SELECT],
6832    ontology: None,
6833});
6834
6835pub static MZ_SHOW_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6836    name: "mz_show_types",
6837    schema: MZ_INTERNAL_SCHEMA,
6838    oid: oid::VIEW_MZ_SHOW_TYPES_OID,
6839    desc: RelationDesc::builder()
6840        .with_column("schema_id", SqlScalarType::String.nullable(false))
6841        .with_column("name", SqlScalarType::String.nullable(false))
6842        .with_column("comment", SqlScalarType::String.nullable(false))
6843        .finish(),
6844    column_comments: BTreeMap::new(),
6845    sql: "WITH comments AS (
6846        SELECT id, comment
6847        FROM mz_internal.mz_comments
6848        WHERE object_type = 'type' AND object_sub_id IS NULL
6849    )
6850    SELECT schema_id, name, COALESCE(comment, '') as comment
6851    FROM mz_catalog.mz_types types
6852    LEFT JOIN comments ON types.id = comments.id",
6853    access: vec![PUBLIC_SELECT],
6854    ontology: None,
6855});
6856
6857pub static MZ_SHOW_CONNECTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6858    name: "mz_show_connections",
6859    schema: MZ_INTERNAL_SCHEMA,
6860    oid: oid::VIEW_MZ_SHOW_CONNECTIONS_OID,
6861    desc: RelationDesc::builder()
6862        .with_column("schema_id", SqlScalarType::String.nullable(false))
6863        .with_column("name", SqlScalarType::String.nullable(false))
6864        .with_column("type", SqlScalarType::String.nullable(false))
6865        .with_column("comment", SqlScalarType::String.nullable(false))
6866        .finish(),
6867    column_comments: BTreeMap::new(),
6868    sql: "WITH comments AS (
6869        SELECT id, comment
6870        FROM mz_internal.mz_comments
6871        WHERE object_type = 'connection' AND object_sub_id IS NULL
6872    )
6873    SELECT schema_id, name, type, COALESCE(comment, '') as comment
6874    FROM mz_catalog.mz_connections connections
6875    LEFT JOIN comments ON connections.id = comments.id",
6876    access: vec![PUBLIC_SELECT],
6877    ontology: None,
6878});
6879
6880pub static MZ_SHOW_SOURCES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6881    name: "mz_show_sources",
6882    schema: MZ_INTERNAL_SCHEMA,
6883    oid: oid::VIEW_MZ_SHOW_SOURCES_OID,
6884    desc: RelationDesc::builder()
6885        .with_column("id", SqlScalarType::String.nullable(false))
6886        .with_column("name", SqlScalarType::String.nullable(false))
6887        .with_column("type", SqlScalarType::String.nullable(false))
6888        .with_column("cluster", SqlScalarType::String.nullable(true))
6889        .with_column("schema_id", SqlScalarType::String.nullable(false))
6890        .with_column("cluster_id", SqlScalarType::String.nullable(true))
6891        .with_column("comment", SqlScalarType::String.nullable(false))
6892        .finish(),
6893    column_comments: BTreeMap::new(),
6894    sql: "
6895WITH comments AS (
6896    SELECT id, comment
6897    FROM mz_internal.mz_comments
6898    WHERE object_type = 'source' AND object_sub_id IS NULL
6899)
6900SELECT
6901    sources.id,
6902    sources.name,
6903    sources.type,
6904    clusters.name AS cluster,
6905    schema_id,
6906    cluster_id,
6907    COALESCE(comments.comment, '') as comment
6908FROM
6909    mz_catalog.mz_sources AS sources
6910        LEFT JOIN
6911            mz_catalog.mz_clusters AS clusters
6912            ON clusters.id = sources.cluster_id
6913        LEFT JOIN comments ON sources.id = comments.id",
6914    access: vec![PUBLIC_SELECT],
6915    ontology: None,
6916});
6917
6918pub static MZ_SHOW_SINKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6919    name: "mz_show_sinks",
6920    schema: MZ_INTERNAL_SCHEMA,
6921    oid: oid::VIEW_MZ_SHOW_SINKS_OID,
6922    desc: RelationDesc::builder()
6923        .with_column("id", SqlScalarType::String.nullable(false))
6924        .with_column("name", SqlScalarType::String.nullable(false))
6925        .with_column("type", SqlScalarType::String.nullable(false))
6926        .with_column("cluster", SqlScalarType::String.nullable(false))
6927        .with_column("schema_id", SqlScalarType::String.nullable(false))
6928        .with_column("cluster_id", SqlScalarType::String.nullable(false))
6929        .with_column("comment", SqlScalarType::String.nullable(false))
6930        .finish(),
6931    column_comments: BTreeMap::new(),
6932    sql: "
6933WITH comments AS (
6934    SELECT id, comment
6935    FROM mz_internal.mz_comments
6936    WHERE object_type = 'sink' AND object_sub_id IS NULL
6937)
6938SELECT
6939    sinks.id,
6940    sinks.name,
6941    sinks.type,
6942    clusters.name AS cluster,
6943    schema_id,
6944    cluster_id,
6945    COALESCE(comments.comment, '') as comment
6946FROM
6947    mz_catalog.mz_sinks AS sinks
6948    JOIN
6949        mz_catalog.mz_clusters AS clusters
6950        ON clusters.id = sinks.cluster_id
6951    LEFT JOIN comments ON sinks.id = comments.id",
6952    access: vec![PUBLIC_SELECT],
6953    ontology: None,
6954});
6955
6956pub static MZ_SHOW_MATERIALIZED_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6957    name: "mz_show_materialized_views",
6958    schema: MZ_INTERNAL_SCHEMA,
6959    oid: oid::VIEW_MZ_SHOW_MATERIALIZED_VIEWS_OID,
6960    desc: RelationDesc::builder()
6961        .with_column("id", SqlScalarType::String.nullable(false))
6962        .with_column("name", SqlScalarType::String.nullable(false))
6963        .with_column("cluster", SqlScalarType::String.nullable(false))
6964        .with_column("schema_id", SqlScalarType::String.nullable(false))
6965        .with_column("cluster_id", SqlScalarType::String.nullable(false))
6966        .with_column("comment", SqlScalarType::String.nullable(false))
6967        .finish(),
6968    column_comments: BTreeMap::new(),
6969    sql: "
6970WITH
6971    comments AS (
6972        SELECT id, comment
6973        FROM mz_internal.mz_comments
6974        WHERE object_type = 'materialized-view' AND object_sub_id IS NULL
6975    )
6976SELECT
6977    mviews.id as id,
6978    mviews.name,
6979    clusters.name AS cluster,
6980    schema_id,
6981    cluster_id,
6982    COALESCE(comments.comment, '') as comment
6983FROM
6984    mz_catalog.mz_materialized_views AS mviews
6985    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = mviews.cluster_id
6986    LEFT JOIN comments ON mviews.id = comments.id",
6987    access: vec![PUBLIC_SELECT],
6988    ontology: None,
6989});
6990
6991pub static MZ_SHOW_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6992    name: "mz_show_indexes",
6993    schema: MZ_INTERNAL_SCHEMA,
6994    oid: oid::VIEW_MZ_SHOW_INDEXES_OID,
6995    desc: RelationDesc::builder()
6996        .with_column("id", SqlScalarType::String.nullable(false))
6997        .with_column("name", SqlScalarType::String.nullable(false))
6998        .with_column("on", SqlScalarType::String.nullable(false))
6999        .with_column("cluster", SqlScalarType::String.nullable(false))
7000        .with_column(
7001            "key",
7002            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
7003        )
7004        .with_column("on_id", SqlScalarType::String.nullable(false))
7005        .with_column("schema_id", SqlScalarType::String.nullable(false))
7006        .with_column("cluster_id", SqlScalarType::String.nullable(false))
7007        .with_column("comment", SqlScalarType::String.nullable(false))
7008        .finish(),
7009    column_comments: BTreeMap::new(),
7010    sql: "
7011WITH comments AS (
7012    SELECT id, comment
7013    FROM mz_internal.mz_comments
7014    WHERE object_type = 'index' AND object_sub_id IS NULL
7015)
7016SELECT
7017    idxs.id AS id,
7018    idxs.name AS name,
7019    objs.name AS on,
7020    clusters.name AS cluster,
7021    COALESCE(keys.key, '{}'::_text) AS key,
7022    idxs.on_id AS on_id,
7023    objs.schema_id AS schema_id,
7024    clusters.id AS cluster_id,
7025    COALESCE(comments.comment, '') as comment
7026FROM
7027    mz_catalog.mz_indexes AS idxs
7028    JOIN mz_catalog.mz_objects AS objs ON idxs.on_id = objs.id
7029    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = idxs.cluster_id
7030    LEFT JOIN
7031        (SELECT
7032            idxs.id,
7033            ARRAY_AGG(
7034                CASE
7035                    WHEN idx_cols.on_expression IS NULL THEN obj_cols.name
7036                    ELSE idx_cols.on_expression
7037                END
7038                ORDER BY idx_cols.index_position ASC
7039            ) AS key
7040        FROM
7041            mz_catalog.mz_indexes AS idxs
7042            JOIN mz_catalog.mz_index_columns idx_cols ON idxs.id = idx_cols.index_id
7043            LEFT JOIN mz_catalog.mz_columns obj_cols ON
7044                idxs.on_id = obj_cols.id AND idx_cols.on_position = obj_cols.position
7045        GROUP BY idxs.id) AS keys
7046    ON idxs.id = keys.id
7047    LEFT JOIN comments ON idxs.id = comments.id",
7048    access: vec![PUBLIC_SELECT],
7049    ontology: None,
7050});
7051
7052pub static MZ_SHOW_CLUSTER_REPLICAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7053    name: "mz_show_cluster_replicas",
7054    schema: MZ_INTERNAL_SCHEMA,
7055    oid: oid::VIEW_MZ_SHOW_CLUSTER_REPLICAS_OID,
7056    desc: RelationDesc::builder()
7057        .with_column("cluster", SqlScalarType::String.nullable(false))
7058        .with_column("replica", SqlScalarType::String.nullable(false))
7059        .with_column("replica_id", SqlScalarType::String.nullable(false))
7060        .with_column("size", SqlScalarType::String.nullable(true))
7061        .with_column("ready", SqlScalarType::Bool.nullable(false))
7062        .with_column("comment", SqlScalarType::String.nullable(false))
7063        .finish(),
7064    column_comments: BTreeMap::new(),
7065    sql: r#"SELECT
7066    mz_catalog.mz_clusters.name AS cluster,
7067    mz_catalog.mz_cluster_replicas.name AS replica,
7068    mz_catalog.mz_cluster_replicas.id as replica_id,
7069    mz_catalog.mz_cluster_replicas.size AS size,
7070    coalesce(statuses.ready, FALSE) AS ready,
7071    coalesce(comments.comment, '') as comment
7072FROM
7073    mz_catalog.mz_cluster_replicas
7074        JOIN mz_catalog.mz_clusters
7075            ON mz_catalog.mz_cluster_replicas.cluster_id = mz_catalog.mz_clusters.id
7076        LEFT JOIN
7077            (
7078                SELECT
7079                    replica_id,
7080                    bool_and(hydrated) AS ready
7081                FROM mz_internal.mz_hydration_statuses
7082                WHERE replica_id is not null
7083                GROUP BY replica_id
7084            ) AS statuses
7085            ON mz_catalog.mz_cluster_replicas.id = statuses.replica_id
7086        LEFT JOIN mz_internal.mz_comments comments
7087            ON mz_catalog.mz_cluster_replicas.id = comments.id
7088            AND comments.object_type = 'cluster-replica'
7089ORDER BY 1, 2"#,
7090    access: vec![PUBLIC_SELECT],
7091    ontology: None,
7092});
7093
7094/// Lightweight data product discovery for MCP (Model Context Protocol).
7095///
7096/// Lists materialized views and indexed views that the current user has
7097/// SELECT privileges on. Non-indexed regular views are excluded because
7098/// querying them would trigger a full recompute. Comments are optional
7099/// enrichment.
7100/// Used by the `get_data_products` and `read_data_product` MCP tools.
7101/// Does not include schema details: use `mz_mcp_data_product_details` for that.
7102pub static MZ_MCP_DATA_PRODUCTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7103    name: "mz_mcp_data_products",
7104    schema: MZ_INTERNAL_SCHEMA,
7105    oid: oid::VIEW_MZ_MCP_DATA_PRODUCTS_OID,
7106    desc: RelationDesc::builder()
7107        .with_column("object_name", SqlScalarType::String.nullable(false))
7108        .with_column("cluster", SqlScalarType::String.nullable(true))
7109        .with_column("description", SqlScalarType::String.nullable(true))
7110        .with_key(vec![0, 1, 2])
7111        .finish(),
7112    column_comments: BTreeMap::from_iter([
7113        (
7114            "object_name",
7115            "Fully qualified object name (database.schema.name).",
7116        ),
7117        (
7118            "cluster",
7119            "Cluster hosting the object's index or compute. Reads still work from any cluster you can use, but only reads on this cluster benefit from the index. Shown only when your role has USAGE on it (otherwise null).",
7120        ),
7121        (
7122            "description",
7123            "Index comment if available, otherwise object comment. Used as data product description.",
7124        ),
7125    ]),
7126    // The `cluster` column is null unless the role has USAGE on the object's
7127    // index/compute cluster, so a data product never advertises a cluster the
7128    // role cannot actually run reads on (DEX-66). Materialized views stay
7129    // listed regardless because they serve from persist, so a read on any
7130    // cluster the role can use is safe. Plain indexed views require at least
7131    // one index cluster the role can use: without one, the default fallback
7132    // to the session cluster would recompute the view, which we deliberately
7133    // avoid (same reason non-indexed views are excluded above).
7134    sql: r#"
7135SELECT DISTINCT
7136    '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS object_name,
7137    CASE WHEN cp.name IS NOT NULL THEN COALESCE(c_idx.name, c_obj.name) END AS cluster,
7138    COALESCE(cts_idx.comment, cts_obj.comment) AS description
7139FROM mz_internal.mz_show_my_object_privileges op
7140JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type
7141JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id
7142JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id
7143LEFT JOIN mz_indexes i ON i.on_id = o.id
7144LEFT JOIN mz_clusters c_idx ON c_idx.id = i.cluster_id
7145LEFT JOIN mz_clusters c_obj ON c_obj.id = o.cluster_id
7146LEFT JOIN mz_internal.mz_show_my_cluster_privileges cp
7147    ON cp.name = COALESCE(c_idx.name, c_obj.name) AND cp.privilege_type = 'USAGE'
7148LEFT JOIN mz_internal.mz_comments cts_idx ON cts_idx.id = i.id AND cts_idx.object_type = 'index' AND cts_idx.object_sub_id IS NULL
7149LEFT JOIN mz_internal.mz_comments cts_obj ON cts_obj.id = o.id AND cts_obj.object_type = o.type AND cts_obj.object_sub_id IS NULL
7150WHERE op.privilege_type = 'SELECT'
7151  AND (o.type = 'materialized-view'
7152       OR (o.type = 'view' AND i.id IS NOT NULL AND cp.name IS NOT NULL))
7153  AND s.name NOT IN ('mz_catalog', 'mz_internal', 'pg_catalog', 'information_schema', 'mz_introspection')
7154"#,
7155    access: vec![PUBLIC_SELECT],
7156    ontology: None,
7157});
7158
7159/// Full data product details with JSON Schema for MCP agents.
7160///
7161/// Extends `mz_mcp_data_products` with column types, index keys (when
7162/// available), and column comments, formatted as a JSON Schema object.
7163/// Used by the `get_data_product_details` MCP tool. Lists materialized
7164/// views and indexed views; non-indexed regular views are excluded to
7165/// avoid triggering full recompute on query. Comments are optional
7166/// enrichment.
7167pub static MZ_MCP_DATA_PRODUCT_DETAILS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7168    name: "mz_mcp_data_product_details",
7169    schema: MZ_INTERNAL_SCHEMA,
7170    oid: oid::VIEW_MZ_MCP_DATA_PRODUCT_DETAILS_OID,
7171    // Note: no `.with_key` here. The view's row identity is semantically
7172    // (object_name, cluster, description) — same as the underlying details
7173    // CTE — but the planner can't prove key propagation through the
7174    // `LEFT JOIN ... ON ... IS NOT DISTINCT FROM` to the hydration CTE,
7175    // so declaring it here would diverge from the inferred RelationDesc
7176    // and fail `verify_builtin_descs`.
7177    desc: RelationDesc::builder()
7178        .with_column("object_name", SqlScalarType::String.nullable(false))
7179        .with_column("cluster", SqlScalarType::String.nullable(true))
7180        .with_column("description", SqlScalarType::String.nullable(true))
7181        .with_column("schema", SqlScalarType::Jsonb.nullable(false))
7182        .with_column("hydration", SqlScalarType::Jsonb.nullable(false))
7183        .finish(),
7184    column_comments: BTreeMap::from_iter([
7185        (
7186            "object_name",
7187            "Fully qualified object name (database.schema.name).",
7188        ),
7189        (
7190            "cluster",
7191            "Cluster hosting the object's index or compute. Reads still work from any cluster you can use, but only reads on this cluster benefit from the index. Shown only when your role has USAGE on it (otherwise null).",
7192        ),
7193        (
7194            "description",
7195            "Index comment if available, otherwise object comment. Used as data product description.",
7196        ),
7197        (
7198            "schema",
7199            "JSON Schema describing the object's columns and types.",
7200        ),
7201        (
7202            "hydration",
7203            "Readiness summary as a JSON object with `hydrated` (bool), `replica_count` (int), and `hydrated_replica_count` (int). `hydrated` is true only when the cluster has at least one replica and the dataflow is hydrated on every replica. Reads against a non-hydrated data product block until the dataflow catches up (they never return partial data). Check this before reading: if `hydrated` is false and `replica_count > 0`, wait and retry; if `replica_count` is 0, the cluster has no replicas and that needs operator action, not a retry. A null `cluster` means your role lacks USAGE on that cluster, and only materialized views appear that way, since a view is listed only with an index on a cluster you can use. A read of such a row runs on another cluster and returns the materialized view's stored results, so `hydration` then reports the materialized view's own cluster, the one that keeps those results current.",
7204        ),
7205    ]),
7206    sql: r#"
7207WITH details_raw AS (
7208    SELECT
7209        '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS object_name,
7210        COALESCE(c_idx.name, c_obj.name) AS cluster,
7211        COALESCE(cts_idx.comment, cts_obj.comment) AS description,
7212        COALESCE(jsonb_build_object(
7213        'type', 'object',
7214        'indexedColumns', jsonb_agg(distinct ccol.name) FILTER (WHERE ccol.position = ic.on_position),
7215        'properties', jsonb_strip_nulls(jsonb_object_agg(
7216            ccol.name,
7217            CASE
7218                WHEN ccol.type IN (
7219                    'uint2', 'uint4','uint8', 'int', 'integer', 'smallint',
7220                    'double', 'double precision', 'bigint', 'float',
7221                    'numeric', 'real'
7222                ) THEN jsonb_build_object(
7223                    'type', 'number',
7224                    'description', cts_col.comment
7225                )
7226                WHEN ccol.type = 'boolean' THEN jsonb_build_object(
7227                    'type', 'boolean',
7228                    'description', cts_col.comment
7229                )
7230                WHEN ccol.type = 'bytea' THEN jsonb_build_object(
7231                    'type', 'string',
7232                    'description', cts_col.comment,
7233                    'contentEncoding', 'base64',
7234                    'contentMediaType', 'application/octet-stream'
7235                )
7236                WHEN ccol.type = 'date' THEN jsonb_build_object(
7237                    'type', 'string',
7238                    'format', 'date',
7239                    'description', cts_col.comment
7240                )
7241                WHEN ccol.type = 'time' THEN jsonb_build_object(
7242                    'type', 'string',
7243                    'format', 'time',
7244                    'description', cts_col.comment
7245                )
7246                WHEN ccol.type ilike 'timestamp%%' THEN jsonb_build_object(
7247                    'type', 'string',
7248                    'format', 'date-time',
7249                    'description', cts_col.comment
7250                )
7251                WHEN ccol.type = 'jsonb' THEN jsonb_build_object(
7252                    'type', 'object',
7253                    'description', cts_col.comment
7254                )
7255                WHEN ccol.type = 'uuid' THEN jsonb_build_object(
7256                    'type', 'string',
7257                    'format', 'uuid',
7258                    'description', cts_col.comment
7259                )
7260                ELSE jsonb_build_object(
7261                    'type', 'string',
7262                    'description', cts_col.comment
7263                )
7264            END
7265        ))
7266    ), '{"type": "object", "properties": {}}'::jsonb) AS schema
7267FROM mz_internal.mz_show_my_object_privileges op
7268JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type
7269JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id
7270JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id
7271JOIN mz_columns ccol ON ccol.id = o.id
7272LEFT JOIN mz_indexes i ON i.on_id = o.id
7273LEFT JOIN mz_index_columns ic ON i.id = ic.index_id
7274LEFT JOIN mz_clusters c_idx ON c_idx.id = i.cluster_id
7275LEFT JOIN mz_clusters c_obj ON c_obj.id = o.cluster_id
7276LEFT JOIN mz_internal.mz_show_my_cluster_privileges cp
7277    ON cp.name = COALESCE(c_idx.name, c_obj.name) AND cp.privilege_type = 'USAGE'
7278LEFT JOIN mz_internal.mz_comments cts_idx ON cts_idx.id = i.id AND cts_idx.object_type = 'index' AND cts_idx.object_sub_id IS NULL
7279LEFT JOIN mz_internal.mz_comments cts_obj ON cts_obj.id = o.id AND cts_obj.object_type = o.type AND cts_obj.object_sub_id IS NULL
7280LEFT JOIN mz_internal.mz_comments cts_col ON cts_col.id = o.id AND cts_col.object_type = o.type AND cts_col.object_sub_id = ccol.position
7281WHERE op.privilege_type = 'SELECT'
7282  AND (o.type = 'materialized-view'
7283       OR (o.type = 'view' AND i.id IS NOT NULL AND cp.name IS NOT NULL))
7284  AND s.name NOT IN ('mz_catalog', 'mz_internal', 'pg_catalog', 'information_schema', 'mz_introspection')
7285GROUP BY 1, 2, 3
7286),
7287hydration_candidates AS (
7288    SELECT
7289        '"' || db.name || '"."' || s.name || '"."' || o.name || '"' AS object_name,
7290        COALESCE(c_idx.name, c_obj.name) AS cluster,
7291        o.id AS object_id,
7292        o.cluster_id AS object_cluster_id,
7293        i.id AS index_id,
7294        i.cluster_id AS index_cluster_id
7295    FROM mz_objects o
7296    JOIN mz_schemas s ON s.id = o.schema_id
7297    JOIN mz_databases db ON db.id = s.database_id
7298    LEFT JOIN mz_indexes i ON i.on_id = o.id
7299    LEFT JOIN mz_clusters c_idx ON c_idx.id = i.cluster_id
7300    LEFT JOIN mz_clusters c_obj ON c_obj.id = o.cluster_id
7301    WHERE (o.type = 'materialized-view' OR (o.type = 'view' AND i.id IS NOT NULL))
7302      AND s.name NOT IN ('mz_catalog', 'mz_internal', 'pg_catalog', 'information_schema', 'mz_introspection')
7303),
7304-- Hydration follows the index when the role can use its cluster, otherwise the
7305-- view's own cluster, which keeps the persisted output a fallback read uses
7306-- fresh (DEX-71). Visibility is an EXISTS over the filtered candidates, since a
7307-- LEFT JOIN kept the optimizer from filtering mz_objects before the join.
7308hydration_meta AS (
7309    SELECT DISTINCT
7310        object_name,
7311        cluster,
7312        CASE WHEN visible THEN COALESCE(index_id, object_id) ELSE object_id END
7313            AS hydration_object_id,
7314        CASE WHEN visible THEN COALESCE(index_cluster_id, object_cluster_id) ELSE object_cluster_id END
7315            AS cluster_id
7316    FROM (
7317        SELECT
7318            c.*,
7319            EXISTS (
7320                SELECT 1 FROM mz_internal.mz_show_my_cluster_privileges cp
7321                WHERE cp.name = c.cluster AND cp.privilege_type = 'USAGE'
7322            ) AS visible
7323        FROM hydration_candidates c
7324    )
7325),
7326-- Dedupe by replica before counting: an MV with multiple indexes on the
7327-- same cluster has multiple rows in `hydration_meta`, and joining each
7328-- of them against `mz_cluster_replicas` would otherwise inflate the
7329-- counts by the number of indexes. A replica is "hydrated" only when
7330-- every index dataflow for this data product is hydrated on it.
7331hydration_per_replica AS (
7332    SELECT
7333        m.object_name,
7334        m.cluster,
7335        r.id AS replica_id,
7336        bool_and(COALESCE(h.hydrated, false)) AS replica_hydrated
7337    FROM hydration_meta m
7338    LEFT JOIN mz_catalog.mz_cluster_replicas r ON r.cluster_id = m.cluster_id
7339    LEFT JOIN mz_internal.mz_hydration_statuses h
7340        ON h.replica_id = r.id AND h.object_id = m.hydration_object_id
7341    GROUP BY m.object_name, m.cluster, r.id
7342),
7343hydration AS (
7344    SELECT
7345        object_name,
7346        cluster,
7347        COUNT(replica_id)::int AS replica_count,
7348        COUNT(replica_id) FILTER (WHERE replica_hydrated)::int AS hydrated_replica_count
7349    FROM hydration_per_replica
7350    GROUP BY object_name, cluster
7351)
7352SELECT
7353    d.object_name,
7354    -- Null the advertised cluster unless the role has USAGE on it (DEX-66),
7355    -- matching mz_mcp_data_products.
7356    CASE WHEN EXISTS (
7357        SELECT 1 FROM mz_internal.mz_show_my_cluster_privileges cp
7358        WHERE cp.name = d.cluster AND cp.privilege_type = 'USAGE'
7359    ) THEN d.cluster END AS cluster,
7360    d.description,
7361    d.schema,
7362    jsonb_build_object(
7363        'hydrated',
7364        COALESCE(h.replica_count > 0 AND h.hydrated_replica_count = h.replica_count, false),
7365        'replica_count', COALESCE(h.replica_count, 0),
7366        'hydrated_replica_count', COALESCE(h.hydrated_replica_count, 0)
7367    ) AS hydration
7368FROM details_raw d
7369LEFT JOIN hydration h
7370    ON h.object_name = d.object_name
7371   AND h.cluster IS NOT DISTINCT FROM d.cluster
7372"#,
7373    access: vec![PUBLIC_SELECT],
7374    ontology: None,
7375});
7376
7377pub static MZ_SHOW_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7378    name: "mz_show_role_members",
7379    schema: MZ_INTERNAL_SCHEMA,
7380    oid: oid::VIEW_MZ_SHOW_ROLE_MEMBERS_OID,
7381    desc: RelationDesc::builder()
7382        .with_column("role", SqlScalarType::String.nullable(false))
7383        .with_column("member", SqlScalarType::String.nullable(false))
7384        .with_column("grantor", SqlScalarType::String.nullable(false))
7385        .finish(),
7386    column_comments: BTreeMap::from_iter([
7387        ("role", "The role that `member` is a member of."),
7388        ("member", "The role that is a member of `role`."),
7389        (
7390            "grantor",
7391            "The role that granted membership of `member` to `role`.",
7392        ),
7393    ]),
7394    sql: r#"SELECT
7395    r1.name AS role,
7396    r2.name AS member,
7397    r3.name AS grantor
7398FROM mz_catalog.mz_role_members rm
7399JOIN mz_catalog.mz_roles r1 ON r1.id = rm.role_id
7400JOIN mz_catalog.mz_roles r2 ON r2.id = rm.member
7401JOIN mz_catalog.mz_roles r3 ON r3.id = rm.grantor
7402ORDER BY role"#,
7403    access: vec![PUBLIC_SELECT],
7404    ontology: None,
7405});
7406
7407pub static MZ_SHOW_MY_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7408    name: "mz_show_my_role_members",
7409    schema: MZ_INTERNAL_SCHEMA,
7410    oid: oid::VIEW_MZ_SHOW_MY_ROLE_MEMBERS_OID,
7411    desc: RelationDesc::builder()
7412        .with_column("role", SqlScalarType::String.nullable(false))
7413        .with_column("member", SqlScalarType::String.nullable(false))
7414        .with_column("grantor", SqlScalarType::String.nullable(false))
7415        .finish(),
7416    column_comments: BTreeMap::from_iter([
7417        ("role", "The role that `member` is a member of."),
7418        ("member", "The role that is a member of `role`."),
7419        (
7420            "grantor",
7421            "The role that granted membership of `member` to `role`.",
7422        ),
7423    ]),
7424    sql: r#"SELECT role, member, grantor
7425FROM mz_internal.mz_show_role_members
7426WHERE pg_has_role(member, 'USAGE')"#,
7427    access: vec![PUBLIC_SELECT],
7428    ontology: None,
7429});
7430
7431pub static MZ_SHOW_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7432    name: "mz_show_system_privileges",
7433    schema: MZ_INTERNAL_SCHEMA,
7434    oid: oid::VIEW_MZ_SHOW_SYSTEM_PRIVILEGES_OID,
7435    desc: RelationDesc::builder()
7436        .with_column("grantor", SqlScalarType::String.nullable(true))
7437        .with_column("grantee", SqlScalarType::String.nullable(true))
7438        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7439        .finish(),
7440    column_comments: BTreeMap::from_iter([
7441        ("grantor", "The role that granted the privilege."),
7442        ("grantee", "The role that the privilege was granted to."),
7443        ("privilege_type", "They type of privilege granted."),
7444    ]),
7445    sql: r#"SELECT
7446    grantor.name AS grantor,
7447    CASE privileges.grantee
7448        WHEN 'p' THEN 'PUBLIC'
7449        ELSE grantee.name
7450    END AS grantee,
7451    privileges.privilege_type AS privilege_type
7452FROM
7453    (SELECT mz_internal.mz_aclexplode(ARRAY[privileges]).*
7454    FROM mz_catalog.mz_system_privileges) AS privileges
7455LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
7456LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
7457WHERE privileges.grantee NOT LIKE 's%'"#,
7458    access: vec![PUBLIC_SELECT],
7459    ontology: None,
7460});
7461
7462pub static MZ_SHOW_MY_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7463    name: "mz_show_my_system_privileges",
7464    schema: MZ_INTERNAL_SCHEMA,
7465    oid: oid::VIEW_MZ_SHOW_MY_SYSTEM_PRIVILEGES_OID,
7466    desc: RelationDesc::builder()
7467        .with_column("grantor", SqlScalarType::String.nullable(true))
7468        .with_column("grantee", SqlScalarType::String.nullable(true))
7469        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7470        .finish(),
7471    column_comments: BTreeMap::from_iter([
7472        ("grantor", "The role that granted the privilege."),
7473        ("grantee", "The role that the privilege was granted to."),
7474        ("privilege_type", "They type of privilege granted."),
7475    ]),
7476    sql: r#"SELECT grantor, grantee, privilege_type
7477FROM mz_internal.mz_show_system_privileges
7478WHERE
7479    CASE
7480        WHEN grantee = 'PUBLIC' THEN true
7481        -- Semantically equivalent to pg_has_role(grantee, 'USAGE'), which checks
7482        -- whether the current user holds role `grantee`. For a nonexistent grantee
7483        -- name, both return false. We use mz_session_role_memberships() instead
7484        -- because pg_has_role internally calls mz_role_oid_memberships(), which
7485        -- loads the full system role graph and is blocked in restricted sessions.
7486        ELSE grantee = ANY(mz_catalog.mz_session_role_memberships())
7487    END"#,
7488    access: vec![PUBLIC_SELECT],
7489    ontology: None,
7490});
7491
7492pub static MZ_SHOW_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7493    name: "mz_show_cluster_privileges",
7494    schema: MZ_INTERNAL_SCHEMA,
7495    oid: oid::VIEW_MZ_SHOW_CLUSTER_PRIVILEGES_OID,
7496    desc: RelationDesc::builder()
7497        .with_column("grantor", SqlScalarType::String.nullable(true))
7498        .with_column("grantee", SqlScalarType::String.nullable(true))
7499        .with_column("name", SqlScalarType::String.nullable(false))
7500        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7501        .finish(),
7502    column_comments: BTreeMap::from_iter([
7503        ("grantor", "The role that granted the privilege."),
7504        ("grantee", "The role that the privilege was granted to."),
7505        ("name", "The name of the cluster."),
7506        ("privilege_type", "They type of privilege granted."),
7507    ]),
7508    sql: r#"SELECT
7509    grantor.name AS grantor,
7510    CASE privileges.grantee
7511        WHEN 'p' THEN 'PUBLIC'
7512        ELSE grantee.name
7513    END AS grantee,
7514    privileges.name AS name,
7515    privileges.privilege_type AS privilege_type
7516FROM
7517    (SELECT mz_internal.mz_aclexplode(privileges).*, name
7518    FROM mz_catalog.mz_clusters
7519    WHERE id NOT LIKE 's%') AS privileges
7520LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
7521LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
7522WHERE privileges.grantee NOT LIKE 's%'"#,
7523    access: vec![PUBLIC_SELECT],
7524    ontology: None,
7525});
7526
7527pub static MZ_SHOW_MY_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7528    name: "mz_show_my_cluster_privileges",
7529    schema: MZ_INTERNAL_SCHEMA,
7530    oid: oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
7531    desc: RelationDesc::builder()
7532        .with_column("grantor", SqlScalarType::String.nullable(true))
7533        .with_column("grantee", SqlScalarType::String.nullable(true))
7534        .with_column("name", SqlScalarType::String.nullable(false))
7535        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7536        .finish(),
7537    column_comments: BTreeMap::from_iter([
7538        ("grantor", "The role that granted the privilege."),
7539        ("grantee", "The role that the privilege was granted to."),
7540        ("name", "The name of the cluster."),
7541        ("privilege_type", "They type of privilege granted."),
7542    ]),
7543    sql: r#"SELECT grantor, grantee, name, privilege_type
7544FROM mz_internal.mz_show_cluster_privileges
7545WHERE
7546    CASE
7547        WHEN grantee = 'PUBLIC' THEN true
7548        -- Semantically equivalent to pg_has_role(grantee, 'USAGE'), which checks
7549        -- whether the current user holds role `grantee`. For a nonexistent grantee
7550        -- name, both return false. We use mz_session_role_memberships() instead
7551        -- because pg_has_role internally calls mz_role_oid_memberships(), which
7552        -- loads the full system role graph and is blocked in restricted sessions.
7553        ELSE grantee = ANY(mz_catalog.mz_session_role_memberships())
7554    END"#,
7555    access: vec![PUBLIC_SELECT],
7556    ontology: None,
7557});
7558
7559pub static MZ_SHOW_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7560    name: "mz_show_database_privileges",
7561    schema: MZ_INTERNAL_SCHEMA,
7562    oid: oid::VIEW_MZ_SHOW_DATABASE_PRIVILEGES_OID,
7563    desc: RelationDesc::builder()
7564        .with_column("grantor", SqlScalarType::String.nullable(true))
7565        .with_column("grantee", SqlScalarType::String.nullable(true))
7566        .with_column("name", SqlScalarType::String.nullable(false))
7567        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7568        .finish(),
7569    column_comments: BTreeMap::from_iter([
7570        ("grantor", "The role that granted the privilege."),
7571        ("grantee", "The role that the privilege was granted to."),
7572        ("name", "The name of the database."),
7573        ("privilege_type", "They type of privilege granted."),
7574    ]),
7575    sql: r#"SELECT
7576    grantor.name AS grantor,
7577    CASE privileges.grantee
7578        WHEN 'p' THEN 'PUBLIC'
7579        ELSE grantee.name
7580    END AS grantee,
7581    privileges.name AS name,
7582    privileges.privilege_type AS privilege_type
7583FROM
7584    (SELECT mz_internal.mz_aclexplode(privileges).*, name
7585    FROM mz_catalog.mz_databases
7586    WHERE id NOT LIKE 's%') AS privileges
7587LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
7588LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
7589WHERE privileges.grantee NOT LIKE 's%'"#,
7590    access: vec![PUBLIC_SELECT],
7591    ontology: None,
7592});
7593
7594pub static MZ_SHOW_MY_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7595    name: "mz_show_my_database_privileges",
7596    schema: MZ_INTERNAL_SCHEMA,
7597    oid: oid::VIEW_MZ_SHOW_MY_DATABASE_PRIVILEGES_OID,
7598    desc: RelationDesc::builder()
7599        .with_column("grantor", SqlScalarType::String.nullable(true))
7600        .with_column("grantee", SqlScalarType::String.nullable(true))
7601        .with_column("name", SqlScalarType::String.nullable(false))
7602        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7603        .finish(),
7604    column_comments: BTreeMap::from_iter([
7605        ("grantor", "The role that granted the privilege."),
7606        ("grantee", "The role that the privilege was granted to."),
7607        ("name", "The name of the cluster."),
7608        ("privilege_type", "They type of privilege granted."),
7609    ]),
7610    sql: r#"SELECT grantor, grantee, name, privilege_type
7611FROM mz_internal.mz_show_database_privileges
7612WHERE
7613    CASE
7614        WHEN grantee = 'PUBLIC' THEN true
7615        -- Semantically equivalent to pg_has_role(grantee, 'USAGE'), which checks
7616        -- whether the current user holds role `grantee`. For a nonexistent grantee
7617        -- name, both return false. We use mz_session_role_memberships() instead
7618        -- because pg_has_role internally calls mz_role_oid_memberships(), which
7619        -- loads the full system role graph and is blocked in restricted sessions.
7620        ELSE grantee = ANY(mz_catalog.mz_session_role_memberships())
7621    END"#,
7622    access: vec![PUBLIC_SELECT],
7623    ontology: None,
7624});
7625
7626pub static MZ_SHOW_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7627    name: "mz_show_schema_privileges",
7628    schema: MZ_INTERNAL_SCHEMA,
7629    oid: oid::VIEW_MZ_SHOW_SCHEMA_PRIVILEGES_OID,
7630    desc: RelationDesc::builder()
7631        .with_column("grantor", SqlScalarType::String.nullable(true))
7632        .with_column("grantee", SqlScalarType::String.nullable(true))
7633        .with_column("database", SqlScalarType::String.nullable(true))
7634        .with_column("name", SqlScalarType::String.nullable(false))
7635        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7636        .finish(),
7637    column_comments: BTreeMap::from_iter([
7638        ("grantor", "The role that granted the privilege."),
7639        ("grantee", "The role that the privilege was granted to."),
7640        (
7641            "database",
7642            "The name of the database containing the schema.",
7643        ),
7644        ("name", "The name of the schema."),
7645        ("privilege_type", "They type of privilege granted."),
7646    ]),
7647    sql: r#"SELECT
7648    grantor.name AS grantor,
7649    CASE privileges.grantee
7650        WHEN 'p' THEN 'PUBLIC'
7651        ELSE grantee.name
7652    END AS grantee,
7653    databases.name AS database,
7654    privileges.name AS name,
7655    privileges.privilege_type AS privilege_type
7656FROM
7657    (SELECT mz_internal.mz_aclexplode(privileges).*, database_id, name
7658    FROM mz_catalog.mz_schemas
7659    WHERE id NOT LIKE 's%') AS privileges
7660LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
7661LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
7662LEFT JOIN mz_catalog.mz_databases databases ON privileges.database_id = databases.id
7663WHERE privileges.grantee NOT LIKE 's%'"#,
7664    access: vec![PUBLIC_SELECT],
7665    ontology: None,
7666});
7667
7668pub static MZ_SHOW_MY_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7669    name: "mz_show_my_schema_privileges",
7670    schema: MZ_INTERNAL_SCHEMA,
7671    oid: oid::VIEW_MZ_SHOW_MY_SCHEMA_PRIVILEGES_OID,
7672    desc: RelationDesc::builder()
7673        .with_column("grantor", SqlScalarType::String.nullable(true))
7674        .with_column("grantee", SqlScalarType::String.nullable(true))
7675        .with_column("database", SqlScalarType::String.nullable(true))
7676        .with_column("name", SqlScalarType::String.nullable(false))
7677        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7678        .finish(),
7679    column_comments: BTreeMap::from_iter([
7680        ("grantor", "The role that granted the privilege."),
7681        ("grantee", "The role that the privilege was granted to."),
7682        (
7683            "database",
7684            "The name of the database containing the schema.",
7685        ),
7686        ("name", "The name of the schema."),
7687        ("privilege_type", "They type of privilege granted."),
7688    ]),
7689    sql: r#"SELECT grantor, grantee, database, name, privilege_type
7690FROM mz_internal.mz_show_schema_privileges
7691WHERE
7692    CASE
7693        WHEN grantee = 'PUBLIC' THEN true
7694        -- Semantically equivalent to pg_has_role(grantee, 'USAGE'), which checks
7695        -- whether the current user holds role `grantee`. For a nonexistent grantee
7696        -- name, both return false. We use mz_session_role_memberships() instead
7697        -- because pg_has_role internally calls mz_role_oid_memberships(), which
7698        -- loads the full system role graph and is blocked in restricted sessions.
7699        ELSE grantee = ANY(mz_catalog.mz_session_role_memberships())
7700    END"#,
7701    access: vec![PUBLIC_SELECT],
7702    ontology: None,
7703});
7704
7705pub static MZ_SHOW_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7706    name: "mz_show_object_privileges",
7707    schema: MZ_INTERNAL_SCHEMA,
7708    oid: oid::VIEW_MZ_SHOW_OBJECT_PRIVILEGES_OID,
7709    desc: RelationDesc::builder()
7710        .with_column("grantor", SqlScalarType::String.nullable(true))
7711        .with_column("grantee", SqlScalarType::String.nullable(true))
7712        .with_column("database", SqlScalarType::String.nullable(true))
7713        .with_column("schema", SqlScalarType::String.nullable(true))
7714        .with_column("name", SqlScalarType::String.nullable(false))
7715        .with_column("object_type", SqlScalarType::String.nullable(false))
7716        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7717        .finish(),
7718    column_comments: BTreeMap::from_iter([
7719        ("grantor", "The role that granted the privilege."),
7720        ("grantee", "The role that the privilege was granted to."),
7721        (
7722            "database",
7723            "The name of the database containing the object.",
7724        ),
7725        ("schema", "The name of the schema containing the object."),
7726        ("name", "The name of the object."),
7727        (
7728            "object_type",
7729            "The type of object the privilege is granted on.",
7730        ),
7731        ("privilege_type", "They type of privilege granted."),
7732    ]),
7733    sql: r#"SELECT
7734    grantor.name AS grantor,
7735    CASE privileges.grantee
7736            WHEN 'p' THEN 'PUBLIC'
7737            ELSE grantee.name
7738        END AS grantee,
7739    databases.name AS database,
7740    schemas.name AS schema,
7741    privileges.name AS name,
7742    privileges.type AS object_type,
7743    privileges.privilege_type AS privilege_type
7744FROM
7745    (SELECT mz_internal.mz_aclexplode(privileges).*, schema_id, name, type
7746    FROM mz_catalog.mz_objects
7747    WHERE id NOT LIKE 's%') AS privileges
7748LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
7749LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
7750LEFT JOIN mz_catalog.mz_schemas schemas ON privileges.schema_id = schemas.id
7751LEFT JOIN mz_catalog.mz_databases databases ON schemas.database_id = databases.id
7752WHERE privileges.grantee NOT LIKE 's%'"#,
7753    access: vec![PUBLIC_SELECT],
7754    ontology: None,
7755});
7756
7757pub static MZ_SHOW_MY_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7758    name: "mz_show_my_object_privileges",
7759    schema: MZ_INTERNAL_SCHEMA,
7760    oid: oid::VIEW_MZ_SHOW_MY_OBJECT_PRIVILEGES_OID,
7761    desc: RelationDesc::builder()
7762        .with_column("grantor", SqlScalarType::String.nullable(true))
7763        .with_column("grantee", SqlScalarType::String.nullable(true))
7764        .with_column("database", SqlScalarType::String.nullable(true))
7765        .with_column("schema", SqlScalarType::String.nullable(true))
7766        .with_column("name", SqlScalarType::String.nullable(false))
7767        .with_column("object_type", SqlScalarType::String.nullable(false))
7768        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7769        .finish(),
7770    column_comments: BTreeMap::from_iter([
7771        ("grantor", "The role that granted the privilege."),
7772        ("grantee", "The role that the privilege was granted to."),
7773        (
7774            "database",
7775            "The name of the database containing the object.",
7776        ),
7777        ("schema", "The name of the schema containing the object."),
7778        ("name", "The name of the object."),
7779        (
7780            "object_type",
7781            "The type of object the privilege is granted on.",
7782        ),
7783        ("privilege_type", "They type of privilege granted."),
7784    ]),
7785    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
7786FROM mz_internal.mz_show_object_privileges
7787WHERE
7788    CASE
7789        WHEN grantee = 'PUBLIC' THEN true
7790        -- Semantically equivalent to pg_has_role(grantee, 'USAGE'), which checks
7791        -- whether the current user holds role `grantee`. For a nonexistent grantee
7792        -- name, both return false. We use mz_session_role_memberships() instead
7793        -- because pg_has_role internally calls mz_role_oid_memberships(), which
7794        -- loads the full system role graph and is blocked in restricted sessions.
7795        ELSE grantee = ANY(mz_catalog.mz_session_role_memberships())
7796    END"#,
7797    access: vec![PUBLIC_SELECT],
7798    ontology: None,
7799});
7800
7801pub static MZ_SHOW_ALL_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7802    name: "mz_show_all_privileges",
7803    schema: MZ_INTERNAL_SCHEMA,
7804    oid: oid::VIEW_MZ_SHOW_ALL_PRIVILEGES_OID,
7805    desc: RelationDesc::builder()
7806        .with_column("grantor", SqlScalarType::String.nullable(true))
7807        .with_column("grantee", SqlScalarType::String.nullable(true))
7808        .with_column("database", SqlScalarType::String.nullable(true))
7809        .with_column("schema", SqlScalarType::String.nullable(true))
7810        .with_column("name", SqlScalarType::String.nullable(true))
7811        .with_column("object_type", SqlScalarType::String.nullable(false))
7812        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7813        .finish(),
7814    column_comments: BTreeMap::from_iter([
7815        ("grantor", "The role that granted the privilege."),
7816        ("grantee", "The role that the privilege was granted to."),
7817        (
7818            "database",
7819            "The name of the database containing the object.",
7820        ),
7821        ("schema", "The name of the schema containing the object."),
7822        ("name", "The name of the privilege target."),
7823        (
7824            "object_type",
7825            "The type of object the privilege is granted on.",
7826        ),
7827        ("privilege_type", "They type of privilege granted."),
7828    ]),
7829    sql: r#"SELECT grantor, grantee, NULL AS database, NULL AS schema, NULL AS name, 'system' AS object_type, privilege_type
7830FROM mz_internal.mz_show_system_privileges
7831UNION ALL
7832SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'cluster' AS object_type, privilege_type
7833FROM mz_internal.mz_show_cluster_privileges
7834UNION ALL
7835SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'database' AS object_type, privilege_type
7836FROM mz_internal.mz_show_database_privileges
7837UNION ALL
7838SELECT grantor, grantee, database, NULL AS schema, name, 'schema' AS object_type, privilege_type
7839FROM mz_internal.mz_show_schema_privileges
7840UNION ALL
7841SELECT grantor, grantee, database, schema, name, object_type, privilege_type
7842FROM mz_internal.mz_show_object_privileges
7843UNION ALL
7844SELECT
7845    grantor.name,
7846    CASE privileges.grantee WHEN 'p' THEN 'PUBLIC' ELSE grantee.name END,
7847    NULL AS database,
7848    NULL AS schema,
7849    privileges.name,
7850    'query policy' AS object_type,
7851    privileges.privilege_type
7852FROM
7853    (SELECT mz_internal.mz_aclexplode(privileges).*, name
7854    FROM mz_internal.mz_query_policies
7855    WHERE id NOT LIKE 's%') AS privileges
7856LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
7857LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
7858WHERE privileges.grantee NOT LIKE 's%'"#,
7859    access: vec![PUBLIC_SELECT],
7860    ontology: None,
7861});
7862
7863pub static MZ_SHOW_ALL_MY_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7864    name: "mz_show_all_my_privileges",
7865    schema: MZ_INTERNAL_SCHEMA,
7866    oid: oid::VIEW_MZ_SHOW_ALL_MY_PRIVILEGES_OID,
7867    desc: RelationDesc::builder()
7868        .with_column("grantor", SqlScalarType::String.nullable(true))
7869        .with_column("grantee", SqlScalarType::String.nullable(true))
7870        .with_column("database", SqlScalarType::String.nullable(true))
7871        .with_column("schema", SqlScalarType::String.nullable(true))
7872        .with_column("name", SqlScalarType::String.nullable(true))
7873        .with_column("object_type", SqlScalarType::String.nullable(false))
7874        .with_column("privilege_type", SqlScalarType::String.nullable(false))
7875        .finish(),
7876    column_comments: BTreeMap::from_iter([
7877        ("grantor", "The role that granted the privilege."),
7878        ("grantee", "The role that the privilege was granted to."),
7879        (
7880            "database",
7881            "The name of the database containing the object.",
7882        ),
7883        ("schema", "The name of the schema containing the object."),
7884        ("name", "The name of the privilege target."),
7885        (
7886            "object_type",
7887            "The type of object the privilege is granted on.",
7888        ),
7889        ("privilege_type", "They type of privilege granted."),
7890    ]),
7891    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
7892FROM mz_internal.mz_show_all_privileges
7893WHERE
7894    CASE
7895        WHEN grantee = 'PUBLIC' THEN true
7896        -- Semantically equivalent to pg_has_role(grantee, 'USAGE'), which checks
7897        -- whether the current user holds role `grantee`. For a nonexistent grantee
7898        -- name, both return false. We use mz_session_role_memberships() instead
7899        -- because pg_has_role internally calls mz_role_oid_memberships(), which
7900        -- loads the full system role graph and is blocked in restricted sessions.
7901        ELSE grantee = ANY(mz_catalog.mz_session_role_memberships())
7902    END"#,
7903    access: vec![PUBLIC_SELECT],
7904    ontology: None,
7905});
7906
7907pub static MZ_SHOW_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7908    name: "mz_show_default_privileges",
7909    schema: MZ_INTERNAL_SCHEMA,
7910    oid: oid::VIEW_MZ_SHOW_DEFAULT_PRIVILEGES_OID,
7911    desc: RelationDesc::builder()
7912        .with_column("object_owner", SqlScalarType::String.nullable(true))
7913        .with_column("database", SqlScalarType::String.nullable(true))
7914        .with_column("schema", SqlScalarType::String.nullable(true))
7915        .with_column("object_type", SqlScalarType::String.nullable(false))
7916        .with_column("grantee", SqlScalarType::String.nullable(true))
7917        .with_column("privilege_type", SqlScalarType::String.nullable(true))
7918        .finish(),
7919    column_comments: BTreeMap::from_iter([
7920        (
7921            "object_owner",
7922            "Privileges described in this row will be granted on objects created by `object_owner`.",
7923        ),
7924        (
7925            "database",
7926            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
7927        ),
7928        (
7929            "schema",
7930            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
7931        ),
7932        (
7933            "object_type",
7934            "Privileges described in this row will be granted only on objects of type `object_type`.",
7935        ),
7936        (
7937            "grantee",
7938            "Privileges described in this row will be granted to `grantee`.",
7939        ),
7940        ("privilege_type", "They type of privilege to be granted."),
7941    ]),
7942    sql: r#"SELECT
7943    CASE defaults.role_id
7944        WHEN 'p' THEN 'PUBLIC'
7945        ELSE object_owner.name
7946    END AS object_owner,
7947    databases.name AS database,
7948    schemas.name AS schema,
7949    object_type,
7950    CASE defaults.grantee
7951        WHEN 'p' THEN 'PUBLIC'
7952        ELSE grantee.name
7953    END AS grantee,
7954    unnest(mz_internal.mz_format_privileges(defaults.privileges)) AS privilege_type
7955FROM mz_catalog.mz_default_privileges defaults
7956LEFT JOIN mz_catalog.mz_roles AS object_owner ON defaults.role_id = object_owner.id
7957LEFT JOIN mz_catalog.mz_roles AS grantee ON defaults.grantee = grantee.id
7958LEFT JOIN mz_catalog.mz_databases AS databases ON defaults.database_id = databases.id
7959LEFT JOIN mz_catalog.mz_schemas AS schemas ON defaults.schema_id = schemas.id
7960WHERE defaults.grantee NOT LIKE 's%'
7961    AND defaults.database_id IS NULL OR defaults.database_id NOT LIKE 's%'
7962    AND defaults.schema_id IS NULL OR defaults.schema_id NOT LIKE 's%'"#,
7963    access: vec![PUBLIC_SELECT],
7964    ontology: None,
7965});
7966
7967pub static MZ_SHOW_MY_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7968    name: "mz_show_my_default_privileges",
7969    schema: MZ_INTERNAL_SCHEMA,
7970    oid: oid::VIEW_MZ_SHOW_MY_DEFAULT_PRIVILEGES_OID,
7971    desc: RelationDesc::builder()
7972        .with_column("object_owner", SqlScalarType::String.nullable(true))
7973        .with_column("database", SqlScalarType::String.nullable(true))
7974        .with_column("schema", SqlScalarType::String.nullable(true))
7975        .with_column("object_type", SqlScalarType::String.nullable(false))
7976        .with_column("grantee", SqlScalarType::String.nullable(true))
7977        .with_column("privilege_type", SqlScalarType::String.nullable(true))
7978        .finish(),
7979    column_comments: BTreeMap::from_iter([
7980        (
7981            "object_owner",
7982            "Privileges described in this row will be granted on objects created by `object_owner`.",
7983        ),
7984        (
7985            "database",
7986            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
7987        ),
7988        (
7989            "schema",
7990            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
7991        ),
7992        (
7993            "object_type",
7994            "Privileges described in this row will be granted only on objects of type `object_type`.",
7995        ),
7996        (
7997            "grantee",
7998            "Privileges described in this row will be granted to `grantee`.",
7999        ),
8000        ("privilege_type", "They type of privilege to be granted."),
8001    ]),
8002    sql: r#"SELECT object_owner, database, schema, object_type, grantee, privilege_type
8003FROM mz_internal.mz_show_default_privileges
8004WHERE
8005    CASE
8006        WHEN grantee = 'PUBLIC' THEN true
8007        -- Semantically equivalent to pg_has_role(grantee, 'USAGE'), which checks
8008        -- whether the current user holds role `grantee`. For a nonexistent grantee
8009        -- name, both return false. We use mz_session_role_memberships() instead
8010        -- because pg_has_role internally calls mz_role_oid_memberships(), which
8011        -- loads the full system role graph and is blocked in restricted sessions.
8012        ELSE grantee = ANY(mz_catalog.mz_session_role_memberships())
8013    END"#,
8014    access: vec![PUBLIC_SELECT],
8015    ontology: None,
8016});
8017
8018pub static MZ_SHOW_NETWORK_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8019    name: "mz_show_network_policies",
8020    schema: MZ_INTERNAL_SCHEMA,
8021    oid: oid::VIEW_MZ_SHOW_NETWORK_POLICIES_OID,
8022    desc: RelationDesc::builder()
8023        .with_column("name", SqlScalarType::String.nullable(false))
8024        .with_column("rules", SqlScalarType::String.nullable(true))
8025        .with_column("comment", SqlScalarType::String.nullable(false))
8026        .finish(),
8027    column_comments: BTreeMap::new(),
8028    sql: "
8029WITH comments AS (
8030    SELECT id, comment
8031    FROM mz_internal.mz_comments
8032    WHERE object_type = 'network-policy' AND object_sub_id IS NULL
8033)
8034SELECT
8035    policy.name,
8036    pg_catalog.string_agg(rule.name,',' ORDER BY rule.name) as rules,
8037    COALESCE(comment, '') as comment
8038FROM
8039    mz_internal.mz_network_policies as policy
8040LEFT JOIN
8041    mz_internal.mz_network_policy_rules as rule ON policy.id = rule.policy_id
8042LEFT JOIN
8043    comments ON policy.id = comments.id
8044WHERE
8045    policy.id NOT LIKE 's%'
8046AND
8047    policy.id NOT LIKE 'g%'
8048GROUP BY policy.name, comments.comment;",
8049    access: vec![PUBLIC_SELECT],
8050    ontology: None,
8051});
8052
8053pub static MZ_SHOW_QUERY_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8054    name: "mz_show_query_policies",
8055    schema: MZ_INTERNAL_SCHEMA,
8056    oid: oid::VIEW_MZ_SHOW_QUERY_POLICIES_OID,
8057    desc: RelationDesc::builder()
8058        .with_column("name", SqlScalarType::String.nullable(false))
8059        .with_column("mode", SqlScalarType::String.nullable(false))
8060        .with_column("rules", SqlScalarType::String.nullable(true))
8061        .with_column("comment", SqlScalarType::String.nullable(false))
8062        .finish(),
8063    column_comments: BTreeMap::new(),
8064    sql: "
8065SELECT policy.name, policy.mode,
8066    pg_catalog.string_agg(rule.name, ',' ORDER BY rule.name) AS rules,
8067    COALESCE(comments.comment, '') AS comment
8068FROM mz_internal.mz_query_policies AS policy
8069LEFT JOIN mz_internal.mz_query_policy_rules AS rule ON policy.id = rule.policy_id
8070LEFT JOIN mz_internal.mz_comments AS comments
8071    ON policy.id = comments.id
8072    AND comments.object_type = 'query-policy'
8073    AND comments.object_sub_id IS NULL
8074WHERE policy.id NOT LIKE 's%'
8075GROUP BY policy.name, policy.mode, comments.comment",
8076    access: vec![PUBLIC_SELECT],
8077    ontology: None,
8078});
8079
8080pub static MZ_CLUSTER_REPLICA_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8081    name: "mz_cluster_replica_history",
8082    schema: MZ_INTERNAL_SCHEMA,
8083    oid: oid::VIEW_MZ_CLUSTER_REPLICA_HISTORY_OID,
8084    desc: RelationDesc::builder()
8085        .with_column("replica_id", SqlScalarType::String.nullable(true))
8086        .with_column("size", SqlScalarType::String.nullable(true))
8087        .with_column("cluster_id", SqlScalarType::String.nullable(true))
8088        .with_column("cluster_name", SqlScalarType::String.nullable(true))
8089        .with_column("replica_name", SqlScalarType::String.nullable(true))
8090        .with_column(
8091            "created_at",
8092            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8093        )
8094        .with_column(
8095            "dropped_at",
8096            SqlScalarType::TimestampTz { precision: None }.nullable(true),
8097        )
8098        .with_column(
8099            "credits_per_hour",
8100            SqlScalarType::Numeric { max_scale: None }.nullable(true),
8101        )
8102        .finish(),
8103    column_comments: BTreeMap::from_iter([
8104        ("replica_id", "The ID of a cluster replica."),
8105        (
8106            "size",
8107            "The size of the cluster replica. Corresponds to `mz_cluster_replica_sizes.size`.",
8108        ),
8109        (
8110            "cluster_id",
8111            "The ID of the cluster associated with the replica.",
8112        ),
8113        (
8114            "cluster_name",
8115            "The name of the cluster associated with the replica.",
8116        ),
8117        ("replica_name", "The name of the replica."),
8118        ("created_at", "The time at which the replica was created."),
8119        (
8120            "dropped_at",
8121            "The time at which the replica was dropped, or `NULL` if it still exists.",
8122        ),
8123        (
8124            "credits_per_hour",
8125            "The number of compute credits consumed per hour. Corresponds to `mz_cluster_replica_sizes.credits_per_hour`.",
8126        ),
8127    ]),
8128    sql: r#"
8129        WITH
8130            creates AS
8131            (
8132                SELECT
8133                    details ->> 'logical_size' AS size,
8134                    details ->> 'replica_id' AS replica_id,
8135                    details ->> 'replica_name' AS replica_name,
8136                    details ->> 'cluster_name' AS cluster_name,
8137                    details ->> 'cluster_id' AS cluster_id,
8138                    occurred_at
8139                FROM mz_catalog.mz_audit_events
8140                WHERE
8141                    object_type = 'cluster-replica' AND event_type = 'create'
8142                        AND
8143                    details ->> 'replica_id' IS NOT NULL
8144                        AND
8145                    details ->> 'cluster_id' !~~ 's%'
8146            ),
8147            drops AS
8148            (
8149                SELECT details ->> 'replica_id' AS replica_id, occurred_at
8150                FROM mz_catalog.mz_audit_events
8151                WHERE object_type = 'cluster-replica' AND event_type = 'drop'
8152            )
8153        SELECT
8154            creates.replica_id,
8155            creates.size,
8156            creates.cluster_id,
8157            creates.cluster_name,
8158            creates.replica_name,
8159            creates.occurred_at AS created_at,
8160            drops.occurred_at AS dropped_at,
8161            mz_cluster_replica_sizes.credits_per_hour as credits_per_hour
8162        FROM
8163            creates
8164                LEFT JOIN drops ON creates.replica_id = drops.replica_id
8165                LEFT JOIN
8166                    mz_catalog.mz_cluster_replica_sizes
8167                    ON mz_cluster_replica_sizes.size = creates.size"#,
8168    access: vec![PUBLIC_SELECT],
8169    ontology: Some(Ontology {
8170        entity_name: "replica_history",
8171        description: "Historical record of replica creation/drops",
8172        links: &const { [] },
8173        column_semantic_types: &[],
8174    }),
8175});
8176
8177pub static MZ_CLUSTER_REPLICA_NAME_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8178    name: "mz_cluster_replica_name_history",
8179    schema: MZ_INTERNAL_SCHEMA,
8180    oid: oid::VIEW_MZ_CLUSTER_REPLICA_NAME_HISTORY_OID,
8181    desc: RelationDesc::builder()
8182        .with_column(
8183            "occurred_at",
8184            SqlScalarType::TimestampTz { precision: None }.nullable(true),
8185        )
8186        .with_column("id", SqlScalarType::String.nullable(true))
8187        .with_column("previous_name", SqlScalarType::String.nullable(true))
8188        .with_column("new_name", SqlScalarType::String.nullable(true))
8189        .finish(),
8190    column_comments: BTreeMap::from_iter([
8191        (
8192            "occurred_at",
8193            "The time at which the cluster replica was created or renamed. `NULL` if it's a built in system cluster replica.",
8194        ),
8195        ("id", "The ID of the cluster replica."),
8196        (
8197            "previous_name",
8198            "The previous name of the cluster replica. `NULL` if there was no previous name.",
8199        ),
8200        ("new_name", "The new name of the cluster replica."),
8201    ]),
8202    sql: r#"WITH user_replica_alter_history AS (
8203  SELECT occurred_at,
8204    audit_events.details->>'replica_id' AS id,
8205    audit_events.details->>'old_name' AS previous_name,
8206    audit_events.details->>'new_name' AS new_name
8207  FROM mz_catalog.mz_audit_events AS audit_events
8208  WHERE object_type = 'cluster-replica'
8209    AND audit_events.event_type = 'alter'
8210    AND audit_events.details->>'replica_id' like 'u%'
8211),
8212user_replica_create_history AS (
8213  SELECT occurred_at,
8214    audit_events.details->>'replica_id' AS id,
8215    NULL AS previous_name,
8216    audit_events.details->>'replica_name' AS new_name
8217  FROM mz_catalog.mz_audit_events AS audit_events
8218  WHERE object_type = 'cluster-replica'
8219    AND audit_events.event_type = 'create'
8220    AND audit_events.details->>'replica_id' like 'u%'
8221),
8222-- Because built in system cluster replicas don't have audit events, we need to manually add them
8223system_replicas AS (
8224  -- We assume that the system cluster replicas were created at the beginning of time
8225  SELECT NULL::timestamptz AS occurred_at,
8226    id,
8227    NULL AS previous_name,
8228    name AS new_name
8229  FROM mz_catalog.mz_cluster_replicas
8230  WHERE id LIKE 's%'
8231)
8232SELECT *
8233FROM user_replica_alter_history
8234UNION ALL
8235SELECT *
8236FROM user_replica_create_history
8237UNION ALL
8238SELECT *
8239FROM system_replicas"#,
8240    access: vec![PUBLIC_SELECT],
8241    ontology: Some(Ontology {
8242        entity_name: "replica_name_history",
8243        description: "Historical replica names",
8244        links: &const { [] },
8245        column_semantic_types: &[("id", SemanticType::CatalogItemId)],
8246    }),
8247});
8248
8249pub static MZ_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8250    name: "mz_hydration_statuses",
8251    schema: MZ_INTERNAL_SCHEMA,
8252    oid: oid::VIEW_MZ_HYDRATION_STATUSES_OID,
8253    desc: RelationDesc::builder()
8254        .with_column("object_id", SqlScalarType::String.nullable(false))
8255        .with_column("replica_id", SqlScalarType::String.nullable(true))
8256        .with_column("hydrated", SqlScalarType::Bool.nullable(true))
8257        .finish(),
8258    column_comments: BTreeMap::from_iter([
8259        (
8260            "object_id",
8261            "The ID of a dataflow-powered object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, `mz_internal.mz_subscriptions`, `mz_catalog.mz_sources.id`, or `mz_catalog.mz_sinks.id`.",
8262        ),
8263        ("replica_id", "The ID of a cluster replica."),
8264        ("hydrated", "Whether the object is hydrated on the replica."),
8265    ]),
8266    sql: r#"WITH
8267-- Joining against the linearizable catalog tables ensures that this view
8268-- always contains the set of installed objects, even when it depends
8269-- on introspection relations that may received delayed updates.
8270--
8271-- Note that this view only includes objects that are maintained by dataflows.
8272-- In particular, some source types (webhook, introspection, ...) are not and
8273-- are therefore omitted.
8274indexes AS (
8275    SELECT
8276        i.id AS object_id,
8277        h.replica_id,
8278        COALESCE(h.hydrated, false) AS hydrated
8279    FROM mz_catalog.mz_indexes i
8280    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
8281        ON (h.object_id = i.id)
8282),
8283materialized_views AS (
8284    SELECT
8285        i.id AS object_id,
8286        h.replica_id,
8287        COALESCE(h.hydrated, false) AS hydrated
8288    FROM mz_catalog.mz_materialized_views i
8289    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
8290        ON (h.object_id = i.id)
8291),
8292-- Hydration is a dataflow concept and not all sources are maintained by
8293-- dataflows, so we need to find the ones that are. Generally, sources that
8294-- have a cluster ID are maintained by a dataflow running on that cluster.
8295-- Webhook sources are an exception to this rule.
8296sources_with_clusters AS (
8297    SELECT id, cluster_id
8298    FROM mz_catalog.mz_sources
8299    WHERE cluster_id IS NOT NULL AND type != 'webhook'
8300),
8301sources AS (
8302    SELECT
8303        s.id AS object_id,
8304        ss.replica_id AS replica_id,
8305        ss.rehydration_latency IS NOT NULL AS hydrated
8306    FROM sources_with_clusters s
8307    LEFT JOIN mz_internal.mz_source_statistics ss USING (id)
8308),
8309-- We don't yet report sink hydration status (database-issues#8331), so we do a best effort attempt here and
8310-- define a sink as hydrated when it's both "running" and has a frontier greater than the minimum.
8311-- There is likely still a possibility of FPs.
8312sinks AS (
8313    SELECT
8314        s.id AS object_id,
8315        r.id AS replica_id,
8316        ss.status = 'running' AND COALESCE(f.write_frontier, 0) > 0 AS hydrated
8317    FROM mz_catalog.mz_sinks s
8318    LEFT JOIN mz_internal.mz_sink_statuses ss USING (id)
8319    JOIN mz_catalog.mz_cluster_replicas r
8320        ON (r.cluster_id = s.cluster_id)
8321    LEFT JOIN mz_catalog.mz_cluster_replica_frontiers f
8322        ON (f.object_id = s.id AND f.replica_id = r.id)
8323)
8324SELECT * FROM indexes
8325UNION ALL
8326SELECT * FROM materialized_views
8327UNION ALL
8328SELECT * FROM sources
8329UNION ALL
8330SELECT * FROM sinks"#,
8331    access: vec![PUBLIC_SELECT],
8332    ontology: Some(Ontology {
8333        entity_name: "hydration_status",
8334        description: "Overall hydration status per object",
8335        links: &const {
8336            [
8337                OntologyLink {
8338                    name: "hydration_of",
8339                    target: "object",
8340                    properties: LinkProperties::fk_typed(
8341                        "object_id",
8342                        "id",
8343                        Cardinality::OneToOne,
8344                        mz_repr::SemanticType::CatalogItemId,
8345                    ),
8346                },
8347                OntologyLink {
8348                    name: "hydration_on_replica",
8349                    target: "replica",
8350                    properties: LinkProperties::fk("replica_id", "id", Cardinality::ManyToOne),
8351                },
8352            ]
8353        },
8354        column_semantic_types: &const {
8355            [
8356                ("object_id", SemanticType::CatalogItemId),
8357                ("replica_id", SemanticType::ReplicaId),
8358            ]
8359        },
8360    }),
8361});
8362
8363pub const MZ_HYDRATION_STATUSES_IND: BuiltinIndex = BuiltinIndex {
8364    name: "mz_hydration_statuses_ind",
8365    schema: MZ_INTERNAL_SCHEMA,
8366    oid: oid::INDEX_MZ_HYDRATION_STATUSES_IND_OID,
8367    sql: "IN CLUSTER mz_catalog_server
8368ON mz_internal.mz_hydration_statuses (object_id, replica_id)",
8369    is_retained_metrics_object: false,
8370};
8371
8372pub static MZ_MATERIALIZATION_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8373    name: "mz_materialization_dependencies",
8374    schema: MZ_INTERNAL_SCHEMA,
8375    oid: oid::VIEW_MZ_MATERIALIZATION_DEPENDENCIES_OID,
8376    desc: RelationDesc::builder()
8377        .with_column("object_id", SqlScalarType::String.nullable(false))
8378        .with_column("dependency_id", SqlScalarType::String.nullable(false))
8379        .finish(),
8380    column_comments: BTreeMap::from_iter([
8381        (
8382            "object_id",
8383            "The ID of a materialization. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_catalog.mz_sinks.id`.",
8384        ),
8385        (
8386            "dependency_id",
8387            "The ID of a dataflow dependency. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, `mz_catalog.mz_sources.id`, or `mz_catalog.mz_tables.id`.",
8388        ),
8389    ]),
8390    sql: "
8391SELECT object_id, dependency_id
8392FROM mz_internal.mz_compute_dependencies
8393UNION ALL
8394SELECT s.id, d.referenced_object_id AS dependency_id
8395FROM mz_internal.mz_object_dependencies d
8396JOIN mz_catalog.mz_sinks s ON (s.id = d.object_id)
8397JOIN mz_catalog.mz_relations r ON (r.id = d.referenced_object_id)",
8398    access: vec![PUBLIC_SELECT],
8399    ontology: Some(Ontology {
8400        entity_name: "materialization_dep",
8401        description: "Dependencies between materializations",
8402        links: &const {
8403            [
8404                OntologyLink {
8405                    name: "depends_on",
8406                    target: "object",
8407                    properties: LinkProperties::DependsOn {
8408                        source_column: "object_id",
8409                        target_column: "id",
8410                        source_id_type: Some(mz_repr::SemanticType::CatalogItemId),
8411                        requires_mapping: None,
8412                    },
8413                },
8414                OntologyLink {
8415                    name: "dependency_is",
8416                    target: "object",
8417                    properties: LinkProperties::fk("dependency_id", "id", Cardinality::ManyToOne),
8418                },
8419            ]
8420        },
8421        column_semantic_types: &const {
8422            [
8423                ("object_id", SemanticType::CatalogItemId),
8424                ("dependency_id", SemanticType::CatalogItemId),
8425            ]
8426        },
8427    }),
8428});
8429
8430pub static MZ_MATERIALIZATION_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8431    name: "mz_materialization_lag",
8432    schema: MZ_INTERNAL_SCHEMA,
8433    oid: oid::VIEW_MZ_MATERIALIZATION_LAG_OID,
8434    desc: RelationDesc::builder()
8435        .with_column("object_id", SqlScalarType::String.nullable(false))
8436        .with_column("local_lag", SqlScalarType::Interval.nullable(true))
8437        .with_column("global_lag", SqlScalarType::Interval.nullable(true))
8438        .with_column(
8439            "slowest_local_input_id",
8440            SqlScalarType::String.nullable(false),
8441        )
8442        .with_column(
8443            "slowest_global_input_id",
8444            SqlScalarType::String.nullable(false),
8445        )
8446        .finish(),
8447    column_comments: BTreeMap::from_iter([
8448        (
8449            "object_id",
8450            "The ID of the materialized view, index, or sink.",
8451        ),
8452        (
8453            "local_lag",
8454            "The amount of time the materialization lags behind its direct inputs.",
8455        ),
8456        (
8457            "global_lag",
8458            "The amount of time the materialization lags behind its root inputs (sources and tables).",
8459        ),
8460        (
8461            "slowest_local_input_id",
8462            "The ID of the slowest direct input.",
8463        ),
8464        (
8465            "slowest_global_input_id",
8466            "The ID of the slowest root input.",
8467        ),
8468    ]),
8469    sql: "
8470WITH MUTUALLY RECURSIVE
8471    -- IDs of objects for which we want to know the lag.
8472    materializations (id text) AS (
8473        SELECT id FROM mz_catalog.mz_indexes
8474        UNION ALL
8475        SELECT id FROM mz_catalog.mz_materialized_views
8476        UNION ALL
8477        SELECT id FROM mz_catalog.mz_sinks
8478    ),
8479    -- Direct dependencies of materializations.
8480    direct_dependencies (id text, dep_id text) AS (
8481        SELECT m.id, d.dependency_id
8482        FROM materializations m
8483        JOIN mz_internal.mz_materialization_dependencies d ON (m.id = d.object_id)
8484    ),
8485    -- All transitive dependencies of materializations.
8486    transitive_dependencies (id text, dep_id text) AS (
8487        SELECT id, dep_id FROM direct_dependencies
8488        UNION
8489        SELECT td.id, dd.dep_id
8490        FROM transitive_dependencies td
8491        JOIN direct_dependencies dd ON (dd.id = td.dep_id)
8492    ),
8493    -- Root dependencies of materializations (sources and tables).
8494    root_dependencies (id text, dep_id text) AS (
8495        SELECT *
8496        FROM transitive_dependencies td
8497        WHERE NOT EXISTS (
8498            SELECT 1
8499            FROM direct_dependencies dd
8500            WHERE dd.id = td.dep_id
8501        )
8502    ),
8503    -- Write progress times of materializations.
8504    materialization_times (id text, time timestamptz) AS (
8505        SELECT m.id, to_timestamp(f.write_frontier::text::double / 1000)
8506        FROM materializations m
8507        JOIN mz_internal.mz_frontiers f ON (m.id = f.object_id)
8508    ),
8509    -- Write progress times of direct dependencies of materializations.
8510    input_times (id text, slowest_dep text, time timestamptz) AS (
8511        SELECT DISTINCT ON (d.id)
8512            d.id,
8513            d.dep_id,
8514            to_timestamp(f.write_frontier::text::double / 1000)
8515        FROM direct_dependencies d
8516        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
8517        ORDER BY d.id, f.write_frontier ASC
8518    ),
8519    -- Write progress times of root dependencies of materializations.
8520    root_times (id text, slowest_dep text, time timestamptz) AS (
8521        SELECT DISTINCT ON (d.id)
8522            d.id,
8523            d.dep_id,
8524            to_timestamp(f.write_frontier::text::double / 1000)
8525        FROM root_dependencies d
8526        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
8527        ORDER BY d.id, f.write_frontier ASC
8528    )
8529SELECT
8530    id AS object_id,
8531    -- Ensure that lag values are always NULL for materializations that have reached the empty
8532    -- frontier, as those have processed all their input data.
8533    -- Also make sure that lag values are never negative, even when input frontiers are before
8534    -- output frontiers (as can happen during hydration).
8535    CASE
8536        WHEN m.time IS NULL THEN INTERVAL '0'
8537        WHEN i.time IS NULL THEN NULL
8538        ELSE greatest(i.time - m.time, INTERVAL '0')
8539    END AS local_lag,
8540    CASE
8541        WHEN m.time IS NULL THEN INTERVAL '0'
8542        WHEN r.time IS NULL THEN NULL
8543        ELSE greatest(r.time - m.time, INTERVAL '0')
8544    END AS global_lag,
8545    i.slowest_dep AS slowest_local_input_id,
8546    r.slowest_dep AS slowest_global_input_id
8547FROM materialization_times m
8548JOIN input_times i USING (id)
8549JOIN root_times r USING (id)",
8550    access: vec![PUBLIC_SELECT],
8551    ontology: Some(Ontology {
8552        entity_name: "materialization_lag",
8553        description: "Lag between a materialization and its inputs",
8554        links: &const {
8555            [
8556                OntologyLink {
8557                    name: "measures_materialization_lag",
8558                    target: "object",
8559                    properties: LinkProperties::measures("object_id", "id", "materialization_lag"),
8560                },
8561                OntologyLink {
8562                    name: "slowest_local_input",
8563                    target: "object",
8564                    properties: LinkProperties::fk(
8565                        "slowest_local_input_id",
8566                        "id",
8567                        Cardinality::ManyToOne,
8568                    ),
8569                },
8570                OntologyLink {
8571                    name: "slowest_global_input",
8572                    target: "object",
8573                    properties: LinkProperties::fk(
8574                        "slowest_global_input_id",
8575                        "id",
8576                        Cardinality::ManyToOne,
8577                    ),
8578                },
8579            ]
8580        },
8581        column_semantic_types: &const {
8582            [
8583                ("object_id", SemanticType::CatalogItemId),
8584                ("slowest_local_input_id", SemanticType::CatalogItemId),
8585                ("slowest_global_input_id", SemanticType::CatalogItemId),
8586            ]
8587        },
8588    }),
8589});
8590/// Worst-process shares of one process's RAM allocation, shared by the console
8591/// utilization view bodies. All three divide by the same denominator so they
8592/// stack on one axis: `ram_percent` is the bar, `swap_of_ram_percent` sits on
8593/// top, and `heap_limit_percent` marks where RAM plus swap runs out, above 1.0.
8594/// Assumes the metrics relation is bound as `m` and the sizes relation as `s`.
8595///
8596/// NOTE: worst-process shares, not replica totals. `memory_percent` alongside
8597/// them sums across processes instead; the two agree at `scale=1`, but above it
8598/// these report "the worst process is at 98% of its own allocation" where
8599/// `memory_percent` reports "the replica is at 32% overall". A replica dies on
8600/// one process being OOM-killed, so the chart's limit line wants the former.
8601///
8602/// NOTE: peak RAM and peak swap are independent maxima, so under multi-process
8603/// skew they can describe different processes and the stack is an upper bound.
8604///
8605/// NOTE: a size that cannot swap reads 0 here, not null. clusterd reports
8606/// `VmSwap` whenever it can read `/proc/self/status`, and that is 0 for a
8607/// process with no swap. Null means no sample at all: the process orchestrator,
8608/// a failed usage fetch, or history predating the column. `heap_limit_percent`
8609/// is what separates "cannot swap" from "did not swap", reading 1.0 exactly
8610/// when the cgroup grants no swap beyond RAM.
8611///
8612/// NOTE: these recombine to `heap_percent` where the maxima agree, so prefer
8613/// that column over a fourth spelling of the same quantity.
8614const CONSOLE_MEMORY_SHARES_SQL: &str = "\
8615    MAX(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0) AS ram_percent,
8616    MAX(m.swap_bytes::float8) / NULLIF(s.memory_bytes, 0) AS swap_of_ram_percent,
8617    MAX(m.heap_limit::float8) / NULLIF(s.memory_bytes, 0) AS heap_limit_percent";
8618
8619/// The output relation shared by all `mz_console_cluster_utilization_overview*`
8620/// views. Every (bucket size, retention) variant produces the same columns so
8621/// the Console can swap between them based on the selected time range.
8622fn console_cluster_utilization_overview_desc() -> RelationDesc {
8623    RelationDesc::builder()
8624        .with_column(
8625            "bucket_start",
8626            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8627        )
8628        .with_column("replica_id", SqlScalarType::String.nullable(false))
8629        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
8630        .with_column(
8631            "max_memory_at",
8632            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8633        )
8634        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
8635        .with_column(
8636            "max_disk_at",
8637            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8638        )
8639        .with_column(
8640            "memory_and_disk_percent",
8641            SqlScalarType::Float64.nullable(true),
8642        )
8643        .with_column(
8644            "max_memory_and_disk_memory_percent",
8645            SqlScalarType::Float64.nullable(true),
8646        )
8647        .with_column(
8648            "max_memory_and_disk_disk_percent",
8649            SqlScalarType::Float64.nullable(true),
8650        )
8651        .with_column(
8652            "max_memory_and_disk_at",
8653            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8654        )
8655        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
8656        .with_column(
8657            "max_heap_at",
8658            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8659        )
8660        .with_column("ram_percent", SqlScalarType::Float64.nullable(true))
8661        .with_column("swap_of_ram_percent", SqlScalarType::Float64.nullable(true))
8662        .with_column("heap_limit_percent", SqlScalarType::Float64.nullable(true))
8663        .with_column("max_cpu_percent", SqlScalarType::Float64.nullable(true))
8664        .with_column(
8665            "max_cpu_at",
8666            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8667        )
8668        .with_column("offline_events", SqlScalarType::Jsonb.nullable(true))
8669        .with_column(
8670            "bucket_end",
8671            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8672        )
8673        .with_column("name", SqlScalarType::String.nullable(true))
8674        .with_column("cluster_id", SqlScalarType::String.nullable(true))
8675        .with_column("size", SqlScalarType::String.nullable(true))
8676        .finish()
8677}
8678
8679/// Builds the SQL body shared by the `mz_console_cluster_utilization_overview*`
8680/// views, which power the Console's cluster utilization graphs.
8681///
8682/// There is one view per (bucket width, retention window) pair so the Console
8683/// can read a pre-materialized, indexed rollup for each time range it offers
8684/// instead of recomputing this (expensive) query on every page load. The bodies
8685/// must be kept in sync with the equivalent ad-hoc query in the Console
8686/// (`buildReplicaUtilizationHistoryQuery` in
8687/// `console/src/api/materialize/cluster/replicaUtilizationHistory.ts`).
8688///
8689/// * `bin`: the `date_bin` bucket width, e.g. `1 MINUTE`.
8690/// * `retention`: how much history the view retains, e.g. `3 HOURS`, enforced with a temporal
8691///   `mz_now()` filter so the maintained arrangement stays bounded.
8692/// * `group_size`: the expected number of metric samples per (replica, bucket), used for the
8693///   `DISTINCT ON INPUT GROUP SIZE` top-k hint. Replica metrics are scraped roughly once per
8694///   minute, so this is the bucket width in minutes.
8695fn console_cluster_utilization_overview_sql(bin: &str, retention: &str, group_size: u32) -> String {
8696    format!(
8697        r#"WITH replica_history AS (
8698  SELECT replica_id, size, cluster_id
8699  FROM mz_internal.mz_cluster_replica_history
8700  UNION
8701  -- We union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters.
8702  SELECT id AS replica_id, size, cluster_id
8703  FROM mz_catalog.mz_cluster_replicas
8704),
8705replica_metrics_history AS (
8706  SELECT
8707    m.occurred_at,
8708    m.replica_id,
8709    r.size,
8710    (SUM(m.cpu_nano_cores::float8) / NULLIF(s.cpu_nano_cores, 0) / NULLIF(s.processes, 0)) AS cpu_percent,
8711    (SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0) / NULLIF(s.processes, 0)) AS memory_percent,
8712    (SUM(m.disk_bytes::float8) / NULLIF(s.disk_bytes, 0) / NULLIF(s.processes, 0)) AS disk_percent,
8713    SUM(m.disk_bytes::float8) AS disk_bytes,
8714    SUM(m.memory_bytes::float8) AS memory_bytes,
8715    s.disk_bytes::float8 * s.processes AS total_disk_bytes,
8716    s.memory_bytes::float8 * s.processes AS total_memory_bytes,
8717    MAX(m.heap_bytes::float8) AS heap_bytes,
8718    MAX(m.heap_limit) AS heap_limit,
8719    -- heap_limit is NULL when clusterd isn't launched with --heap-limit (e.g.
8720    -- the emulator's process orchestrator). Fall back to the size-based memory
8721    -- percent so the chart still renders.
8722    COALESCE(
8723      MAX(m.heap_bytes::float8 / NULLIF(m.heap_limit, 0)),
8724      SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0) / NULLIF(s.processes, 0)
8725    ) AS heap_percent,
8726{shares}
8727  FROM
8728    replica_history AS r
8729    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8730    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
8731  GROUP BY
8732    m.occurred_at,
8733    m.replica_id,
8734    r.size,
8735    s.cpu_nano_cores,
8736    s.memory_bytes,
8737    s.disk_bytes,
8738    s.processes
8739),
8740replica_utilization_history_binned AS (
8741  -- NOTE: we read directly from replica_metrics_history rather than re-joining
8742  -- replica_history; every replica_id here already came from replica_history,
8743  -- so the join was redundant (and could fan out a replica that changed size).
8744  SELECT
8745    m.occurred_at,
8746    m.replica_id,
8747    m.cpu_percent,
8748    m.memory_percent,
8749    m.memory_bytes,
8750    m.disk_percent,
8751    m.disk_bytes,
8752    m.total_disk_bytes,
8753    m.total_memory_bytes,
8754    m.heap_bytes,
8755    m.heap_percent,
8756    m.ram_percent,
8757    m.swap_of_ram_percent,
8758    m.heap_limit_percent,
8759    m.size,
8760    date_bin('{bin}', m.occurred_at, '1970-01-01'::timestamp) AS bucket_start
8761  FROM replica_metrics_history AS m
8762  WHERE mz_now() <= date_bin('{bin}', m.occurred_at, '1970-01-01'::timestamp) + INTERVAL '{retention}'
8763),
8764-- For each (replica, bucket), take the sample with the highest memory.
8765max_memory AS (
8766  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start, replica_id, memory_percent, occurred_at
8767  FROM replica_utilization_history_binned
8768  OPTIONS (DISTINCT ON INPUT GROUP SIZE = {group_size})
8769  ORDER BY bucket_start, replica_id, COALESCE(memory_bytes, 0) DESC
8770),
8771-- For each (replica, bucket), take the sample with the highest disk.
8772max_disk AS (
8773  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start, replica_id, disk_percent, occurred_at
8774  FROM replica_utilization_history_binned
8775  OPTIONS (DISTINCT ON INPUT GROUP SIZE = {group_size})
8776  ORDER BY bucket_start, replica_id, COALESCE(disk_bytes, 0) DESC
8777),
8778-- For each (replica, bucket), take the sample with the highest cpu.
8779max_cpu AS (
8780  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start, replica_id, cpu_percent, occurred_at
8781  FROM replica_utilization_history_binned
8782  OPTIONS (DISTINCT ON INPUT GROUP SIZE = {group_size})
8783  ORDER BY bucket_start, replica_id, COALESCE(cpu_percent, 0) DESC
8784),
8785/*
8786  For each (replica, bucket), take the sample with the highest combined memory
8787  and disk. This is different from adding max_memory and max_disk per bucket
8788  because both values may not occur at the same time if the bucket interval is
8789  large.
8790*/
8791max_memory_and_disk AS (
8792  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start, replica_id, memory_percent, disk_percent, memory_and_disk_percent, occurred_at
8793  FROM (
8794    SELECT *,
8795      CASE
8796        WHEN disk_bytes IS NULL AND memory_bytes IS NULL THEN NULL
8797        ELSE (COALESCE(memory_bytes, 0) + COALESCE(disk_bytes, 0)) / NULLIF((total_memory_bytes + total_disk_bytes), 0)
8798      END AS memory_and_disk_percent
8799    FROM replica_utilization_history_binned
8800  ) AS max_memory_and_disk_inner
8801  OPTIONS (DISTINCT ON INPUT GROUP SIZE = {group_size})
8802  ORDER BY bucket_start, replica_id, COALESCE(memory_and_disk_percent, 0) DESC
8803),
8804-- For each (replica, bucket), take the sample with the highest heap. The RAM
8805-- and swap shares ride along, so they describe that sample rather than the
8806-- bucket's peak RAM, which is what max_memory reports.
8807max_heap AS (
8808  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start, replica_id, heap_percent, ram_percent, swap_of_ram_percent, heap_limit_percent, occurred_at
8809  FROM replica_utilization_history_binned
8810  OPTIONS (DISTINCT ON INPUT GROUP SIZE = {group_size})
8811  ORDER BY bucket_start, replica_id, COALESCE(heap_bytes, 0) DESC
8812),
8813-- For each (replica, bucket), collect its offline events at that time.
8814replica_offline_event_history AS (
8815  SELECT
8816    date_bin('{bin}', occurred_at, '1970-01-01'::timestamp) AS bucket_start,
8817    replica_id,
8818    jsonb_agg(
8819      jsonb_build_object(
8820        'replicaId', rsh.replica_id,
8821        'occurredAt', rsh.occurred_at,
8822        'status', rsh.status,
8823        'reason', rsh.reason
8824      )
8825    ) AS offline_events
8826  FROM mz_internal.mz_cluster_replica_status_history AS rsh
8827  -- We assume the statuses for process 0 are the same as all processes.
8828  WHERE process_id = '0'
8829    AND status = 'offline'
8830    AND mz_now() <= date_bin('{bin}', occurred_at, '1970-01-01'::timestamp) + INTERVAL '{retention}'
8831  GROUP BY bucket_start, replica_id
8832)
8833SELECT
8834  bucket_start,
8835  replica_id,
8836  max_memory.memory_percent,
8837  max_memory.occurred_at AS max_memory_at,
8838  max_disk.disk_percent,
8839  max_disk.occurred_at AS max_disk_at,
8840  max_memory_and_disk.memory_and_disk_percent AS memory_and_disk_percent,
8841  max_memory_and_disk.memory_percent AS max_memory_and_disk_memory_percent,
8842  max_memory_and_disk.disk_percent AS max_memory_and_disk_disk_percent,
8843  max_memory_and_disk.occurred_at AS max_memory_and_disk_at,
8844  max_heap.heap_percent,
8845  max_heap.occurred_at AS max_heap_at,
8846  max_heap.ram_percent,
8847  max_heap.swap_of_ram_percent,
8848  max_heap.heap_limit_percent,
8849  max_cpu.cpu_percent AS max_cpu_percent,
8850  max_cpu.occurred_at AS max_cpu_at,
8851  replica_offline_event_history.offline_events,
8852  bucket_start + INTERVAL '{bin}' AS bucket_end,
8853  replica_name_history.new_name AS name,
8854  replica_history.cluster_id,
8855  replica_history.size
8856FROM max_memory
8857JOIN max_disk USING (bucket_start, replica_id)
8858JOIN max_cpu USING (bucket_start, replica_id)
8859JOIN max_memory_and_disk USING (bucket_start, replica_id)
8860JOIN max_heap USING (bucket_start, replica_id)
8861JOIN replica_history USING (replica_id)
8862/*
8863  TOP k=1 over the name history via a LATERAL subquery + LIMIT: for each bucket,
8864  get the most recent replica name as of the end of the bucket.
8865*/
8866CROSS JOIN LATERAL (
8867  SELECT new_name
8868  FROM mz_internal.mz_cluster_replica_name_history AS replica_name_history
8869  WHERE replica_id = replica_name_history.id
8870    -- We treat NULLs as the beginning of time.
8871    AND bucket_start + INTERVAL '{bin}' >= COALESCE(replica_name_history.occurred_at, '1970-01-01'::timestamp)
8872  ORDER BY replica_name_history.occurred_at DESC
8873  LIMIT 1
8874) AS replica_name_history
8875LEFT JOIN replica_offline_event_history USING (bucket_start, replica_id)"#,
8876        bin = bin,
8877        retention = retention,
8878        group_size = group_size,
8879        shares = CONSOLE_MEMORY_SHARES_SQL,
8880    )
8881}
8882
8883/// Schema for the un-binned 3-hour console cluster utilization base. Unlike the
8884/// binned `_overview*` views, this exposes raw per-(replica, sample) metrics so
8885/// the Console can bin client-side.
8886fn console_cluster_utilization_unbinned_3h_desc() -> RelationDesc {
8887    RelationDesc::builder()
8888        .with_column("replica_id", SqlScalarType::String.nullable(false))
8889        .with_column("cluster_id", SqlScalarType::String.nullable(true))
8890        .with_column("size", SqlScalarType::String.nullable(false))
8891        .with_column("name", SqlScalarType::String.nullable(true))
8892        .with_column(
8893            "occurred_at",
8894            SqlScalarType::TimestampTz { precision: None }.nullable(false),
8895        )
8896        .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
8897        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
8898        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
8899        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
8900        .with_column("ram_percent", SqlScalarType::Float64.nullable(true))
8901        .with_column("swap_of_ram_percent", SqlScalarType::Float64.nullable(true))
8902        .with_column("heap_limit_percent", SqlScalarType::Float64.nullable(true))
8903        .with_column(
8904            "memory_and_disk_percent",
8905            SqlScalarType::Float64.nullable(true),
8906        )
8907        .finish()
8908}
8909
8910/// Builds the SQL for the un-binned 3-hour console cluster utilization base: one
8911/// row per (replica, metric sample) over `retention`, with no `date_bin`/top-k,
8912/// so the Console bins it client-side. The binned `_overview*` views handle the
8913/// longer windows. A temporal `mz_now()` filter bounds the maintained
8914/// arrangement. Kept in sync with the Console
8915/// (`buildConsoleClusterUtilizationUnbinned3hQuery` in
8916/// `replicaUtilizationHistory.ts`).
8917fn console_cluster_utilization_unbinned_3h_sql(retention: &str) -> String {
8918    format!(
8919        r#"WITH replica_history AS (
8920  -- Dedup to one row per replica (prefer the current size). Size is fixed per
8921  -- replica so this is normally a no-op, but a stray duplicate size in history
8922  -- would fan out the metrics join; with no Top-1 dedup here that would emit two
8923  -- rows per (replica_id, occurred_at) and break the Console SUBSCRIBE upsert key.
8924  SELECT DISTINCT ON (replica_id) replica_id, size, cluster_id
8925  FROM (
8926    -- We union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters.
8927    SELECT id AS replica_id, size, cluster_id, 0 AS source_rank
8928    FROM mz_catalog.mz_cluster_replicas
8929    UNION ALL
8930    SELECT replica_id, size, cluster_id, 1 AS source_rank
8931    FROM mz_internal.mz_cluster_replica_history
8932  ) all_replicas
8933  ORDER BY replica_id, source_rank
8934),
8935replica_metrics AS (
8936  SELECT
8937    m.occurred_at,
8938    m.replica_id,
8939    r.cluster_id,
8940    r.size,
8941    (SUM(m.cpu_nano_cores::float8) / NULLIF(s.cpu_nano_cores, 0) / NULLIF(s.processes, 0)) AS cpu_percent,
8942    (SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0) / NULLIF(s.processes, 0)) AS memory_percent,
8943    (SUM(m.disk_bytes::float8) / NULLIF(s.disk_bytes, 0) / NULLIF(s.processes, 0)) AS disk_percent,
8944    COALESCE(
8945      MAX(m.heap_bytes::float8 / NULLIF(m.heap_limit, 0)),
8946      SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0) / NULLIF(s.processes, 0)
8947    ) AS heap_percent,
8948{shares},
8949    CASE
8950      WHEN SUM(m.disk_bytes::float8) IS NULL AND SUM(m.memory_bytes::float8) IS NULL THEN NULL
8951      ELSE (COALESCE(SUM(m.memory_bytes::float8), 0) + COALESCE(SUM(m.disk_bytes::float8), 0))
8952           / NULLIF((s.memory_bytes::float8 + s.disk_bytes::float8) * s.processes, 0)
8953    END AS memory_and_disk_percent
8954  FROM replica_history AS r
8955    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
8956    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
8957  -- No aggregation over time: one row per (replica, sample) so the Console bins
8958  -- client-side. The temporal mz_now() filter keeps the maintained arrangement
8959  -- bounded to the retention window.
8960  WHERE mz_now() <= m.occurred_at + INTERVAL '{retention}'
8961  GROUP BY
8962    m.occurred_at,
8963    m.replica_id,
8964    r.cluster_id,
8965    r.size,
8966    s.cpu_nano_cores,
8967    s.memory_bytes,
8968    s.disk_bytes,
8969    s.processes
8970)
8971SELECT
8972  m.replica_id,
8973  m.cluster_id,
8974  m.size,
8975  replica_name_history.new_name AS name,
8976  m.occurred_at,
8977  m.cpu_percent,
8978  m.memory_percent,
8979  m.disk_percent,
8980  m.heap_percent,
8981  m.ram_percent,
8982  m.swap_of_ram_percent,
8983  m.heap_limit_percent,
8984  m.memory_and_disk_percent
8985FROM replica_metrics AS m
8986/* Most recent replica name as of the sample time. */
8987CROSS JOIN LATERAL (
8988  SELECT new_name
8989  FROM mz_internal.mz_cluster_replica_name_history AS replica_name_history
8990  WHERE m.replica_id = replica_name_history.id
8991    -- We treat NULLs as the beginning of time.
8992    AND m.occurred_at >= COALESCE(replica_name_history.occurred_at, '1970-01-01'::timestamp)
8993  ORDER BY replica_name_history.occurred_at DESC
8994  LIMIT 1
8995) AS replica_name_history"#,
8996        retention = retention,
8997        shares = CONSOLE_MEMORY_SHARES_SQL,
8998    )
8999}
9000
9001/**
9002 * Displays cluster utilization over 14 days bucketed by 1 hour, for the
9003 * Console's environment overview and cluster pages, to speed up load times.
9004 * This view (and its `_3h`/`_24h` siblings) is kept in sync with
9005 * MaterializeInc/console/src/api/materialize/cluster/replicaUtilizationHistory.ts
9006 */
9007pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW: LazyLock<BuiltinView> =
9008    LazyLock::new(|| BuiltinView {
9009        name: "mz_console_cluster_utilization_overview",
9010        schema: MZ_INTERNAL_SCHEMA,
9011        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_OID,
9012        desc: console_cluster_utilization_overview_desc(),
9013        column_comments: BTreeMap::new(),
9014        sql: Box::leak(
9015            console_cluster_utilization_overview_sql("1 HOUR", "14 DAYS", 60).into_boxed_str(),
9016        ),
9017        access: vec![PUBLIC_SELECT],
9018        ontology: None,
9019    });
9020
9021/**
9022 * Un-binned cluster utilization over the last 3 hours, for the Console's "Last
9023 * hour" / "Last 3 hours" graphs. Unlike the binned `_overview*` views, this
9024 * exposes raw per-(replica, sample) metrics and the Console bins client-side.
9025 * See `console_cluster_utilization_unbinned_3h_sql` for details.
9026 */
9027pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_3H: LazyLock<BuiltinView> =
9028    LazyLock::new(|| BuiltinView {
9029        name: "mz_console_cluster_utilization_overview_3h",
9030        schema: MZ_INTERNAL_SCHEMA,
9031        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_3H_OID,
9032        desc: console_cluster_utilization_unbinned_3h_desc(),
9033        column_comments: BTreeMap::new(),
9034        sql: Box::leak(console_cluster_utilization_unbinned_3h_sql("3 HOURS").into_boxed_str()),
9035        access: vec![PUBLIC_SELECT],
9036        ontology: None,
9037    });
9038
9039/**
9040 * Cluster utilization over the last 24 hours bucketed by 5 minutes, for the
9041 * Console's "Last 6 hours" / "Last 24 hours" cluster utilization graphs. See
9042 * `console_cluster_utilization_overview_sql` for details.
9043 */
9044pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_24H: LazyLock<BuiltinView> =
9045    LazyLock::new(|| BuiltinView {
9046        name: "mz_console_cluster_utilization_overview_24h",
9047        schema: MZ_INTERNAL_SCHEMA,
9048        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_24H_OID,
9049        desc: console_cluster_utilization_overview_desc(),
9050        column_comments: BTreeMap::new(),
9051        sql: Box::leak(
9052            console_cluster_utilization_overview_sql("5 MINUTES", "24 HOURS", 5).into_boxed_str(),
9053        ),
9054        access: vec![PUBLIC_SELECT],
9055        ontology: None,
9056    });
9057/**
9058 * Traces the blue/green deployment lineage in the audit log to determine all cluster
9059 * IDs that are logically the same cluster.
9060 * cluster_id: The ID of a cluster.
9061 * current_deployment_cluster_id: The cluster ID of the last cluster in
9062 *   cluster_id's blue/green lineage.
9063 * cluster_name: The name of the cluster.
9064 * The approach taken is as follows. First, find all extant clusters and add them
9065 * to the result set. Per cluster, we do the following:
9066 * 1. Find the most recent create or rename event. This moment represents when the cluster took
9067 *    on its final logical identity.
9068 * 2. Look for a cluster that had the same name (or the same name with `_dbt_deploy` appended)
9069 *    that was dropped within one minute of that moment. That cluster is almost certainly the
9070 *    logical predecessor of the current cluster. Add the cluster to the result set.
9071 * 3. Repeat the procedure until a cluster with no logical predecessor is discovered.
9072 * Limiting the search for a dropped cluster to a window of one minute is a heuristic,
9073 * but one that's likely to be pretty good one. If a name is reused after more
9074 * than one minute, that's a good sign that it wasn't an automatic blue/green
9075 * process, but someone turning on a new use case that happens to have the same
9076 * name as a previous but logically distinct use case.
9077 */
9078pub static MZ_CLUSTER_DEPLOYMENT_LINEAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9079    name: "mz_cluster_deployment_lineage",
9080    schema: MZ_INTERNAL_SCHEMA,
9081    oid: oid::VIEW_MZ_CLUSTER_DEPLOYMENT_LINEAGE_OID,
9082    desc: RelationDesc::builder()
9083        .with_column("cluster_id", SqlScalarType::String.nullable(true))
9084        .with_column(
9085            "current_deployment_cluster_id",
9086            SqlScalarType::String.nullable(false),
9087        )
9088        .with_column("cluster_name", SqlScalarType::String.nullable(false))
9089        .with_key(vec![0, 1, 2])
9090        .finish(),
9091    column_comments: BTreeMap::from_iter([
9092        (
9093            "cluster_id",
9094            "The ID of the cluster. Corresponds to `mz_clusters.id` (though the cluster may no longer exist).",
9095        ),
9096        (
9097            "current_deployment_cluster_id",
9098            "The cluster ID of the last cluster in `cluster_id`'s blue/green lineage (the cluster is guaranteed to exist).",
9099        ),
9100        ("cluster_name", "The name of the cluster"),
9101    ]),
9102    sql: r#"WITH MUTUALLY RECURSIVE cluster_events (
9103  cluster_id text,
9104  cluster_name text,
9105  event_type text,
9106  occurred_at timestamptz
9107) AS (
9108  SELECT coalesce(details->>'id', details->>'cluster_id') AS cluster_id,
9109    coalesce(details->>'name', details->>'new_name') AS cluster_name,
9110    event_type,
9111    occurred_at
9112  FROM mz_audit_events
9113  WHERE (
9114      event_type IN ('create', 'drop')
9115      OR (
9116        event_type = 'alter'
9117        AND details ? 'new_name'
9118      )
9119    )
9120    AND object_type = 'cluster'
9121    AND mz_now() < occurred_at + INTERVAL '30 days'
9122),
9123mz_cluster_deployment_lineage (
9124  cluster_id text,
9125  current_deployment_cluster_id text,
9126  cluster_name text
9127) AS (
9128  SELECT c.id,
9129    c.id,
9130    c.name
9131  FROM mz_clusters c
9132  WHERE c.id LIKE 'u%'
9133  UNION
9134  SELECT *
9135  FROM dropped_clusters
9136),
9137-- Closest create or rename event based on the current clusters in the result set
9138most_recent_create_or_rename (
9139  cluster_id text,
9140  current_deployment_cluster_id text,
9141  cluster_name text,
9142  occurred_at timestamptz
9143) AS (
9144  SELECT DISTINCT ON (e.cluster_id) e.cluster_id,
9145    c.current_deployment_cluster_id,
9146    e.cluster_name,
9147    e.occurred_at
9148  FROM mz_cluster_deployment_lineage c
9149    JOIN cluster_events e ON c.cluster_id = e.cluster_id
9150    AND c.cluster_name = e.cluster_name
9151  WHERE e.event_type <> 'drop'
9152  ORDER BY e.cluster_id,
9153    e.occurred_at DESC
9154),
9155-- Clusters that were dropped most recently within 1 minute of most_recent_create_or_rename
9156dropped_clusters (
9157  cluster_id text,
9158  current_deployment_cluster_id text,
9159  cluster_name text
9160) AS (
9161  SELECT DISTINCT ON (cr.cluster_id) e.cluster_id,
9162    cr.current_deployment_cluster_id,
9163    cr.cluster_name
9164  FROM most_recent_create_or_rename cr
9165    JOIN cluster_events e ON e.occurred_at BETWEEN cr.occurred_at - interval '1 minute'
9166    AND cr.occurred_at + interval '1 minute'
9167    AND (
9168      e.cluster_name = cr.cluster_name
9169      OR e.cluster_name = cr.cluster_name || '_dbt_deploy'
9170    )
9171  WHERE e.event_type = 'drop'
9172  ORDER BY cr.cluster_id,
9173    abs(
9174      extract(
9175        epoch
9176        FROM cr.occurred_at - e.occurred_at
9177      )
9178    )
9179)
9180SELECT *
9181FROM mz_cluster_deployment_lineage"#,
9182    access: vec![PUBLIC_SELECT],
9183    ontology: Some(Ontology {
9184        entity_name: "cluster_deployment",
9185        description: "Cluster deployment lineage information",
9186        links: &const {
9187            [
9188                OntologyLink {
9189                    name: "deployment_of",
9190                    target: "cluster",
9191                    properties: LinkProperties::fk("cluster_id", "id", Cardinality::ManyToOne),
9192                },
9193                OntologyLink {
9194                    name: "current_deployment",
9195                    target: "cluster",
9196                    properties: LinkProperties::fk(
9197                        "current_deployment_cluster_id",
9198                        "id",
9199                        Cardinality::ManyToOne,
9200                    ),
9201                },
9202            ]
9203        },
9204        column_semantic_types: &[],
9205    }),
9206});
9207
9208pub const MZ_SHOW_DATABASES_IND: BuiltinIndex = BuiltinIndex {
9209    name: "mz_show_databases_ind",
9210    schema: MZ_INTERNAL_SCHEMA,
9211    oid: oid::INDEX_MZ_SHOW_DATABASES_IND_OID,
9212    sql: "IN CLUSTER mz_catalog_server
9213ON mz_internal.mz_show_databases (name)",
9214    is_retained_metrics_object: false,
9215};
9216
9217pub const MZ_SHOW_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
9218    name: "mz_show_schemas_ind",
9219    schema: MZ_INTERNAL_SCHEMA,
9220    oid: oid::INDEX_MZ_SHOW_SCHEMAS_IND_OID,
9221    sql: "IN CLUSTER mz_catalog_server
9222ON mz_internal.mz_show_schemas (database_id)",
9223    is_retained_metrics_object: false,
9224};
9225
9226pub const MZ_SHOW_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
9227    name: "mz_show_connections_ind",
9228    schema: MZ_INTERNAL_SCHEMA,
9229    oid: oid::INDEX_MZ_SHOW_CONNECTIONS_IND_OID,
9230    sql: "IN CLUSTER mz_catalog_server
9231ON mz_internal.mz_show_connections (schema_id)",
9232    is_retained_metrics_object: false,
9233};
9234
9235pub const MZ_SHOW_TABLES_IND: BuiltinIndex = BuiltinIndex {
9236    name: "mz_show_tables_ind",
9237    schema: MZ_INTERNAL_SCHEMA,
9238    oid: oid::INDEX_MZ_SHOW_TABLES_IND_OID,
9239    sql: "IN CLUSTER mz_catalog_server
9240ON mz_internal.mz_show_tables (schema_id)",
9241    is_retained_metrics_object: false,
9242};
9243
9244pub const MZ_SHOW_SOURCES_IND: BuiltinIndex = BuiltinIndex {
9245    name: "mz_show_sources_ind",
9246    schema: MZ_INTERNAL_SCHEMA,
9247    oid: oid::INDEX_MZ_SHOW_SOURCES_IND_OID,
9248    sql: "IN CLUSTER mz_catalog_server
9249ON mz_internal.mz_show_sources (schema_id)",
9250    is_retained_metrics_object: false,
9251};
9252
9253pub const MZ_SHOW_VIEWS_IND: BuiltinIndex = BuiltinIndex {
9254    name: "mz_show_views_ind",
9255    schema: MZ_INTERNAL_SCHEMA,
9256    oid: oid::INDEX_MZ_SHOW_VIEWS_IND_OID,
9257    sql: "IN CLUSTER mz_catalog_server
9258ON mz_internal.mz_show_views (schema_id)",
9259    is_retained_metrics_object: false,
9260};
9261
9262pub const MZ_SHOW_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
9263    name: "mz_show_materialized_views_ind",
9264    schema: MZ_INTERNAL_SCHEMA,
9265    oid: oid::INDEX_MZ_SHOW_MATERIALIZED_VIEWS_IND_OID,
9266    sql: "IN CLUSTER mz_catalog_server
9267ON mz_internal.mz_show_materialized_views (schema_id)",
9268    is_retained_metrics_object: false,
9269};
9270
9271pub const MZ_SHOW_SINKS_IND: BuiltinIndex = BuiltinIndex {
9272    name: "mz_show_sinks_ind",
9273    schema: MZ_INTERNAL_SCHEMA,
9274    oid: oid::INDEX_MZ_SHOW_SINKS_IND_OID,
9275    sql: "IN CLUSTER mz_catalog_server
9276ON mz_internal.mz_show_sinks (schema_id)",
9277    is_retained_metrics_object: false,
9278};
9279
9280pub const MZ_SHOW_TYPES_IND: BuiltinIndex = BuiltinIndex {
9281    name: "mz_show_types_ind",
9282    schema: MZ_INTERNAL_SCHEMA,
9283    oid: oid::INDEX_MZ_SHOW_TYPES_IND_OID,
9284    sql: "IN CLUSTER mz_catalog_server
9285ON mz_internal.mz_show_types (schema_id)",
9286    is_retained_metrics_object: false,
9287};
9288
9289pub const MZ_SHOW_ROLES_IND: BuiltinIndex = BuiltinIndex {
9290    name: "mz_show_roles_ind",
9291    schema: MZ_INTERNAL_SCHEMA,
9292    oid: oid::INDEX_MZ_SHOW_ROLES_IND_OID,
9293    sql: "IN CLUSTER mz_catalog_server
9294ON mz_internal.mz_show_roles (name)",
9295    is_retained_metrics_object: false,
9296};
9297
9298pub const MZ_SHOW_ALL_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
9299    name: "mz_show_all_objects_ind",
9300    schema: MZ_INTERNAL_SCHEMA,
9301    oid: oid::INDEX_MZ_SHOW_ALL_OBJECTS_IND_OID,
9302    sql: "IN CLUSTER mz_catalog_server
9303ON mz_internal.mz_show_all_objects (schema_id)",
9304    is_retained_metrics_object: false,
9305};
9306
9307pub const MZ_SHOW_INDEXES_IND: BuiltinIndex = BuiltinIndex {
9308    name: "mz_show_indexes_ind",
9309    schema: MZ_INTERNAL_SCHEMA,
9310    oid: oid::INDEX_MZ_SHOW_INDEXES_IND_OID,
9311    sql: "IN CLUSTER mz_catalog_server
9312ON mz_internal.mz_show_indexes (schema_id)",
9313    is_retained_metrics_object: false,
9314};
9315
9316pub const MZ_SHOW_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
9317    name: "mz_show_columns_ind",
9318    schema: MZ_INTERNAL_SCHEMA,
9319    oid: oid::INDEX_MZ_SHOW_COLUMNS_IND_OID,
9320    sql: "IN CLUSTER mz_catalog_server
9321ON mz_internal.mz_show_columns (id)",
9322    is_retained_metrics_object: false,
9323};
9324
9325pub const MZ_SHOW_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
9326    name: "mz_show_clusters_ind",
9327    schema: MZ_INTERNAL_SCHEMA,
9328    oid: oid::INDEX_MZ_SHOW_CLUSTERS_IND_OID,
9329    sql: "IN CLUSTER mz_catalog_server
9330ON mz_internal.mz_show_clusters (name)",
9331    is_retained_metrics_object: false,
9332};
9333
9334pub const MZ_SHOW_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
9335    name: "mz_show_cluster_replicas_ind",
9336    schema: MZ_INTERNAL_SCHEMA,
9337    oid: oid::INDEX_MZ_SHOW_CLUSTER_REPLICAS_IND_OID,
9338    sql: "IN CLUSTER mz_catalog_server
9339ON mz_internal.mz_show_cluster_replicas (cluster)",
9340    is_retained_metrics_object: false,
9341};
9342
9343pub const MZ_SHOW_SECRETS_IND: BuiltinIndex = BuiltinIndex {
9344    name: "mz_show_secrets_ind",
9345    schema: MZ_INTERNAL_SCHEMA,
9346    oid: oid::INDEX_MZ_SHOW_SECRETS_IND_OID,
9347    sql: "IN CLUSTER mz_catalog_server
9348ON mz_internal.mz_show_secrets (schema_id)",
9349    is_retained_metrics_object: false,
9350};
9351
9352pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND: BuiltinIndex = BuiltinIndex {
9353    name: "mz_console_cluster_utilization_overview_ind",
9354    schema: MZ_INTERNAL_SCHEMA,
9355    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND_OID,
9356    sql: "IN CLUSTER mz_catalog_server
9357ON mz_internal.mz_console_cluster_utilization_overview (cluster_id)",
9358    is_retained_metrics_object: false,
9359};
9360
9361pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_3H_IND: BuiltinIndex = BuiltinIndex {
9362    name: "mz_console_cluster_utilization_overview_3h_ind",
9363    schema: MZ_INTERNAL_SCHEMA,
9364    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_3H_IND_OID,
9365    sql: "IN CLUSTER mz_catalog_server
9366ON mz_internal.mz_console_cluster_utilization_overview_3h (cluster_id)",
9367    is_retained_metrics_object: false,
9368};
9369
9370pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_24H_IND: BuiltinIndex = BuiltinIndex {
9371    name: "mz_console_cluster_utilization_overview_24h_ind",
9372    schema: MZ_INTERNAL_SCHEMA,
9373    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_24H_IND_OID,
9374    sql: "IN CLUSTER mz_catalog_server
9375ON mz_internal.mz_console_cluster_utilization_overview_24h (cluster_id)",
9376    is_retained_metrics_object: false,
9377};
9378
9379pub const MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND: BuiltinIndex = BuiltinIndex {
9380    name: "mz_cluster_deployment_lineage_ind",
9381    schema: MZ_INTERNAL_SCHEMA,
9382    oid: oid::INDEX_MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND_OID,
9383    sql: "IN CLUSTER mz_catalog_server
9384ON mz_internal.mz_cluster_deployment_lineage (cluster_id)",
9385    is_retained_metrics_object: false,
9386};
9387
9388pub const MZ_SOURCE_STATUSES_IND: BuiltinIndex = BuiltinIndex {
9389    name: "mz_source_statuses_ind",
9390    schema: MZ_INTERNAL_SCHEMA,
9391    oid: oid::INDEX_MZ_SOURCE_STATUSES_IND_OID,
9392    sql: "IN CLUSTER mz_catalog_server
9393ON mz_internal.mz_source_statuses (id)",
9394    is_retained_metrics_object: false,
9395};
9396
9397pub const MZ_SINK_STATUSES_IND: BuiltinIndex = BuiltinIndex {
9398    name: "mz_sink_statuses_ind",
9399    schema: MZ_INTERNAL_SCHEMA,
9400    oid: oid::INDEX_MZ_SINK_STATUSES_IND_OID,
9401    sql: "IN CLUSTER mz_catalog_server
9402ON mz_internal.mz_sink_statuses (id)",
9403    is_retained_metrics_object: false,
9404};
9405
9406pub const MZ_SOURCE_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9407    name: "mz_source_status_history_ind",
9408    schema: MZ_INTERNAL_SCHEMA,
9409    oid: oid::INDEX_MZ_SOURCE_STATUS_HISTORY_IND_OID,
9410    sql: "IN CLUSTER mz_catalog_server
9411ON mz_internal.mz_source_status_history (source_id)",
9412    is_retained_metrics_object: false,
9413};
9414
9415pub const MZ_SINK_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9416    name: "mz_sink_status_history_ind",
9417    schema: MZ_INTERNAL_SCHEMA,
9418    oid: oid::INDEX_MZ_SINK_STATUS_HISTORY_IND_OID,
9419    sql: "IN CLUSTER mz_catalog_server
9420ON mz_internal.mz_sink_status_history (sink_id)",
9421    is_retained_metrics_object: false,
9422};
9423
9424// In both `mz_source_statistics` and `mz_sink_statistics` we cast the `SUM` of
9425// uint8's to `uint8` instead of leaving them as `numeric`. This is because we want to
9426// save index space, and we don't expect the sum to be > 2^63
9427// (even if a source with 2000 workers, that each produce 400 terabytes in a month ~ 2^61).
9428//
9429//
9430// These aggregations are just to make `GROUP BY` happy. Each id has a single row in the
9431// underlying relation.
9432//
9433// We append WITH_HISTORY because we want to build a separate view + index that doesn't
9434// retain history. This is because retaining its history causes
9435// MZ_SOURCE_STATISTICS_WITH_HISTORY_IND to hold all records/updates, which causes CPU and latency
9436// of querying it to spike.
9437pub static MZ_SOURCE_STATISTICS_WITH_HISTORY: LazyLock<BuiltinView> =
9438    LazyLock::new(|| BuiltinView {
9439        name: "mz_source_statistics_with_history",
9440        schema: MZ_INTERNAL_SCHEMA,
9441        oid: oid::VIEW_MZ_SOURCE_STATISTICS_WITH_HISTORY_OID,
9442        desc: RelationDesc::builder()
9443            .with_column("id", SqlScalarType::String.nullable(false))
9444            .with_column("replica_id", SqlScalarType::String.nullable(true))
9445            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
9446            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
9447            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
9448            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
9449            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
9450            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
9451            .with_column(
9452                "rehydration_latency",
9453                SqlScalarType::Interval.nullable(true),
9454            )
9455            .with_column(
9456                "snapshot_records_known",
9457                SqlScalarType::UInt64.nullable(true),
9458            )
9459            .with_column(
9460                "snapshot_records_staged",
9461                SqlScalarType::UInt64.nullable(true),
9462            )
9463            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
9464            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
9465            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
9466            .with_key(vec![0, 1])
9467            .finish(),
9468        column_comments: BTreeMap::new(),
9469        sql: "
9470WITH
9471    -- For each subsource, statistics are reported as its parent source
9472    subsource_to_parent AS
9473    (
9474        SELECT subsource.id AS id, parent.id AS report_id
9475        FROM mz_catalog.mz_sources AS subsource
9476            JOIN mz_internal.mz_object_dependencies AS dep ON subsource.id = dep.object_id
9477            JOIN mz_catalog.mz_sources AS parent ON parent.id = dep.referenced_object_id
9478        WHERE subsource.type = 'subsource'
9479    ),
9480    -- For each table from source, statistics are reported as its parent source
9481    table_to_parent AS
9482    (
9483        SELECT id, source_id AS report_id
9484        FROM mz_catalog.mz_tables
9485        WHERE source_id IS NOT NULL
9486    ),
9487    -- For each source and subsource, statistics are reported as itself
9488    source_refl AS
9489    (
9490        SELECT id, id AS report_id
9491        FROM mz_catalog.mz_sources
9492        WHERE type NOT IN ('progress', 'log')
9493    ),
9494    -- For each table from source, statistics are reported as itself
9495    table_refl AS
9496    (
9497        SELECT id, id AS report_id
9498        FROM mz_catalog.mz_tables
9499        WHERE source_id IS NOT NULL
9500    ),
9501    report_paths AS
9502    (
9503        SELECT id, report_id FROM subsource_to_parent
9504        UNION ALL SELECT id, report_id FROM table_to_parent
9505        UNION ALL SELECT id, report_id FROM source_refl
9506        UNION ALL SELECT id, report_id FROM table_refl
9507    )
9508SELECT
9509    report_paths.report_id AS id,
9510    replica_id,
9511    -- Counters
9512    SUM(messages_received)::uint8 AS messages_received,
9513    SUM(bytes_received)::uint8 AS bytes_received,
9514    SUM(updates_staged)::uint8 AS updates_staged,
9515    SUM(updates_committed)::uint8 AS updates_committed,
9516    -- Resetting Gauges
9517    SUM(records_indexed)::uint8 AS records_indexed,
9518    SUM(bytes_indexed)::uint8 AS bytes_indexed,
9519    -- Ensure we aggregate to NULL when not all workers are done rehydrating.
9520    CASE
9521        WHEN bool_or(rehydration_latency IS NULL) THEN NULL
9522        ELSE MAX(rehydration_latency)::interval
9523    END AS rehydration_latency,
9524    SUM(snapshot_records_known)::uint8 AS snapshot_records_known,
9525    SUM(snapshot_records_staged)::uint8 AS snapshot_records_staged,
9526    bool_and(snapshot_committed) as snapshot_committed,
9527    -- Gauges
9528    MAX(offset_known)::uint8 AS offset_known,
9529    MIN(offset_committed)::uint8 AS offset_committed
9530FROM mz_internal.mz_source_statistics_raw
9531    JOIN report_paths USING (id)
9532GROUP BY report_paths.report_id, replica_id",
9533        access: vec![PUBLIC_SELECT],
9534        ontology: None,
9535    });
9536
9537pub const MZ_SOURCE_STATISTICS_WITH_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9538    name: "mz_source_statistics_with_history_ind",
9539    schema: MZ_INTERNAL_SCHEMA,
9540    oid: oid::INDEX_MZ_SOURCE_STATISTICS_WITH_HISTORY_IND_OID,
9541    sql: "IN CLUSTER mz_catalog_server
9542ON mz_internal.mz_source_statistics_with_history (id, replica_id)",
9543    is_retained_metrics_object: true,
9544};
9545
9546// The non historical version of MZ_SOURCE_STATISTICS_WITH_HISTORY.
9547// Used to query MZ_SOURCE_STATISTICS at the current time.
9548pub static MZ_SOURCE_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| {
9549    BuiltinView {
9550        name: "mz_source_statistics",
9551        schema: MZ_INTERNAL_SCHEMA,
9552        oid: oid::VIEW_MZ_SOURCE_STATISTICS_OID,
9553        // We need to add a redundant where clause for a new dataflow to be created.
9554        desc: RelationDesc::builder()
9555            .with_column("id", SqlScalarType::String.nullable(false))
9556            .with_column("replica_id", SqlScalarType::String.nullable(true))
9557            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
9558            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
9559            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
9560            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
9561            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
9562            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
9563            .with_column(
9564                "rehydration_latency",
9565                SqlScalarType::Interval.nullable(true),
9566            )
9567            .with_column(
9568                "snapshot_records_known",
9569                SqlScalarType::UInt64.nullable(true),
9570            )
9571            .with_column(
9572                "snapshot_records_staged",
9573                SqlScalarType::UInt64.nullable(true),
9574            )
9575            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
9576            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
9577            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
9578            .with_key(vec![0, 1])
9579            .finish(),
9580        column_comments: BTreeMap::from_iter([
9581            (
9582                "id",
9583                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
9584            ),
9585            (
9586                "replica_id",
9587                "The ID of a replica running the source. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
9588            ),
9589            (
9590                "messages_received",
9591                "The number of messages the source has received from the external system. Messages are counted in a source type-specific manner. Messages do not correspond directly to updates: some messages produce multiple updates, while other messages may be coalesced into a single update.",
9592            ),
9593            (
9594                "bytes_received",
9595                "The number of bytes the source has read from the external system. Bytes are counted in a source type-specific manner and may or may not include protocol overhead.",
9596            ),
9597            (
9598                "updates_staged",
9599                "The number of updates (insertions plus deletions) the source has written but not yet committed to the storage layer.",
9600            ),
9601            (
9602                "updates_committed",
9603                "The number of updates (insertions plus deletions) the source has committed to the storage layer.",
9604            ),
9605            (
9606                "records_indexed",
9607                "The number of individual records indexed in the source envelope state.",
9608            ),
9609            (
9610                "bytes_indexed",
9611                "The number of bytes stored in the source's internal index, if any.",
9612            ),
9613            (
9614                "rehydration_latency",
9615                "The amount of time it took for the source to rehydrate its internal index, if any, after the source last restarted.",
9616            ),
9617            (
9618                "snapshot_records_known",
9619                "The size of the source's snapshot, measured in number of records. See below to learn what constitutes a record.",
9620            ),
9621            (
9622                "snapshot_records_staged",
9623                "The number of records in the source's snapshot that Materialize has read. See below to learn what constitutes a record.",
9624            ),
9625            (
9626                "snapshot_committed",
9627                "Whether the source has committed the initial snapshot for a source.",
9628            ),
9629            (
9630                "offset_known",
9631                "The offset of the most recent data in the source's upstream service that Materialize knows about. See below to learn what constitutes an offset.",
9632            ),
9633            (
9634                "offset_committed",
9635                "The offset of the the data that Materialize has durably ingested. See below to learn what constitutes an offset.",
9636            ),
9637        ]),
9638        sql: "SELECT * FROM mz_internal.mz_source_statistics_with_history WHERE length(id) > 0",
9639        access: vec![PUBLIC_SELECT],
9640        ontology: Some(Ontology {
9641            entity_name: "source_statistics",
9642            description: "Aggregated source ingestion statistics",
9643            links: &const {
9644                [OntologyLink {
9645                    name: "statistics_of_source",
9646                    target: "source",
9647                    properties: LinkProperties::measures("id", "id", "ingestion_statistics"),
9648                }]
9649            },
9650            column_semantic_types: &const {
9651                [
9652                    ("id", SemanticType::CatalogItemId),
9653                    ("replica_id", SemanticType::ReplicaId),
9654                    ("messages_received", SemanticType::RecordCount),
9655                    ("bytes_received", SemanticType::ByteCount),
9656                    ("updates_staged", SemanticType::RecordCount),
9657                    ("updates_committed", SemanticType::RecordCount),
9658                    ("records_indexed", SemanticType::RecordCount),
9659                    ("bytes_indexed", SemanticType::ByteCount),
9660                    ("snapshot_records_known", SemanticType::RecordCount),
9661                    ("snapshot_records_staged", SemanticType::RecordCount),
9662                ]
9663            },
9664        }),
9665    }
9666});
9667
9668pub const MZ_SOURCE_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
9669    name: "mz_source_statistics_ind",
9670    schema: MZ_INTERNAL_SCHEMA,
9671    oid: oid::INDEX_MZ_SOURCE_STATISTICS_IND_OID,
9672    sql: "IN CLUSTER mz_catalog_server
9673ON mz_internal.mz_source_statistics (id, replica_id)",
9674    is_retained_metrics_object: false,
9675};
9676
9677pub static MZ_SINK_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9678    name: "mz_sink_statistics",
9679    schema: MZ_INTERNAL_SCHEMA,
9680    oid: oid::VIEW_MZ_SINK_STATISTICS_OID,
9681    desc: RelationDesc::builder()
9682        .with_column("id", SqlScalarType::String.nullable(false))
9683        .with_column("replica_id", SqlScalarType::String.nullable(true))
9684        .with_column("messages_staged", SqlScalarType::UInt64.nullable(false))
9685        .with_column("messages_committed", SqlScalarType::UInt64.nullable(false))
9686        .with_column("bytes_staged", SqlScalarType::UInt64.nullable(false))
9687        .with_column("bytes_committed", SqlScalarType::UInt64.nullable(false))
9688        .with_key(vec![0, 1])
9689        .finish(),
9690    column_comments: BTreeMap::from_iter([
9691        (
9692            "id",
9693            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
9694        ),
9695        (
9696            "replica_id",
9697            "The ID of a replica running the sink. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
9698        ),
9699        (
9700            "messages_staged",
9701            "The number of messages staged but possibly not committed to the sink.",
9702        ),
9703        (
9704            "messages_committed",
9705            "The number of messages committed to the sink.",
9706        ),
9707        (
9708            "bytes_staged",
9709            "The number of bytes staged but possibly not committed to the sink. This counts both keys and values, if applicable.",
9710        ),
9711        (
9712            "bytes_committed",
9713            "The number of bytes committed to the sink. This counts both keys and values, if applicable.",
9714        ),
9715    ]),
9716    sql: "
9717SELECT
9718    id,
9719    replica_id,
9720    SUM(messages_staged)::uint8 AS messages_staged,
9721    SUM(messages_committed)::uint8 AS messages_committed,
9722    SUM(bytes_staged)::uint8 AS bytes_staged,
9723    SUM(bytes_committed)::uint8 AS bytes_committed
9724FROM mz_internal.mz_sink_statistics_raw
9725GROUP BY id, replica_id",
9726    access: vec![PUBLIC_SELECT],
9727    ontology: Some(Ontology {
9728        entity_name: "sink_statistics",
9729        description: "Aggregated sink export statistics",
9730        links: &const {
9731            [OntologyLink {
9732                name: "statistics_of_sink",
9733                target: "sink",
9734                properties: LinkProperties::measures("id", "id", "export_statistics"),
9735            }]
9736        },
9737        column_semantic_types: &const {
9738            [
9739                ("id", SemanticType::CatalogItemId),
9740                ("replica_id", SemanticType::ReplicaId),
9741                ("messages_staged", SemanticType::RecordCount),
9742                ("messages_committed", SemanticType::RecordCount),
9743                ("bytes_staged", SemanticType::ByteCount),
9744                ("bytes_committed", SemanticType::ByteCount),
9745            ]
9746        },
9747    }),
9748});
9749
9750pub const MZ_SINK_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
9751    name: "mz_sink_statistics_ind",
9752    schema: MZ_INTERNAL_SCHEMA,
9753    oid: oid::INDEX_MZ_SINK_STATISTICS_IND_OID,
9754    sql: "IN CLUSTER mz_catalog_server
9755ON mz_internal.mz_sink_statistics (id, replica_id)",
9756    is_retained_metrics_object: true,
9757};
9758
9759pub const MZ_CLUSTER_REPLICA_STATUSES_IND: BuiltinIndex = BuiltinIndex {
9760    name: "mz_cluster_replica_statuses_ind",
9761    schema: MZ_INTERNAL_SCHEMA,
9762    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUSES_IND_OID,
9763    sql: "IN CLUSTER mz_catalog_server
9764ON mz_internal.mz_cluster_replica_statuses (replica_id)",
9765    is_retained_metrics_object: false,
9766};
9767
9768pub const MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9769    name: "mz_cluster_replica_status_history_ind",
9770    schema: MZ_INTERNAL_SCHEMA,
9771    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND_OID,
9772    sql: "IN CLUSTER mz_catalog_server
9773ON mz_internal.mz_cluster_replica_status_history (replica_id)",
9774    is_retained_metrics_object: false,
9775};
9776
9777pub const MZ_CLUSTER_REPLICA_METRICS_IND: BuiltinIndex = BuiltinIndex {
9778    name: "mz_cluster_replica_metrics_ind",
9779    schema: MZ_INTERNAL_SCHEMA,
9780    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_IND_OID,
9781    sql: "IN CLUSTER mz_catalog_server
9782ON mz_internal.mz_cluster_replica_metrics (replica_id)",
9783    is_retained_metrics_object: false,
9784};
9785
9786pub const MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9787    name: "mz_cluster_replica_metrics_history_ind",
9788    schema: MZ_INTERNAL_SCHEMA,
9789    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND_OID,
9790    sql: "IN CLUSTER mz_catalog_server
9791ON mz_internal.mz_cluster_replica_metrics_history (replica_id)",
9792    is_retained_metrics_object: false,
9793};
9794
9795pub const MZ_CLUSTER_REPLICA_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9796    name: "mz_cluster_replica_history_ind",
9797    schema: MZ_INTERNAL_SCHEMA,
9798    oid: oid::INDEX_MZ_CLUSTER_REPLICA_HISTORY_IND_OID,
9799    sql: "IN CLUSTER mz_catalog_server
9800ON mz_internal.mz_cluster_replica_history (dropped_at)",
9801    is_retained_metrics_object: true,
9802};
9803
9804pub const MZ_CLUSTER_REPLICA_NAME_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9805    name: "mz_cluster_replica_name_history_ind",
9806    schema: MZ_INTERNAL_SCHEMA,
9807    oid: oid::INDEX_MZ_CLUSTER_REPLICA_NAME_HISTORY_IND_OID,
9808    sql: "IN CLUSTER mz_catalog_server
9809ON mz_internal.mz_cluster_replica_name_history (id)",
9810    is_retained_metrics_object: false,
9811};
9812
9813pub const MZ_OBJECT_LIFETIMES_IND: BuiltinIndex = BuiltinIndex {
9814    name: "mz_object_lifetimes_ind",
9815    schema: MZ_INTERNAL_SCHEMA,
9816    oid: oid::INDEX_MZ_OBJECT_LIFETIMES_IND_OID,
9817    sql: "IN CLUSTER mz_catalog_server
9818ON mz_internal.mz_object_lifetimes (id)",
9819    is_retained_metrics_object: false,
9820};
9821
9822pub const MZ_OBJECT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9823    name: "mz_object_history_ind",
9824    schema: MZ_INTERNAL_SCHEMA,
9825    oid: oid::INDEX_MZ_OBJECT_HISTORY_IND_OID,
9826    sql: "IN CLUSTER mz_catalog_server
9827ON mz_internal.mz_object_history (id)",
9828    is_retained_metrics_object: false,
9829};
9830
9831pub const MZ_OBJECT_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
9832    name: "mz_object_dependencies_ind",
9833    schema: MZ_INTERNAL_SCHEMA,
9834    oid: oid::INDEX_MZ_OBJECT_DEPENDENCIES_IND_OID,
9835    sql: "IN CLUSTER mz_catalog_server
9836ON mz_internal.mz_object_dependencies (object_id)",
9837    is_retained_metrics_object: true,
9838};
9839
9840pub const MZ_COMPUTE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
9841    name: "mz_compute_dependencies_ind",
9842    schema: MZ_INTERNAL_SCHEMA,
9843    oid: oid::INDEX_MZ_COMPUTE_DEPENDENCIES_IND_OID,
9844    sql: "IN CLUSTER mz_catalog_server
9845ON mz_internal.mz_compute_dependencies (dependency_id)",
9846    is_retained_metrics_object: false,
9847};
9848
9849pub const MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
9850    name: "mz_object_transitive_dependencies_ind",
9851    schema: MZ_INTERNAL_SCHEMA,
9852    oid: oid::INDEX_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND_OID,
9853    sql: "IN CLUSTER mz_catalog_server
9854ON mz_internal.mz_object_transitive_dependencies (object_id)",
9855    is_retained_metrics_object: false,
9856};
9857
9858pub const MZ_OBJECT_GRAPH_EDGES_IND: BuiltinIndex = BuiltinIndex {
9859    name: "mz_object_graph_edges_ind",
9860    schema: MZ_INTERNAL_SCHEMA,
9861    oid: oid::INDEX_MZ_OBJECT_GRAPH_EDGES_IND_OID,
9862    sql: "IN CLUSTER mz_catalog_server
9863ON mz_internal.mz_object_graph_edges (object_id)",
9864    is_retained_metrics_object: false,
9865};
9866
9867pub const MZ_FRONTIERS_IND: BuiltinIndex = BuiltinIndex {
9868    name: "mz_frontiers_ind",
9869    schema: MZ_INTERNAL_SCHEMA,
9870    oid: oid::INDEX_MZ_FRONTIERS_IND_OID,
9871    sql: "IN CLUSTER mz_catalog_server
9872ON mz_internal.mz_frontiers (object_id)",
9873    is_retained_metrics_object: false,
9874};
9875
9876pub const MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
9877    name: "mz_wallclock_global_lag_recent_history_ind",
9878    schema: MZ_INTERNAL_SCHEMA,
9879    oid: oid::INDEX_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND_OID,
9880    sql: "IN CLUSTER mz_catalog_server
9881ON mz_internal.mz_wallclock_global_lag_recent_history (object_id)",
9882    is_retained_metrics_object: false,
9883};
9884
9885pub const MZ_RECENT_ACTIVITY_LOG_THINNED_IND: BuiltinIndex = BuiltinIndex {
9886    name: "mz_recent_activity_log_thinned_ind",
9887    schema: MZ_INTERNAL_SCHEMA,
9888    oid: oid::INDEX_MZ_RECENT_ACTIVITY_LOG_THINNED_IND_OID,
9889    sql: "IN CLUSTER mz_catalog_server
9890-- sql_hash because we plan to join
9891-- this against mz_internal.mz_sql_text
9892ON mz_internal.mz_recent_activity_log_thinned (sql_hash)",
9893    is_retained_metrics_object: false,
9894};
9895
9896pub const MZ_WEBHOOK_SOURCES_IND: BuiltinIndex = BuiltinIndex {
9897    name: "mz_webhook_sources_ind",
9898    schema: MZ_INTERNAL_SCHEMA,
9899    oid: oid::INDEX_MZ_WEBHOOK_SOURCES_IND_OID,
9900    sql: "IN CLUSTER mz_catalog_server
9901ON mz_internal.mz_webhook_sources (id)",
9902    is_retained_metrics_object: true,
9903};
9904
9905pub const MZ_COMMENTS_IND: BuiltinIndex = BuiltinIndex {
9906    name: "mz_comments_ind",
9907    schema: MZ_INTERNAL_SCHEMA,
9908    oid: oid::INDEX_MZ_COMMENTS_IND_OID,
9909    sql: "IN CLUSTER mz_catalog_server
9910ON mz_internal.mz_comments (id)",
9911    is_retained_metrics_object: true,
9912};
9913
9914pub static MZ_ANALYTICS: BuiltinConnection = BuiltinConnection {
9915    name: "mz_analytics",
9916    schema: MZ_INTERNAL_SCHEMA,
9917    oid: oid::CONNECTION_MZ_ANALYTICS_OID,
9918    sql: "CREATE CONNECTION mz_internal.mz_analytics TO AWS (ASSUME ROLE ARN = '')",
9919    access: &[MzAclItem {
9920        grantee: MZ_SYSTEM_ROLE_ID,
9921        grantor: MZ_ANALYTICS_ROLE_ID,
9922        acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Connection)),
9923    }],
9924    owner_id: &MZ_ANALYTICS_ROLE_ID,
9925    runtime_alterable: true,
9926};