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