Skip to main content

mz_catalog/
builtin.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.
11//!
12//! Builtins exist in the `mz_catalog` ambient schema. They are automatically
13//! installed into the catalog when it is opened. Their definitions are not
14//! persisted in the catalog, but hardcoded in this module. This makes it easy
15//! to add new builtins, or change the definition of existing builtins, in new
16//! versions of Materialize.
17//!
18//! Builtin's names, columns, and types are part of the stable API of
19//! Materialize. Be careful to maintain backwards compatibility when changing
20//! definitions of existing builtins!
21//!
22//! More information about builtin system tables and types can be found in
23//! <https://materialize.com/docs/sql/system-catalog/>.
24
25mod builtin;
26pub mod notice;
27
28use std::collections::BTreeMap;
29use std::hash::Hash;
30use std::string::ToString;
31use std::sync::LazyLock;
32
33use mz_compute_client::logging::{ComputeLog, DifferentialLog, LogVariant, TimelyLog};
34use mz_ore::collections::HashMap;
35use mz_pgrepr::oid;
36use mz_repr::adt::mz_acl_item::{AclMode, MzAclItem};
37use mz_repr::adt::numeric::NumericMaxScale;
38use mz_repr::namespaces::{
39    INFORMATION_SCHEMA, MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA, MZ_INTROSPECTION_SCHEMA,
40    MZ_UNSAFE_SCHEMA, PG_CATALOG_SCHEMA,
41};
42use mz_repr::role_id::RoleId;
43use mz_repr::{RelationDesc, SqlRelationType, SqlScalarType};
44use mz_sql::catalog::RoleAttributesRaw;
45use mz_sql::catalog::{
46    CatalogItemType, CatalogType, CatalogTypeDetails, CatalogTypePgMetadata, NameReference,
47    ObjectType, SystemObjectType, TypeReference,
48};
49use mz_sql::rbac;
50use mz_sql::session::user::{
51    ANALYTICS_USER_NAME, MZ_ANALYTICS_ROLE_ID, MZ_MONITOR_REDACTED_ROLE_ID, MZ_MONITOR_ROLE_ID,
52    MZ_SUPPORT_ROLE_ID, MZ_SYSTEM_ROLE_ID, SUPPORT_USER_NAME, SYSTEM_USER_NAME,
53};
54use mz_storage_client::controller::IntrospectionType;
55use mz_storage_client::healthcheck::WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC;
56use mz_storage_client::healthcheck::{
57    MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC, MZ_PREPARED_STATEMENT_HISTORY_DESC,
58    MZ_SESSION_HISTORY_DESC, MZ_SINK_STATUS_HISTORY_DESC, MZ_SOURCE_STATUS_HISTORY_DESC,
59    MZ_SQL_TEXT_DESC, MZ_STATEMENT_EXECUTION_HISTORY_DESC, REPLICA_METRICS_HISTORY_DESC,
60    REPLICA_STATUS_HISTORY_DESC, WALLCLOCK_LAG_HISTORY_DESC,
61};
62use mz_storage_client::statistics::{MZ_SINK_STATISTICS_RAW_DESC, MZ_SOURCE_STATISTICS_RAW_DESC};
63use serde::Serialize;
64
65use crate::durable::objects::SystemObjectDescription;
66use crate::memory::objects::DataSourceDesc;
67
68pub const BUILTIN_PREFIXES: &[&str] = &["mz_", "pg_", "external_"];
69const BUILTIN_CLUSTER_REPLICA_NAME: &str = "r1";
70
71/// A sentinel used in place of a fingerprint that indicates that a builtin
72/// object is runtime alterable. Runtime alterable objects don't have meaningful
73/// fingerprints because they may have been intentionally changed by the user
74/// after creation.
75// NOTE(benesch): ideally we'd use a fingerprint type that used a sum type
76// rather than a loosely typed string to represent the runtime alterable
77// state like so:
78//
79//     enum Fingerprint {
80//         SqlText(String),
81//         RuntimeAlterable,
82//     }
83//
84// However, that would entail a complicated migration for the existing system object
85// mapping collection stored on disk.
86pub const RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL: &str = "<RUNTIME-ALTERABLE>";
87
88#[derive(Clone, Debug)]
89pub enum Builtin<T: 'static + TypeReference> {
90    Log(&'static BuiltinLog),
91    Table(&'static BuiltinTable),
92    View(&'static BuiltinView),
93    MaterializedView(&'static BuiltinMaterializedView),
94    Type(&'static BuiltinType<T>),
95    Func(BuiltinFunc),
96    Source(&'static BuiltinSource),
97    ContinualTask(&'static BuiltinContinualTask),
98    Index(&'static BuiltinIndex),
99    Connection(&'static BuiltinConnection),
100}
101
102impl<T: TypeReference> Builtin<T> {
103    pub fn name(&self) -> &'static str {
104        match self {
105            Builtin::Log(log) => log.name,
106            Builtin::Table(table) => table.name,
107            Builtin::View(view) => view.name,
108            Builtin::MaterializedView(mv) => mv.name,
109            Builtin::Type(typ) => typ.name,
110            Builtin::Func(func) => func.name,
111            Builtin::Source(coll) => coll.name,
112            Builtin::ContinualTask(ct) => ct.name,
113            Builtin::Index(index) => index.name,
114            Builtin::Connection(connection) => connection.name,
115        }
116    }
117
118    pub fn schema(&self) -> &'static str {
119        match self {
120            Builtin::Log(log) => log.schema,
121            Builtin::Table(table) => table.schema,
122            Builtin::View(view) => view.schema,
123            Builtin::MaterializedView(mv) => mv.schema,
124            Builtin::Type(typ) => typ.schema,
125            Builtin::Func(func) => func.schema,
126            Builtin::Source(coll) => coll.schema,
127            Builtin::ContinualTask(ct) => ct.schema,
128            Builtin::Index(index) => index.schema,
129            Builtin::Connection(connection) => connection.schema,
130        }
131    }
132
133    pub fn catalog_item_type(&self) -> CatalogItemType {
134        match self {
135            Builtin::Log(_) => CatalogItemType::Source,
136            Builtin::Source(_) => CatalogItemType::Source,
137            Builtin::ContinualTask(_) => CatalogItemType::ContinualTask,
138            Builtin::Table(_) => CatalogItemType::Table,
139            Builtin::View(_) => CatalogItemType::View,
140            Builtin::MaterializedView(_) => CatalogItemType::MaterializedView,
141            Builtin::Type(_) => CatalogItemType::Type,
142            Builtin::Func(_) => CatalogItemType::Func,
143            Builtin::Index(_) => CatalogItemType::Index,
144            Builtin::Connection(_) => CatalogItemType::Connection,
145        }
146    }
147
148    /// Whether the object can be altered at runtime by its owner.
149    pub fn runtime_alterable(&self) -> bool {
150        match self {
151            Builtin::Connection(c) => c.runtime_alterable,
152            _ => false,
153        }
154    }
155}
156
157#[derive(Clone, Debug, Hash, Serialize)]
158pub struct BuiltinLog {
159    pub variant: LogVariant,
160    pub name: &'static str,
161    pub schema: &'static str,
162    pub oid: u32,
163    /// ACL items to apply to the object
164    pub access: Vec<MzAclItem>,
165}
166
167#[derive(Clone, Hash, Debug, PartialEq, Eq)]
168pub struct BuiltinTable {
169    pub name: &'static str,
170    pub schema: &'static str,
171    pub oid: u32,
172    pub desc: RelationDesc,
173    pub column_comments: BTreeMap<&'static str, &'static str>,
174    /// Whether the table's retention policy is controlled by
175    /// the system variable `METRICS_RETENTION`
176    pub is_retained_metrics_object: bool,
177    /// ACL items to apply to the object
178    pub access: Vec<MzAclItem>,
179}
180
181#[derive(Clone, Debug, PartialEq, Eq)]
182pub struct BuiltinSource {
183    pub name: &'static str,
184    pub schema: &'static str,
185    pub oid: u32,
186    pub desc: RelationDesc,
187    pub column_comments: BTreeMap<&'static str, &'static str>,
188    pub data_source: DataSourceDesc,
189    /// Whether the source's retention policy is controlled by
190    /// the system variable `METRICS_RETENTION`
191    pub is_retained_metrics_object: bool,
192    /// ACL items to apply to the object
193    pub access: Vec<MzAclItem>,
194}
195
196#[derive(Hash, Debug, PartialEq, Eq)]
197pub struct BuiltinContinualTask {
198    pub name: &'static str,
199    pub schema: &'static str,
200    pub oid: u32,
201    pub desc: RelationDesc,
202    pub sql: &'static str,
203    /// ACL items to apply to the object
204    pub access: Vec<MzAclItem>,
205}
206
207#[derive(Hash, Debug)]
208pub struct BuiltinView {
209    pub name: &'static str,
210    pub schema: &'static str,
211    pub oid: u32,
212    pub desc: RelationDesc,
213    pub column_comments: BTreeMap<&'static str, &'static str>,
214    pub sql: &'static str,
215    /// ACL items to apply to the object
216    pub access: Vec<MzAclItem>,
217}
218
219impl BuiltinView {
220    pub fn create_sql(&self) -> String {
221        format!("CREATE VIEW {}.{} AS {}", self.schema, self.name, self.sql)
222    }
223}
224
225#[derive(Hash, Debug)]
226pub struct BuiltinMaterializedView {
227    pub name: &'static str,
228    pub schema: &'static str,
229    pub oid: u32,
230    pub desc: RelationDesc,
231    pub column_comments: BTreeMap<&'static str, &'static str>,
232    /// SQL fragment for the MV, following `CREATE MATERIALIZED VIEW [name]`
233    ///
234    /// Format: `IN CLUSTER [cluster_name] AS [query]`
235    pub sql: &'static str,
236    /// Whether the MV's retention policy is controlled by
237    /// the system variable `METRICS_RETENTION`
238    pub is_retained_metrics_object: bool,
239    /// ACL items to apply to the object
240    pub access: Vec<MzAclItem>,
241}
242
243impl BuiltinMaterializedView {
244    pub fn create_sql(&self) -> String {
245        format!(
246            "CREATE MATERIALIZED VIEW {}.{} {}",
247            self.schema, self.name, self.sql
248        )
249    }
250}
251
252#[derive(Debug)]
253pub struct BuiltinType<T: TypeReference> {
254    pub name: &'static str,
255    pub schema: &'static str,
256    pub oid: u32,
257    pub details: CatalogTypeDetails<T>,
258}
259
260#[derive(Clone, Debug)]
261pub struct BuiltinFunc {
262    pub schema: &'static str,
263    pub name: &'static str,
264    pub inner: &'static mz_sql::func::Func,
265}
266
267/// Note: When creating a built-in index, it's usually best to choose a key that has only one
268/// component. For example, if you created an index
269/// `ON mz_internal.mz_object_lifetimes (id, object_type)`, then this index couldn't be used for a
270/// lookup for `WHERE object_type = ...`, and neither for joins keyed on just `id`.
271/// See <https://materialize.com/docs/transform-data/optimization/#matching-multi-column-indexes-to-multi-column-where-clauses>
272#[derive(Debug)]
273pub struct BuiltinIndex {
274    pub name: &'static str,
275    pub schema: &'static str,
276    pub oid: u32,
277    /// SQL fragment for the index, following `CREATE INDEX [name]`
278    ///
279    /// Format: `IN CLUSTER [cluster_name] ON [table_name] ([column_exprs])`
280    pub sql: &'static str,
281    pub is_retained_metrics_object: bool,
282}
283
284impl BuiltinIndex {
285    pub fn create_sql(&self) -> String {
286        format!("CREATE INDEX {}\n{}", self.name, self.sql)
287    }
288}
289
290impl BuiltinContinualTask {
291    pub fn create_sql(&self) -> String {
292        format!(
293            "CREATE CONTINUAL TASK {}.{}\n{}",
294            self.schema, self.name, self.sql
295        )
296    }
297}
298
299#[derive(Hash, Debug)]
300pub struct BuiltinConnection {
301    pub name: &'static str,
302    pub schema: &'static str,
303    pub oid: u32,
304    pub sql: &'static str,
305    pub access: &'static [MzAclItem],
306    pub owner_id: &'static RoleId,
307    /// Whether the object can be altered at runtime by its owner.
308    ///
309    /// Note that when `runtime_alterable` is true, changing the `sql` in future
310    /// versions does not trigger a migration.
311    pub runtime_alterable: bool,
312}
313
314#[derive(Clone, Debug)]
315pub struct BuiltinRole {
316    pub id: RoleId,
317    /// Name of the builtin role.
318    ///
319    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
320    pub name: &'static str,
321    pub oid: u32,
322    pub attributes: RoleAttributesRaw,
323}
324
325#[derive(Clone, Debug)]
326pub struct BuiltinCluster {
327    /// Name of the cluster.
328    ///
329    /// IMPORTANT: Must start with a prefix from [`BUILTIN_PREFIXES`].
330    pub name: &'static str,
331    pub privileges: &'static [MzAclItem],
332    pub owner_id: &'static RoleId,
333}
334
335#[derive(Clone, Debug, PartialEq, Eq)]
336pub struct BuiltinClusterReplica {
337    /// Name of the compute replica.
338    pub name: &'static str,
339    /// Name of the cluster that this replica belongs to.
340    pub cluster_name: &'static str,
341}
342
343/// Uniquely identifies the definition of a builtin object.
344pub trait Fingerprint {
345    fn fingerprint(&self) -> String;
346}
347
348impl<T: TypeReference> Fingerprint for &Builtin<T> {
349    fn fingerprint(&self) -> String {
350        match self {
351            Builtin::Log(log) => log.fingerprint(),
352            Builtin::Table(table) => table.fingerprint(),
353            Builtin::View(view) => view.fingerprint(),
354            Builtin::MaterializedView(mv) => mv.fingerprint(),
355            Builtin::Type(typ) => typ.fingerprint(),
356            Builtin::Func(func) => func.fingerprint(),
357            Builtin::Source(coll) => coll.fingerprint(),
358            Builtin::ContinualTask(ct) => ct.fingerprint(),
359            Builtin::Index(index) => index.fingerprint(),
360            Builtin::Connection(connection) => connection.fingerprint(),
361        }
362    }
363}
364
365// Types and Funcs never change fingerprints so we just return constant 0
366impl<T: TypeReference> Fingerprint for &BuiltinType<T> {
367    fn fingerprint(&self) -> String {
368        "".to_string()
369    }
370}
371
372impl Fingerprint for &BuiltinFunc {
373    fn fingerprint(&self) -> String {
374        "".to_string()
375    }
376}
377
378impl Fingerprint for &BuiltinLog {
379    fn fingerprint(&self) -> String {
380        self.variant.desc().fingerprint()
381    }
382}
383
384impl Fingerprint for &BuiltinTable {
385    fn fingerprint(&self) -> String {
386        self.desc.fingerprint()
387    }
388}
389
390impl Fingerprint for &BuiltinView {
391    fn fingerprint(&self) -> String {
392        self.sql.to_string()
393    }
394}
395
396impl Fingerprint for &BuiltinSource {
397    fn fingerprint(&self) -> String {
398        self.desc.fingerprint()
399    }
400}
401
402impl Fingerprint for &BuiltinMaterializedView {
403    fn fingerprint(&self) -> String {
404        self.create_sql()
405    }
406}
407
408impl Fingerprint for &BuiltinContinualTask {
409    fn fingerprint(&self) -> String {
410        self.create_sql()
411    }
412}
413
414impl Fingerprint for &BuiltinIndex {
415    fn fingerprint(&self) -> String {
416        self.create_sql()
417    }
418}
419
420impl Fingerprint for &BuiltinConnection {
421    fn fingerprint(&self) -> String {
422        self.sql.to_string()
423    }
424}
425
426impl Fingerprint for RelationDesc {
427    fn fingerprint(&self) -> String {
428        self.typ().fingerprint()
429    }
430}
431
432impl Fingerprint for SqlRelationType {
433    fn fingerprint(&self) -> String {
434        serde_json::to_string(self).expect("serialization cannot fail")
435    }
436}
437
438// Builtin definitions below. Ensure you add new builtins to the `BUILTINS` map.
439//
440// You SHOULD NOT delete a builtin. If you do, you will break any downstream
441// user objects that depended on the builtin.
442//
443// Builtins are loaded in dependency order, so a builtin must appear in `BUILTINS`
444// before any items it depends upon.
445//
446// WARNING: if you change the definition of an existing builtin item, you must
447// be careful to maintain backwards compatibility! Adding new columns is safe.
448// Removing a column, changing the name of a column, or changing the type of a
449// column is not safe, as persisted user views may depend upon that column.
450
451// The following types are the list of builtin data types available
452// in Materialize. This list is derived from the `pg_type` table in PostgreSQL.
453//
454// Builtin types cannot be created, updated, or deleted. Their OIDs
455// are static, unlike other objects, to match the type OIDs defined by Postgres.
456
457pub const TYPE_BOOL: BuiltinType<NameReference> = BuiltinType {
458    name: "bool",
459    schema: PG_CATALOG_SCHEMA,
460    oid: oid::TYPE_BOOL_OID,
461    details: CatalogTypeDetails {
462        typ: CatalogType::Bool,
463        array_id: None,
464        pg_metadata: Some(CatalogTypePgMetadata {
465            typinput_oid: 1242,
466            typreceive_oid: 2436,
467        }),
468    },
469};
470
471pub const TYPE_BYTEA: BuiltinType<NameReference> = BuiltinType {
472    name: "bytea",
473    schema: PG_CATALOG_SCHEMA,
474    oid: oid::TYPE_BYTEA_OID,
475    details: CatalogTypeDetails {
476        typ: CatalogType::Bytes,
477        array_id: None,
478        pg_metadata: Some(CatalogTypePgMetadata {
479            typinput_oid: 1244,
480            typreceive_oid: 2412,
481        }),
482    },
483};
484
485pub const TYPE_INT8: BuiltinType<NameReference> = BuiltinType {
486    name: "int8",
487    schema: PG_CATALOG_SCHEMA,
488    oid: oid::TYPE_INT8_OID,
489    details: CatalogTypeDetails {
490        typ: CatalogType::Int64,
491        array_id: None,
492        pg_metadata: Some(CatalogTypePgMetadata {
493            typinput_oid: 460,
494            typreceive_oid: 2408,
495        }),
496    },
497};
498
499pub const TYPE_INT4: BuiltinType<NameReference> = BuiltinType {
500    name: "int4",
501    schema: PG_CATALOG_SCHEMA,
502    oid: oid::TYPE_INT4_OID,
503    details: CatalogTypeDetails {
504        typ: CatalogType::Int32,
505        array_id: None,
506        pg_metadata: Some(CatalogTypePgMetadata {
507            typinput_oid: 42,
508            typreceive_oid: 2406,
509        }),
510    },
511};
512
513pub const TYPE_TEXT: BuiltinType<NameReference> = BuiltinType {
514    name: "text",
515    schema: PG_CATALOG_SCHEMA,
516    oid: oid::TYPE_TEXT_OID,
517    details: CatalogTypeDetails {
518        typ: CatalogType::String,
519        array_id: None,
520        pg_metadata: Some(CatalogTypePgMetadata {
521            typinput_oid: 46,
522            typreceive_oid: 2414,
523        }),
524    },
525};
526
527pub const TYPE_OID: BuiltinType<NameReference> = BuiltinType {
528    name: "oid",
529    schema: PG_CATALOG_SCHEMA,
530    oid: oid::TYPE_OID_OID,
531    details: CatalogTypeDetails {
532        typ: CatalogType::Oid,
533        array_id: None,
534        pg_metadata: Some(CatalogTypePgMetadata {
535            typinput_oid: 1798,
536            typreceive_oid: 2418,
537        }),
538    },
539};
540
541pub const TYPE_FLOAT4: BuiltinType<NameReference> = BuiltinType {
542    name: "float4",
543    schema: PG_CATALOG_SCHEMA,
544    oid: oid::TYPE_FLOAT4_OID,
545    details: CatalogTypeDetails {
546        typ: CatalogType::Float32,
547        array_id: None,
548        pg_metadata: Some(CatalogTypePgMetadata {
549            typinput_oid: 200,
550            typreceive_oid: 2424,
551        }),
552    },
553};
554
555pub const TYPE_FLOAT8: BuiltinType<NameReference> = BuiltinType {
556    name: "float8",
557    schema: PG_CATALOG_SCHEMA,
558    oid: oid::TYPE_FLOAT8_OID,
559    details: CatalogTypeDetails {
560        typ: CatalogType::Float64,
561        array_id: None,
562        pg_metadata: Some(CatalogTypePgMetadata {
563            typinput_oid: 214,
564            typreceive_oid: 2426,
565        }),
566    },
567};
568
569pub const TYPE_BOOL_ARRAY: BuiltinType<NameReference> = BuiltinType {
570    name: "_bool",
571    schema: PG_CATALOG_SCHEMA,
572    oid: oid::TYPE_BOOL_ARRAY_OID,
573    details: CatalogTypeDetails {
574        typ: CatalogType::Array {
575            element_reference: TYPE_BOOL.name,
576        },
577        array_id: None,
578        pg_metadata: Some(CatalogTypePgMetadata {
579            typinput_oid: 750,
580            typreceive_oid: 2400,
581        }),
582    },
583};
584
585pub const TYPE_BYTEA_ARRAY: BuiltinType<NameReference> = BuiltinType {
586    name: "_bytea",
587    schema: PG_CATALOG_SCHEMA,
588    oid: oid::TYPE_BYTEA_ARRAY_OID,
589    details: CatalogTypeDetails {
590        typ: CatalogType::Array {
591            element_reference: TYPE_BYTEA.name,
592        },
593        array_id: None,
594        pg_metadata: Some(CatalogTypePgMetadata {
595            typinput_oid: 750,
596            typreceive_oid: 2400,
597        }),
598    },
599};
600
601pub const TYPE_INT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
602    name: "_int4",
603    schema: PG_CATALOG_SCHEMA,
604    oid: oid::TYPE_INT4_ARRAY_OID,
605    details: CatalogTypeDetails {
606        typ: CatalogType::Array {
607            element_reference: TYPE_INT4.name,
608        },
609        array_id: None,
610        pg_metadata: Some(CatalogTypePgMetadata {
611            typinput_oid: 750,
612            typreceive_oid: 2400,
613        }),
614    },
615};
616
617pub const TYPE_TEXT_ARRAY: BuiltinType<NameReference> = BuiltinType {
618    name: "_text",
619    schema: PG_CATALOG_SCHEMA,
620    oid: oid::TYPE_TEXT_ARRAY_OID,
621    details: CatalogTypeDetails {
622        typ: CatalogType::Array {
623            element_reference: TYPE_TEXT.name,
624        },
625        array_id: None,
626        pg_metadata: Some(CatalogTypePgMetadata {
627            typinput_oid: 750,
628            typreceive_oid: 2400,
629        }),
630    },
631};
632
633pub const TYPE_INT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
634    name: "_int8",
635    schema: PG_CATALOG_SCHEMA,
636    oid: oid::TYPE_INT8_ARRAY_OID,
637    details: CatalogTypeDetails {
638        typ: CatalogType::Array {
639            element_reference: TYPE_INT8.name,
640        },
641        array_id: None,
642        pg_metadata: Some(CatalogTypePgMetadata {
643            typinput_oid: 750,
644            typreceive_oid: 2400,
645        }),
646    },
647};
648
649pub const TYPE_FLOAT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
650    name: "_float4",
651    schema: PG_CATALOG_SCHEMA,
652    oid: oid::TYPE_FLOAT4_ARRAY_OID,
653    details: CatalogTypeDetails {
654        typ: CatalogType::Array {
655            element_reference: TYPE_FLOAT4.name,
656        },
657        array_id: None,
658        pg_metadata: Some(CatalogTypePgMetadata {
659            typinput_oid: 750,
660            typreceive_oid: 2400,
661        }),
662    },
663};
664
665pub const TYPE_FLOAT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
666    name: "_float8",
667    schema: PG_CATALOG_SCHEMA,
668    oid: oid::TYPE_FLOAT8_ARRAY_OID,
669    details: CatalogTypeDetails {
670        typ: CatalogType::Array {
671            element_reference: TYPE_FLOAT8.name,
672        },
673        array_id: None,
674        pg_metadata: Some(CatalogTypePgMetadata {
675            typinput_oid: 750,
676            typreceive_oid: 2400,
677        }),
678    },
679};
680
681pub const TYPE_OID_ARRAY: BuiltinType<NameReference> = BuiltinType {
682    name: "_oid",
683    schema: PG_CATALOG_SCHEMA,
684    oid: oid::TYPE_OID_ARRAY_OID,
685    details: CatalogTypeDetails {
686        typ: CatalogType::Array {
687            element_reference: TYPE_OID.name,
688        },
689        array_id: None,
690        pg_metadata: Some(CatalogTypePgMetadata {
691            typinput_oid: 750,
692            typreceive_oid: 2400,
693        }),
694    },
695};
696
697pub const TYPE_DATE: BuiltinType<NameReference> = BuiltinType {
698    name: "date",
699    schema: PG_CATALOG_SCHEMA,
700    oid: oid::TYPE_DATE_OID,
701    details: CatalogTypeDetails {
702        typ: CatalogType::Date,
703        array_id: None,
704        pg_metadata: Some(CatalogTypePgMetadata {
705            typinput_oid: 1084,
706            typreceive_oid: 2468,
707        }),
708    },
709};
710
711pub const TYPE_TIME: BuiltinType<NameReference> = BuiltinType {
712    name: "time",
713    schema: PG_CATALOG_SCHEMA,
714    oid: oid::TYPE_TIME_OID,
715    details: CatalogTypeDetails {
716        typ: CatalogType::Time,
717        array_id: None,
718        pg_metadata: Some(CatalogTypePgMetadata {
719            typinput_oid: 1143,
720            typreceive_oid: 2470,
721        }),
722    },
723};
724
725pub const TYPE_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
726    name: "timestamp",
727    schema: PG_CATALOG_SCHEMA,
728    oid: oid::TYPE_TIMESTAMP_OID,
729    details: CatalogTypeDetails {
730        typ: CatalogType::Timestamp,
731        array_id: None,
732        pg_metadata: Some(CatalogTypePgMetadata {
733            typinput_oid: 1312,
734            typreceive_oid: 2474,
735        }),
736    },
737};
738
739pub const TYPE_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
740    name: "_timestamp",
741    schema: PG_CATALOG_SCHEMA,
742    oid: oid::TYPE_TIMESTAMP_ARRAY_OID,
743    details: CatalogTypeDetails {
744        typ: CatalogType::Array {
745            element_reference: TYPE_TIMESTAMP.name,
746        },
747        array_id: None,
748        pg_metadata: Some(CatalogTypePgMetadata {
749            typinput_oid: 750,
750            typreceive_oid: 2400,
751        }),
752    },
753};
754
755pub const TYPE_DATE_ARRAY: BuiltinType<NameReference> = BuiltinType {
756    name: "_date",
757    schema: PG_CATALOG_SCHEMA,
758    oid: oid::TYPE_DATE_ARRAY_OID,
759    details: CatalogTypeDetails {
760        typ: CatalogType::Array {
761            element_reference: TYPE_DATE.name,
762        },
763        array_id: None,
764        pg_metadata: Some(CatalogTypePgMetadata {
765            typinput_oid: 750,
766            typreceive_oid: 2400,
767        }),
768    },
769};
770
771pub const TYPE_TIME_ARRAY: BuiltinType<NameReference> = BuiltinType {
772    name: "_time",
773    schema: PG_CATALOG_SCHEMA,
774    oid: oid::TYPE_TIME_ARRAY_OID,
775    details: CatalogTypeDetails {
776        typ: CatalogType::Array {
777            element_reference: TYPE_TIME.name,
778        },
779        array_id: None,
780        pg_metadata: Some(CatalogTypePgMetadata {
781            typinput_oid: 750,
782            typreceive_oid: 2400,
783        }),
784    },
785};
786
787pub const TYPE_TIMESTAMPTZ: BuiltinType<NameReference> = BuiltinType {
788    name: "timestamptz",
789    schema: PG_CATALOG_SCHEMA,
790    oid: oid::TYPE_TIMESTAMPTZ_OID,
791    details: CatalogTypeDetails {
792        typ: CatalogType::TimestampTz,
793        array_id: None,
794        pg_metadata: Some(CatalogTypePgMetadata {
795            typinput_oid: 1150,
796            typreceive_oid: 2476,
797        }),
798    },
799};
800
801pub const TYPE_TIMESTAMPTZ_ARRAY: BuiltinType<NameReference> = BuiltinType {
802    name: "_timestamptz",
803    schema: PG_CATALOG_SCHEMA,
804    oid: oid::TYPE_TIMESTAMPTZ_ARRAY_OID,
805    details: CatalogTypeDetails {
806        typ: CatalogType::Array {
807            element_reference: TYPE_TIMESTAMPTZ.name,
808        },
809        array_id: None,
810        pg_metadata: Some(CatalogTypePgMetadata {
811            typinput_oid: 750,
812            typreceive_oid: 2400,
813        }),
814    },
815};
816
817pub const TYPE_INTERVAL: BuiltinType<NameReference> = BuiltinType {
818    name: "interval",
819    schema: PG_CATALOG_SCHEMA,
820    oid: oid::TYPE_INTERVAL_OID,
821    details: CatalogTypeDetails {
822        typ: CatalogType::Interval,
823        array_id: None,
824        pg_metadata: Some(CatalogTypePgMetadata {
825            typinput_oid: 1160,
826            typreceive_oid: 2478,
827        }),
828    },
829};
830
831pub const TYPE_INTERVAL_ARRAY: BuiltinType<NameReference> = BuiltinType {
832    name: "_interval",
833    schema: PG_CATALOG_SCHEMA,
834    oid: oid::TYPE_INTERVAL_ARRAY_OID,
835    details: CatalogTypeDetails {
836        typ: CatalogType::Array {
837            element_reference: TYPE_INTERVAL.name,
838        },
839        array_id: None,
840        pg_metadata: Some(CatalogTypePgMetadata {
841            typinput_oid: 750,
842            typreceive_oid: 2400,
843        }),
844    },
845};
846
847pub const TYPE_NAME: BuiltinType<NameReference> = BuiltinType {
848    name: "name",
849    schema: PG_CATALOG_SCHEMA,
850    oid: oid::TYPE_NAME_OID,
851    details: CatalogTypeDetails {
852        typ: CatalogType::PgLegacyName,
853        array_id: None,
854        pg_metadata: Some(CatalogTypePgMetadata {
855            typinput_oid: 34,
856            typreceive_oid: 2422,
857        }),
858    },
859};
860
861pub const TYPE_NAME_ARRAY: BuiltinType<NameReference> = BuiltinType {
862    name: "_name",
863    schema: PG_CATALOG_SCHEMA,
864    oid: oid::TYPE_NAME_ARRAY_OID,
865    details: CatalogTypeDetails {
866        typ: CatalogType::Array {
867            element_reference: TYPE_NAME.name,
868        },
869        array_id: None,
870        pg_metadata: Some(CatalogTypePgMetadata {
871            typinput_oid: 750,
872            typreceive_oid: 2400,
873        }),
874    },
875};
876
877pub const TYPE_NUMERIC: BuiltinType<NameReference> = BuiltinType {
878    name: "numeric",
879    schema: PG_CATALOG_SCHEMA,
880    oid: oid::TYPE_NUMERIC_OID,
881    details: CatalogTypeDetails {
882        typ: CatalogType::Numeric,
883        array_id: None,
884        pg_metadata: Some(CatalogTypePgMetadata {
885            typinput_oid: 1701,
886            typreceive_oid: 2460,
887        }),
888    },
889};
890
891pub const TYPE_NUMERIC_ARRAY: BuiltinType<NameReference> = BuiltinType {
892    name: "_numeric",
893    schema: PG_CATALOG_SCHEMA,
894    oid: oid::TYPE_NUMERIC_ARRAY_OID,
895    details: CatalogTypeDetails {
896        typ: CatalogType::Array {
897            element_reference: TYPE_NUMERIC.name,
898        },
899        array_id: None,
900        pg_metadata: Some(CatalogTypePgMetadata {
901            typinput_oid: 750,
902            typreceive_oid: 2400,
903        }),
904    },
905};
906
907pub const TYPE_RECORD: BuiltinType<NameReference> = BuiltinType {
908    name: "record",
909    schema: PG_CATALOG_SCHEMA,
910    oid: oid::TYPE_RECORD_OID,
911    details: CatalogTypeDetails {
912        typ: CatalogType::Pseudo,
913        array_id: None,
914        pg_metadata: Some(CatalogTypePgMetadata {
915            typinput_oid: 2290,
916            typreceive_oid: 2402,
917        }),
918    },
919};
920
921pub const TYPE_RECORD_ARRAY: BuiltinType<NameReference> = BuiltinType {
922    name: "_record",
923    schema: PG_CATALOG_SCHEMA,
924    oid: oid::TYPE_RECORD_ARRAY_OID,
925    details: CatalogTypeDetails {
926        typ: CatalogType::Array {
927            element_reference: TYPE_RECORD.name,
928        },
929        array_id: None,
930        pg_metadata: Some(CatalogTypePgMetadata {
931            typinput_oid: 750,
932            typreceive_oid: 2400,
933        }),
934    },
935};
936
937pub const TYPE_UUID: BuiltinType<NameReference> = BuiltinType {
938    name: "uuid",
939    schema: PG_CATALOG_SCHEMA,
940    oid: oid::TYPE_UUID_OID,
941    details: CatalogTypeDetails {
942        typ: CatalogType::Uuid,
943        array_id: None,
944        pg_metadata: Some(CatalogTypePgMetadata {
945            typinput_oid: 2952,
946            typreceive_oid: 2961,
947        }),
948    },
949};
950
951pub const TYPE_UUID_ARRAY: BuiltinType<NameReference> = BuiltinType {
952    name: "_uuid",
953    schema: PG_CATALOG_SCHEMA,
954    oid: oid::TYPE_UUID_ARRAY_OID,
955    details: CatalogTypeDetails {
956        typ: CatalogType::Array {
957            element_reference: TYPE_UUID.name,
958        },
959        array_id: None,
960        pg_metadata: Some(CatalogTypePgMetadata {
961            typinput_oid: 750,
962            typreceive_oid: 2400,
963        }),
964    },
965};
966
967pub const TYPE_JSONB: BuiltinType<NameReference> = BuiltinType {
968    name: "jsonb",
969    schema: PG_CATALOG_SCHEMA,
970    oid: oid::TYPE_JSONB_OID,
971    details: CatalogTypeDetails {
972        typ: CatalogType::Jsonb,
973        array_id: None,
974        pg_metadata: Some(CatalogTypePgMetadata {
975            typinput_oid: 3806,
976            typreceive_oid: 3805,
977        }),
978    },
979};
980
981pub const TYPE_JSONB_ARRAY: BuiltinType<NameReference> = BuiltinType {
982    name: "_jsonb",
983    schema: PG_CATALOG_SCHEMA,
984    oid: oid::TYPE_JSONB_ARRAY_OID,
985    details: CatalogTypeDetails {
986        typ: CatalogType::Array {
987            element_reference: TYPE_JSONB.name,
988        },
989        array_id: None,
990        pg_metadata: Some(CatalogTypePgMetadata {
991            typinput_oid: 750,
992            typreceive_oid: 2400,
993        }),
994    },
995};
996
997pub const TYPE_ANY: BuiltinType<NameReference> = BuiltinType {
998    name: "any",
999    schema: PG_CATALOG_SCHEMA,
1000    oid: oid::TYPE_ANY_OID,
1001    details: CatalogTypeDetails {
1002        typ: CatalogType::Pseudo,
1003        array_id: None,
1004        pg_metadata: Some(CatalogTypePgMetadata {
1005            typinput_oid: 2294,
1006            typreceive_oid: 0,
1007        }),
1008    },
1009};
1010
1011pub const TYPE_ANYARRAY: BuiltinType<NameReference> = BuiltinType {
1012    name: "anyarray",
1013    schema: PG_CATALOG_SCHEMA,
1014    oid: oid::TYPE_ANYARRAY_OID,
1015    details: CatalogTypeDetails {
1016        typ: CatalogType::Pseudo,
1017        array_id: None,
1018        pg_metadata: Some(CatalogTypePgMetadata {
1019            typinput_oid: 2296,
1020            typreceive_oid: 2502,
1021        }),
1022    },
1023};
1024
1025pub const TYPE_ANYELEMENT: BuiltinType<NameReference> = BuiltinType {
1026    name: "anyelement",
1027    schema: PG_CATALOG_SCHEMA,
1028    oid: oid::TYPE_ANYELEMENT_OID,
1029    details: CatalogTypeDetails {
1030        typ: CatalogType::Pseudo,
1031        array_id: None,
1032        pg_metadata: Some(CatalogTypePgMetadata {
1033            typinput_oid: 2312,
1034            typreceive_oid: 0,
1035        }),
1036    },
1037};
1038
1039pub const TYPE_ANYNONARRAY: BuiltinType<NameReference> = BuiltinType {
1040    name: "anynonarray",
1041    schema: PG_CATALOG_SCHEMA,
1042    oid: oid::TYPE_ANYNONARRAY_OID,
1043    details: CatalogTypeDetails {
1044        typ: CatalogType::Pseudo,
1045        array_id: None,
1046        pg_metadata: Some(CatalogTypePgMetadata {
1047            typinput_oid: 2777,
1048            typreceive_oid: 0,
1049        }),
1050    },
1051};
1052
1053pub const TYPE_ANYRANGE: BuiltinType<NameReference> = BuiltinType {
1054    name: "anyrange",
1055    schema: PG_CATALOG_SCHEMA,
1056    oid: oid::TYPE_ANYRANGE_OID,
1057    details: CatalogTypeDetails {
1058        typ: CatalogType::Pseudo,
1059        array_id: None,
1060        pg_metadata: Some(CatalogTypePgMetadata {
1061            typinput_oid: 3832,
1062            typreceive_oid: 0,
1063        }),
1064    },
1065};
1066
1067pub const TYPE_CHAR: BuiltinType<NameReference> = BuiltinType {
1068    name: "char",
1069    schema: PG_CATALOG_SCHEMA,
1070    oid: oid::TYPE_CHAR_OID,
1071    details: CatalogTypeDetails {
1072        typ: CatalogType::PgLegacyChar,
1073        array_id: None,
1074        pg_metadata: Some(CatalogTypePgMetadata {
1075            typinput_oid: 1245,
1076            typreceive_oid: 2434,
1077        }),
1078    },
1079};
1080
1081pub const TYPE_VARCHAR: BuiltinType<NameReference> = BuiltinType {
1082    name: "varchar",
1083    schema: PG_CATALOG_SCHEMA,
1084    oid: oid::TYPE_VARCHAR_OID,
1085    details: CatalogTypeDetails {
1086        typ: CatalogType::VarChar,
1087        array_id: None,
1088        pg_metadata: Some(CatalogTypePgMetadata {
1089            typinput_oid: 1046,
1090            typreceive_oid: 2432,
1091        }),
1092    },
1093};
1094
1095pub const TYPE_INT2: BuiltinType<NameReference> = BuiltinType {
1096    name: "int2",
1097    schema: PG_CATALOG_SCHEMA,
1098    oid: oid::TYPE_INT2_OID,
1099    details: CatalogTypeDetails {
1100        typ: CatalogType::Int16,
1101        array_id: None,
1102        pg_metadata: Some(CatalogTypePgMetadata {
1103            typinput_oid: 38,
1104            typreceive_oid: 2404,
1105        }),
1106    },
1107};
1108
1109pub const TYPE_INT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1110    name: "_int2",
1111    schema: PG_CATALOG_SCHEMA,
1112    oid: oid::TYPE_INT2_ARRAY_OID,
1113    details: CatalogTypeDetails {
1114        typ: CatalogType::Array {
1115            element_reference: TYPE_INT2.name,
1116        },
1117        array_id: None,
1118        pg_metadata: Some(CatalogTypePgMetadata {
1119            typinput_oid: 750,
1120            typreceive_oid: 2400,
1121        }),
1122    },
1123};
1124
1125pub const TYPE_BPCHAR: BuiltinType<NameReference> = BuiltinType {
1126    name: "bpchar",
1127    schema: PG_CATALOG_SCHEMA,
1128    oid: oid::TYPE_BPCHAR_OID,
1129    details: CatalogTypeDetails {
1130        typ: CatalogType::Char,
1131        array_id: None,
1132        pg_metadata: Some(CatalogTypePgMetadata {
1133            typinput_oid: 1044,
1134            typreceive_oid: 2430,
1135        }),
1136    },
1137};
1138
1139pub const TYPE_CHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1140    name: "_char",
1141    schema: PG_CATALOG_SCHEMA,
1142    oid: oid::TYPE_CHAR_ARRAY_OID,
1143    details: CatalogTypeDetails {
1144        typ: CatalogType::Array {
1145            element_reference: TYPE_CHAR.name,
1146        },
1147        array_id: None,
1148        pg_metadata: Some(CatalogTypePgMetadata {
1149            typinput_oid: 750,
1150            typreceive_oid: 2400,
1151        }),
1152    },
1153};
1154
1155pub const TYPE_VARCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1156    name: "_varchar",
1157    schema: PG_CATALOG_SCHEMA,
1158    oid: oid::TYPE_VARCHAR_ARRAY_OID,
1159    details: CatalogTypeDetails {
1160        typ: CatalogType::Array {
1161            element_reference: TYPE_VARCHAR.name,
1162        },
1163        array_id: None,
1164        pg_metadata: Some(CatalogTypePgMetadata {
1165            typinput_oid: 750,
1166            typreceive_oid: 2400,
1167        }),
1168    },
1169};
1170
1171pub const TYPE_BPCHAR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1172    name: "_bpchar",
1173    schema: PG_CATALOG_SCHEMA,
1174    oid: oid::TYPE_BPCHAR_ARRAY_OID,
1175    details: CatalogTypeDetails {
1176        typ: CatalogType::Array {
1177            element_reference: TYPE_BPCHAR.name,
1178        },
1179        array_id: None,
1180        pg_metadata: Some(CatalogTypePgMetadata {
1181            typinput_oid: 750,
1182            typreceive_oid: 2400,
1183        }),
1184    },
1185};
1186
1187pub const TYPE_REGPROC: BuiltinType<NameReference> = BuiltinType {
1188    name: "regproc",
1189    schema: PG_CATALOG_SCHEMA,
1190    oid: oid::TYPE_REGPROC_OID,
1191    details: CatalogTypeDetails {
1192        typ: CatalogType::RegProc,
1193        array_id: None,
1194        pg_metadata: Some(CatalogTypePgMetadata {
1195            typinput_oid: 44,
1196            typreceive_oid: 2444,
1197        }),
1198    },
1199};
1200
1201pub const TYPE_REGPROC_ARRAY: BuiltinType<NameReference> = BuiltinType {
1202    name: "_regproc",
1203    schema: PG_CATALOG_SCHEMA,
1204    oid: oid::TYPE_REGPROC_ARRAY_OID,
1205    details: CatalogTypeDetails {
1206        typ: CatalogType::Array {
1207            element_reference: TYPE_REGPROC.name,
1208        },
1209        array_id: None,
1210        pg_metadata: Some(CatalogTypePgMetadata {
1211            typinput_oid: 750,
1212            typreceive_oid: 2400,
1213        }),
1214    },
1215};
1216
1217pub const TYPE_REGTYPE: BuiltinType<NameReference> = BuiltinType {
1218    name: "regtype",
1219    schema: PG_CATALOG_SCHEMA,
1220    oid: oid::TYPE_REGTYPE_OID,
1221    details: CatalogTypeDetails {
1222        typ: CatalogType::RegType,
1223        array_id: None,
1224        pg_metadata: Some(CatalogTypePgMetadata {
1225            typinput_oid: 2220,
1226            typreceive_oid: 2454,
1227        }),
1228    },
1229};
1230
1231pub const TYPE_REGTYPE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1232    name: "_regtype",
1233    schema: PG_CATALOG_SCHEMA,
1234    oid: oid::TYPE_REGTYPE_ARRAY_OID,
1235    details: CatalogTypeDetails {
1236        typ: CatalogType::Array {
1237            element_reference: TYPE_REGTYPE.name,
1238        },
1239        array_id: None,
1240        pg_metadata: Some(CatalogTypePgMetadata {
1241            typinput_oid: 750,
1242            typreceive_oid: 2400,
1243        }),
1244    },
1245};
1246
1247pub const TYPE_REGCLASS: BuiltinType<NameReference> = BuiltinType {
1248    name: "regclass",
1249    schema: PG_CATALOG_SCHEMA,
1250    oid: oid::TYPE_REGCLASS_OID,
1251    details: CatalogTypeDetails {
1252        typ: CatalogType::RegClass,
1253        array_id: None,
1254        pg_metadata: Some(CatalogTypePgMetadata {
1255            typinput_oid: 2218,
1256            typreceive_oid: 2452,
1257        }),
1258    },
1259};
1260
1261pub const TYPE_REGCLASS_ARRAY: BuiltinType<NameReference> = BuiltinType {
1262    name: "_regclass",
1263    schema: PG_CATALOG_SCHEMA,
1264    oid: oid::TYPE_REGCLASS_ARRAY_OID,
1265    details: CatalogTypeDetails {
1266        typ: CatalogType::Array {
1267            element_reference: TYPE_REGCLASS.name,
1268        },
1269        array_id: None,
1270        pg_metadata: Some(CatalogTypePgMetadata {
1271            typinput_oid: 750,
1272            typreceive_oid: 2400,
1273        }),
1274    },
1275};
1276
1277pub const TYPE_INT2_VECTOR: BuiltinType<NameReference> = BuiltinType {
1278    name: "int2vector",
1279    schema: PG_CATALOG_SCHEMA,
1280    oid: oid::TYPE_INT2_VECTOR_OID,
1281    details: CatalogTypeDetails {
1282        typ: CatalogType::Int2Vector,
1283        array_id: None,
1284        pg_metadata: Some(CatalogTypePgMetadata {
1285            typinput_oid: 40,
1286            typreceive_oid: 2410,
1287        }),
1288    },
1289};
1290
1291pub const TYPE_INT2_VECTOR_ARRAY: BuiltinType<NameReference> = BuiltinType {
1292    name: "_int2vector",
1293    schema: PG_CATALOG_SCHEMA,
1294    oid: oid::TYPE_INT2_VECTOR_ARRAY_OID,
1295    details: CatalogTypeDetails {
1296        typ: CatalogType::Array {
1297            element_reference: TYPE_INT2_VECTOR.name,
1298        },
1299        array_id: None,
1300        pg_metadata: Some(CatalogTypePgMetadata {
1301            typinput_oid: 750,
1302            typreceive_oid: 2400,
1303        }),
1304    },
1305};
1306
1307pub const TYPE_ANYCOMPATIBLE: BuiltinType<NameReference> = BuiltinType {
1308    name: "anycompatible",
1309    schema: PG_CATALOG_SCHEMA,
1310    oid: oid::TYPE_ANYCOMPATIBLE_OID,
1311    details: CatalogTypeDetails {
1312        typ: CatalogType::Pseudo,
1313        array_id: None,
1314        pg_metadata: Some(CatalogTypePgMetadata {
1315            typinput_oid: 5086,
1316            typreceive_oid: 0,
1317        }),
1318    },
1319};
1320
1321pub const TYPE_ANYCOMPATIBLEARRAY: BuiltinType<NameReference> = BuiltinType {
1322    name: "anycompatiblearray",
1323    schema: PG_CATALOG_SCHEMA,
1324    oid: oid::TYPE_ANYCOMPATIBLEARRAY_OID,
1325    details: CatalogTypeDetails {
1326        typ: CatalogType::Pseudo,
1327        array_id: None,
1328        pg_metadata: Some(CatalogTypePgMetadata {
1329            typinput_oid: 5088,
1330            typreceive_oid: 5090,
1331        }),
1332    },
1333};
1334
1335pub const TYPE_ANYCOMPATIBLENONARRAY: BuiltinType<NameReference> = BuiltinType {
1336    name: "anycompatiblenonarray",
1337    schema: PG_CATALOG_SCHEMA,
1338    oid: oid::TYPE_ANYCOMPATIBLENONARRAY_OID,
1339    details: CatalogTypeDetails {
1340        typ: CatalogType::Pseudo,
1341        array_id: None,
1342        pg_metadata: Some(CatalogTypePgMetadata {
1343            typinput_oid: 5092,
1344            typreceive_oid: 0,
1345        }),
1346    },
1347};
1348
1349pub const TYPE_ANYCOMPATIBLERANGE: BuiltinType<NameReference> = BuiltinType {
1350    name: "anycompatiblerange",
1351    schema: PG_CATALOG_SCHEMA,
1352    oid: oid::TYPE_ANYCOMPATIBLERANGE_OID,
1353    details: CatalogTypeDetails {
1354        typ: CatalogType::Pseudo,
1355        array_id: None,
1356        pg_metadata: Some(CatalogTypePgMetadata {
1357            typinput_oid: 5094,
1358            typreceive_oid: 0,
1359        }),
1360    },
1361};
1362
1363pub const TYPE_LIST: BuiltinType<NameReference> = BuiltinType {
1364    name: "list",
1365    schema: MZ_CATALOG_SCHEMA,
1366    oid: mz_pgrepr::oid::TYPE_LIST_OID,
1367    details: CatalogTypeDetails {
1368        typ: CatalogType::Pseudo,
1369        array_id: None,
1370        pg_metadata: None,
1371    },
1372};
1373
1374pub const TYPE_MAP: BuiltinType<NameReference> = BuiltinType {
1375    name: "map",
1376    schema: MZ_CATALOG_SCHEMA,
1377    oid: mz_pgrepr::oid::TYPE_MAP_OID,
1378    details: CatalogTypeDetails {
1379        typ: CatalogType::Pseudo,
1380        array_id: None,
1381        pg_metadata: None,
1382    },
1383};
1384
1385pub const TYPE_ANYCOMPATIBLELIST: BuiltinType<NameReference> = BuiltinType {
1386    name: "anycompatiblelist",
1387    schema: MZ_CATALOG_SCHEMA,
1388    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLELIST_OID,
1389    details: CatalogTypeDetails {
1390        typ: CatalogType::Pseudo,
1391        array_id: None,
1392        pg_metadata: None,
1393    },
1394};
1395
1396pub const TYPE_ANYCOMPATIBLEMAP: BuiltinType<NameReference> = BuiltinType {
1397    name: "anycompatiblemap",
1398    schema: MZ_CATALOG_SCHEMA,
1399    oid: mz_pgrepr::oid::TYPE_ANYCOMPATIBLEMAP_OID,
1400    details: CatalogTypeDetails {
1401        typ: CatalogType::Pseudo,
1402        array_id: None,
1403        pg_metadata: None,
1404    },
1405};
1406
1407pub const TYPE_UINT2: BuiltinType<NameReference> = BuiltinType {
1408    name: "uint2",
1409    schema: MZ_CATALOG_SCHEMA,
1410    oid: mz_pgrepr::oid::TYPE_UINT2_OID,
1411    details: CatalogTypeDetails {
1412        typ: CatalogType::UInt16,
1413        array_id: None,
1414        pg_metadata: None,
1415    },
1416};
1417
1418pub const TYPE_UINT2_ARRAY: BuiltinType<NameReference> = BuiltinType {
1419    name: "_uint2",
1420    schema: MZ_CATALOG_SCHEMA,
1421    oid: mz_pgrepr::oid::TYPE_UINT2_ARRAY_OID,
1422    details: CatalogTypeDetails {
1423        typ: CatalogType::Array {
1424            element_reference: TYPE_UINT2.name,
1425        },
1426        array_id: None,
1427        pg_metadata: None,
1428    },
1429};
1430
1431pub const TYPE_UINT4: BuiltinType<NameReference> = BuiltinType {
1432    name: "uint4",
1433    schema: MZ_CATALOG_SCHEMA,
1434    oid: mz_pgrepr::oid::TYPE_UINT4_OID,
1435    details: CatalogTypeDetails {
1436        typ: CatalogType::UInt32,
1437        array_id: None,
1438        pg_metadata: None,
1439    },
1440};
1441
1442pub const TYPE_UINT4_ARRAY: BuiltinType<NameReference> = BuiltinType {
1443    name: "_uint4",
1444    schema: MZ_CATALOG_SCHEMA,
1445    oid: mz_pgrepr::oid::TYPE_UINT4_ARRAY_OID,
1446    details: CatalogTypeDetails {
1447        typ: CatalogType::Array {
1448            element_reference: TYPE_UINT4.name,
1449        },
1450        array_id: None,
1451        pg_metadata: None,
1452    },
1453};
1454
1455pub const TYPE_UINT8: BuiltinType<NameReference> = BuiltinType {
1456    name: "uint8",
1457    schema: MZ_CATALOG_SCHEMA,
1458    oid: mz_pgrepr::oid::TYPE_UINT8_OID,
1459    details: CatalogTypeDetails {
1460        typ: CatalogType::UInt64,
1461        array_id: None,
1462        pg_metadata: None,
1463    },
1464};
1465
1466pub const TYPE_UINT8_ARRAY: BuiltinType<NameReference> = BuiltinType {
1467    name: "_uint8",
1468    schema: MZ_CATALOG_SCHEMA,
1469    oid: mz_pgrepr::oid::TYPE_UINT8_ARRAY_OID,
1470    details: CatalogTypeDetails {
1471        typ: CatalogType::Array {
1472            element_reference: TYPE_UINT8.name,
1473        },
1474        array_id: None,
1475        pg_metadata: None,
1476    },
1477};
1478
1479pub const TYPE_MZ_TIMESTAMP: BuiltinType<NameReference> = BuiltinType {
1480    name: "mz_timestamp",
1481    schema: MZ_CATALOG_SCHEMA,
1482    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_OID,
1483    details: CatalogTypeDetails {
1484        typ: CatalogType::MzTimestamp,
1485        array_id: None,
1486        pg_metadata: None,
1487    },
1488};
1489
1490pub const TYPE_MZ_TIMESTAMP_ARRAY: BuiltinType<NameReference> = BuiltinType {
1491    name: "_mz_timestamp",
1492    schema: MZ_CATALOG_SCHEMA,
1493    oid: mz_pgrepr::oid::TYPE_MZ_TIMESTAMP_ARRAY_OID,
1494    details: CatalogTypeDetails {
1495        typ: CatalogType::Array {
1496            element_reference: TYPE_MZ_TIMESTAMP.name,
1497        },
1498        array_id: None,
1499        pg_metadata: None,
1500    },
1501};
1502
1503pub const TYPE_INT4_RANGE: BuiltinType<NameReference> = BuiltinType {
1504    name: "int4range",
1505    schema: PG_CATALOG_SCHEMA,
1506    oid: mz_pgrepr::oid::TYPE_INT4RANGE_OID,
1507    details: CatalogTypeDetails {
1508        typ: CatalogType::Range {
1509            element_reference: TYPE_INT4.name,
1510        },
1511        array_id: None,
1512        pg_metadata: Some(CatalogTypePgMetadata {
1513            typinput_oid: 3834,
1514            typreceive_oid: 3836,
1515        }),
1516    },
1517};
1518
1519pub const TYPE_INT4_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1520    name: "_int4range",
1521    schema: PG_CATALOG_SCHEMA,
1522    oid: mz_pgrepr::oid::TYPE_INT4RANGE_ARRAY_OID,
1523    details: CatalogTypeDetails {
1524        typ: CatalogType::Array {
1525            element_reference: TYPE_INT4_RANGE.name,
1526        },
1527        array_id: None,
1528        pg_metadata: Some(CatalogTypePgMetadata {
1529            typinput_oid: 750,
1530            typreceive_oid: 2400,
1531        }),
1532    },
1533};
1534
1535pub const TYPE_INT8_RANGE: BuiltinType<NameReference> = BuiltinType {
1536    name: "int8range",
1537    schema: PG_CATALOG_SCHEMA,
1538    oid: mz_pgrepr::oid::TYPE_INT8RANGE_OID,
1539    details: CatalogTypeDetails {
1540        typ: CatalogType::Range {
1541            element_reference: TYPE_INT8.name,
1542        },
1543        array_id: None,
1544        pg_metadata: Some(CatalogTypePgMetadata {
1545            typinput_oid: 3834,
1546            typreceive_oid: 3836,
1547        }),
1548    },
1549};
1550
1551pub const TYPE_INT8_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1552    name: "_int8range",
1553    schema: PG_CATALOG_SCHEMA,
1554    oid: mz_pgrepr::oid::TYPE_INT8RANGE_ARRAY_OID,
1555    details: CatalogTypeDetails {
1556        typ: CatalogType::Array {
1557            element_reference: TYPE_INT8_RANGE.name,
1558        },
1559        array_id: None,
1560        pg_metadata: Some(CatalogTypePgMetadata {
1561            typinput_oid: 750,
1562            typreceive_oid: 2400,
1563        }),
1564    },
1565};
1566
1567pub const TYPE_DATE_RANGE: BuiltinType<NameReference> = BuiltinType {
1568    name: "daterange",
1569    schema: PG_CATALOG_SCHEMA,
1570    oid: mz_pgrepr::oid::TYPE_DATERANGE_OID,
1571    details: CatalogTypeDetails {
1572        typ: CatalogType::Range {
1573            element_reference: TYPE_DATE.name,
1574        },
1575        array_id: None,
1576        pg_metadata: Some(CatalogTypePgMetadata {
1577            typinput_oid: 3834,
1578            typreceive_oid: 3836,
1579        }),
1580    },
1581};
1582
1583pub const TYPE_DATE_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1584    name: "_daterange",
1585    schema: PG_CATALOG_SCHEMA,
1586    oid: mz_pgrepr::oid::TYPE_DATERANGE_ARRAY_OID,
1587    details: CatalogTypeDetails {
1588        typ: CatalogType::Array {
1589            element_reference: TYPE_DATE_RANGE.name,
1590        },
1591        array_id: None,
1592        pg_metadata: Some(CatalogTypePgMetadata {
1593            typinput_oid: 750,
1594            typreceive_oid: 2400,
1595        }),
1596    },
1597};
1598
1599pub const TYPE_NUM_RANGE: BuiltinType<NameReference> = BuiltinType {
1600    name: "numrange",
1601    schema: PG_CATALOG_SCHEMA,
1602    oid: mz_pgrepr::oid::TYPE_NUMRANGE_OID,
1603    details: CatalogTypeDetails {
1604        typ: CatalogType::Range {
1605            element_reference: TYPE_NUMERIC.name,
1606        },
1607        array_id: None,
1608        pg_metadata: Some(CatalogTypePgMetadata {
1609            typinput_oid: 3834,
1610            typreceive_oid: 3836,
1611        }),
1612    },
1613};
1614
1615pub const TYPE_NUM_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1616    name: "_numrange",
1617    schema: PG_CATALOG_SCHEMA,
1618    oid: mz_pgrepr::oid::TYPE_NUMRANGE_ARRAY_OID,
1619    details: CatalogTypeDetails {
1620        typ: CatalogType::Array {
1621            element_reference: TYPE_NUM_RANGE.name,
1622        },
1623        array_id: None,
1624        pg_metadata: Some(CatalogTypePgMetadata {
1625            typinput_oid: 750,
1626            typreceive_oid: 2400,
1627        }),
1628    },
1629};
1630
1631pub const TYPE_TS_RANGE: BuiltinType<NameReference> = BuiltinType {
1632    name: "tsrange",
1633    schema: PG_CATALOG_SCHEMA,
1634    oid: mz_pgrepr::oid::TYPE_TSRANGE_OID,
1635    details: CatalogTypeDetails {
1636        typ: CatalogType::Range {
1637            element_reference: TYPE_TIMESTAMP.name,
1638        },
1639        array_id: None,
1640        pg_metadata: Some(CatalogTypePgMetadata {
1641            typinput_oid: 3834,
1642            typreceive_oid: 3836,
1643        }),
1644    },
1645};
1646
1647pub const TYPE_TS_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1648    name: "_tsrange",
1649    schema: PG_CATALOG_SCHEMA,
1650    oid: mz_pgrepr::oid::TYPE_TSRANGE_ARRAY_OID,
1651    details: CatalogTypeDetails {
1652        typ: CatalogType::Array {
1653            element_reference: TYPE_TS_RANGE.name,
1654        },
1655        array_id: None,
1656        pg_metadata: Some(CatalogTypePgMetadata {
1657            typinput_oid: 750,
1658            typreceive_oid: 2400,
1659        }),
1660    },
1661};
1662
1663pub const TYPE_TSTZ_RANGE: BuiltinType<NameReference> = BuiltinType {
1664    name: "tstzrange",
1665    schema: PG_CATALOG_SCHEMA,
1666    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_OID,
1667    details: CatalogTypeDetails {
1668        typ: CatalogType::Range {
1669            element_reference: TYPE_TIMESTAMPTZ.name,
1670        },
1671        array_id: None,
1672        pg_metadata: Some(CatalogTypePgMetadata {
1673            typinput_oid: 3834,
1674            typreceive_oid: 3836,
1675        }),
1676    },
1677};
1678
1679pub const TYPE_TSTZ_RANGE_ARRAY: BuiltinType<NameReference> = BuiltinType {
1680    name: "_tstzrange",
1681    schema: PG_CATALOG_SCHEMA,
1682    oid: mz_pgrepr::oid::TYPE_TSTZRANGE_ARRAY_OID,
1683    details: CatalogTypeDetails {
1684        typ: CatalogType::Array {
1685            element_reference: TYPE_TSTZ_RANGE.name,
1686        },
1687        array_id: None,
1688        pg_metadata: Some(CatalogTypePgMetadata {
1689            typinput_oid: 750,
1690            typreceive_oid: 2400,
1691        }),
1692    },
1693};
1694
1695pub const TYPE_MZ_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1696    name: "mz_aclitem",
1697    schema: MZ_CATALOG_SCHEMA,
1698    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_OID,
1699    details: CatalogTypeDetails {
1700        typ: CatalogType::MzAclItem,
1701        array_id: None,
1702        pg_metadata: None,
1703    },
1704};
1705
1706pub const TYPE_MZ_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1707    name: "_mz_aclitem",
1708    schema: MZ_CATALOG_SCHEMA,
1709    oid: mz_pgrepr::oid::TYPE_MZ_ACL_ITEM_ARRAY_OID,
1710    details: CatalogTypeDetails {
1711        typ: CatalogType::Array {
1712            element_reference: TYPE_MZ_ACL_ITEM.name,
1713        },
1714        array_id: None,
1715        pg_metadata: Some(CatalogTypePgMetadata {
1716            typinput_oid: 750,
1717            typreceive_oid: 2400,
1718        }),
1719    },
1720};
1721
1722pub const TYPE_ACL_ITEM: BuiltinType<NameReference> = BuiltinType {
1723    name: "aclitem",
1724    schema: PG_CATALOG_SCHEMA,
1725    oid: 1033,
1726    details: CatalogTypeDetails {
1727        typ: CatalogType::AclItem,
1728        array_id: None,
1729        pg_metadata: Some(CatalogTypePgMetadata {
1730            typinput_oid: 1031,
1731            typreceive_oid: 0,
1732        }),
1733    },
1734};
1735
1736pub const TYPE_ACL_ITEM_ARRAY: BuiltinType<NameReference> = BuiltinType {
1737    name: "_aclitem",
1738    schema: PG_CATALOG_SCHEMA,
1739    oid: 1034,
1740    details: CatalogTypeDetails {
1741        typ: CatalogType::Array {
1742            element_reference: TYPE_ACL_ITEM.name,
1743        },
1744        array_id: None,
1745        pg_metadata: Some(CatalogTypePgMetadata {
1746            typinput_oid: 750,
1747            typreceive_oid: 2400,
1748        }),
1749    },
1750};
1751
1752pub const TYPE_INTERNAL: BuiltinType<NameReference> = BuiltinType {
1753    name: "internal",
1754    schema: PG_CATALOG_SCHEMA,
1755    oid: 2281,
1756    details: CatalogTypeDetails {
1757        typ: CatalogType::Pseudo,
1758        array_id: None,
1759        pg_metadata: Some(CatalogTypePgMetadata {
1760            typinput_oid: 2304,
1761            typreceive_oid: 0,
1762        }),
1763    },
1764};
1765
1766const PUBLIC_SELECT: MzAclItem = MzAclItem {
1767    grantee: RoleId::Public,
1768    grantor: MZ_SYSTEM_ROLE_ID,
1769    acl_mode: AclMode::SELECT,
1770};
1771
1772const SUPPORT_SELECT: MzAclItem = MzAclItem {
1773    grantee: MZ_SUPPORT_ROLE_ID,
1774    grantor: MZ_SYSTEM_ROLE_ID,
1775    acl_mode: AclMode::SELECT,
1776};
1777
1778const ANALYTICS_SELECT: MzAclItem = MzAclItem {
1779    grantee: MZ_ANALYTICS_ROLE_ID,
1780    grantor: MZ_SYSTEM_ROLE_ID,
1781    acl_mode: AclMode::SELECT,
1782};
1783
1784const MONITOR_SELECT: MzAclItem = MzAclItem {
1785    grantee: MZ_MONITOR_ROLE_ID,
1786    grantor: MZ_SYSTEM_ROLE_ID,
1787    acl_mode: AclMode::SELECT,
1788};
1789
1790const MONITOR_REDACTED_SELECT: MzAclItem = MzAclItem {
1791    grantee: MZ_MONITOR_REDACTED_ROLE_ID,
1792    grantor: MZ_SYSTEM_ROLE_ID,
1793    acl_mode: AclMode::SELECT,
1794};
1795
1796pub static MZ_CATALOG_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
1797    name: "mz_catalog_raw",
1798    schema: MZ_INTERNAL_SCHEMA,
1799    oid: oid::SOURCE_MZ_CATALOG_RAW_OID,
1800    data_source: DataSourceDesc::Catalog,
1801    desc: crate::durable::persist_desc(),
1802    column_comments: BTreeMap::new(),
1803    is_retained_metrics_object: false,
1804    // The raw catalog contains unredacted SQL statements, so we limit access to the system user.
1805    access: vec![],
1806});
1807
1808pub static MZ_CATALOG_RAW_DESCRIPTION: LazyLock<SystemObjectDescription> =
1809    LazyLock::new(|| SystemObjectDescription {
1810        schema_name: MZ_CATALOG_RAW.schema.to_string(),
1811        object_type: CatalogItemType::Source,
1812        object_name: MZ_CATALOG_RAW.name.to_string(),
1813    });
1814
1815pub static MZ_DATAFLOW_OPERATORS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1816    name: "mz_dataflow_operators_per_worker",
1817    schema: MZ_INTROSPECTION_SCHEMA,
1818    oid: oid::LOG_MZ_DATAFLOW_OPERATORS_PER_WORKER_OID,
1819    variant: LogVariant::Timely(TimelyLog::Operates),
1820    access: vec![PUBLIC_SELECT],
1821});
1822
1823pub static MZ_DATAFLOW_ADDRESSES_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1824    name: "mz_dataflow_addresses_per_worker",
1825    schema: MZ_INTROSPECTION_SCHEMA,
1826    oid: oid::LOG_MZ_DATAFLOW_ADDRESSES_PER_WORKER_OID,
1827    variant: LogVariant::Timely(TimelyLog::Addresses),
1828    access: vec![PUBLIC_SELECT],
1829});
1830
1831pub static MZ_DATAFLOW_CHANNELS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1832    name: "mz_dataflow_channels_per_worker",
1833    schema: MZ_INTROSPECTION_SCHEMA,
1834    oid: oid::LOG_MZ_DATAFLOW_CHANNELS_PER_WORKER_OID,
1835    variant: LogVariant::Timely(TimelyLog::Channels),
1836    access: vec![PUBLIC_SELECT],
1837});
1838
1839pub static MZ_SCHEDULING_ELAPSED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1840    name: "mz_scheduling_elapsed_raw",
1841    schema: MZ_INTROSPECTION_SCHEMA,
1842    oid: oid::LOG_MZ_SCHEDULING_ELAPSED_RAW_OID,
1843    variant: LogVariant::Timely(TimelyLog::Elapsed),
1844    access: vec![PUBLIC_SELECT],
1845});
1846
1847pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> =
1848    LazyLock::new(|| BuiltinLog {
1849        name: "mz_compute_operator_durations_histogram_raw",
1850        schema: MZ_INTROSPECTION_SCHEMA,
1851        oid: oid::LOG_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW_OID,
1852        variant: LogVariant::Timely(TimelyLog::Histogram),
1853        access: vec![PUBLIC_SELECT],
1854    });
1855
1856pub static MZ_SCHEDULING_PARKS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1857    name: "mz_scheduling_parks_histogram_raw",
1858    schema: MZ_INTROSPECTION_SCHEMA,
1859    oid: oid::LOG_MZ_SCHEDULING_PARKS_HISTOGRAM_RAW_OID,
1860    variant: LogVariant::Timely(TimelyLog::Parks),
1861    access: vec![PUBLIC_SELECT],
1862});
1863
1864pub static MZ_ARRANGEMENT_RECORDS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1865    name: "mz_arrangement_records_raw",
1866    schema: MZ_INTROSPECTION_SCHEMA,
1867    oid: oid::LOG_MZ_ARRANGEMENT_RECORDS_RAW_OID,
1868    variant: LogVariant::Differential(DifferentialLog::ArrangementRecords),
1869    access: vec![PUBLIC_SELECT],
1870});
1871
1872pub static MZ_ARRANGEMENT_BATCHES_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1873    name: "mz_arrangement_batches_raw",
1874    schema: MZ_INTROSPECTION_SCHEMA,
1875    oid: oid::LOG_MZ_ARRANGEMENT_BATCHES_RAW_OID,
1876    variant: LogVariant::Differential(DifferentialLog::ArrangementBatches),
1877    access: vec![PUBLIC_SELECT],
1878});
1879
1880pub static MZ_ARRANGEMENT_SHARING_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1881    name: "mz_arrangement_sharing_raw",
1882    schema: MZ_INTROSPECTION_SCHEMA,
1883    oid: oid::LOG_MZ_ARRANGEMENT_SHARING_RAW_OID,
1884    variant: LogVariant::Differential(DifferentialLog::Sharing),
1885    access: vec![PUBLIC_SELECT],
1886});
1887
1888pub static MZ_ARRANGEMENT_BATCHER_RECORDS_RAW: LazyLock<BuiltinLog> =
1889    LazyLock::new(|| BuiltinLog {
1890        name: "mz_arrangement_batcher_records_raw",
1891        schema: MZ_INTROSPECTION_SCHEMA,
1892        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_RECORDS_RAW_OID,
1893        variant: LogVariant::Differential(DifferentialLog::BatcherRecords),
1894        access: vec![PUBLIC_SELECT],
1895    });
1896
1897pub static MZ_ARRANGEMENT_BATCHER_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1898    name: "mz_arrangement_batcher_size_raw",
1899    schema: MZ_INTROSPECTION_SCHEMA,
1900    oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_SIZE_RAW_OID,
1901    variant: LogVariant::Differential(DifferentialLog::BatcherSize),
1902    access: vec![PUBLIC_SELECT],
1903});
1904
1905pub static MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW: LazyLock<BuiltinLog> =
1906    LazyLock::new(|| BuiltinLog {
1907        name: "mz_arrangement_batcher_capacity_raw",
1908        schema: MZ_INTROSPECTION_SCHEMA,
1909        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW_OID,
1910        variant: LogVariant::Differential(DifferentialLog::BatcherCapacity),
1911        access: vec![PUBLIC_SELECT],
1912    });
1913
1914pub static MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
1915    LazyLock::new(|| BuiltinLog {
1916        name: "mz_arrangement_batcher_allocations_raw",
1917        schema: MZ_INTROSPECTION_SCHEMA,
1918        oid: oid::LOG_MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW_OID,
1919        variant: LogVariant::Differential(DifferentialLog::BatcherAllocations),
1920        access: vec![PUBLIC_SELECT],
1921    });
1922
1923pub static MZ_COMPUTE_EXPORTS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1924    name: "mz_compute_exports_per_worker",
1925    schema: MZ_INTROSPECTION_SCHEMA,
1926    oid: oid::LOG_MZ_COMPUTE_EXPORTS_PER_WORKER_OID,
1927    variant: LogVariant::Compute(ComputeLog::DataflowCurrent),
1928    access: vec![PUBLIC_SELECT],
1929});
1930
1931pub static MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER: LazyLock<BuiltinLog> =
1932    LazyLock::new(|| BuiltinLog {
1933        name: "mz_compute_dataflow_global_ids_per_worker",
1934        schema: MZ_INTROSPECTION_SCHEMA,
1935        oid: oid::LOG_MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER_OID,
1936        variant: LogVariant::Compute(ComputeLog::DataflowGlobal),
1937        access: vec![PUBLIC_SELECT],
1938    });
1939
1940pub static MZ_CLUSTER_PROMETHEUS_METRICS: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1941    name: "mz_cluster_prometheus_metrics",
1942    schema: MZ_INTROSPECTION_SCHEMA,
1943    oid: oid::LOG_MZ_CLUSTER_PROMETHEUS_METRICS_OID,
1944    variant: LogVariant::Compute(ComputeLog::PrometheusMetrics),
1945    access: vec![PUBLIC_SELECT],
1946});
1947
1948pub static MZ_COMPUTE_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1949    name: "mz_compute_frontiers_per_worker",
1950    schema: MZ_INTROSPECTION_SCHEMA,
1951    oid: oid::LOG_MZ_COMPUTE_FRONTIERS_PER_WORKER_OID,
1952    variant: LogVariant::Compute(ComputeLog::FrontierCurrent),
1953    access: vec![PUBLIC_SELECT],
1954});
1955
1956pub static MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER: LazyLock<BuiltinLog> =
1957    LazyLock::new(|| BuiltinLog {
1958        name: "mz_compute_import_frontiers_per_worker",
1959        schema: MZ_INTROSPECTION_SCHEMA,
1960        oid: oid::LOG_MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER_OID,
1961        variant: LogVariant::Compute(ComputeLog::ImportFrontierCurrent),
1962        access: vec![PUBLIC_SELECT],
1963    });
1964
1965pub static MZ_COMPUTE_ERROR_COUNTS_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1966    name: "mz_compute_error_counts_raw",
1967    schema: MZ_INTROSPECTION_SCHEMA,
1968    oid: oid::LOG_MZ_COMPUTE_ERROR_COUNTS_RAW_OID,
1969    variant: LogVariant::Compute(ComputeLog::ErrorCount),
1970    access: vec![PUBLIC_SELECT],
1971});
1972
1973pub static MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER: LazyLock<BuiltinLog> =
1974    LazyLock::new(|| BuiltinLog {
1975        name: "mz_compute_hydration_times_per_worker",
1976        schema: MZ_INTROSPECTION_SCHEMA,
1977        oid: oid::LOG_MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER_OID,
1978        variant: LogVariant::Compute(ComputeLog::HydrationTime),
1979        access: vec![PUBLIC_SELECT],
1980    });
1981
1982pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER: LazyLock<BuiltinLog> =
1983    LazyLock::new(|| BuiltinLog {
1984        name: "mz_compute_operator_hydration_statuses_per_worker",
1985        schema: MZ_INTROSPECTION_SCHEMA,
1986        oid: oid::LOG_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER_OID,
1987        variant: LogVariant::Compute(ComputeLog::OperatorHydrationStatus),
1988        access: vec![PUBLIC_SELECT],
1989    });
1990
1991pub static MZ_ACTIVE_PEEKS_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
1992    name: "mz_active_peeks_per_worker",
1993    schema: MZ_INTROSPECTION_SCHEMA,
1994    oid: oid::LOG_MZ_ACTIVE_PEEKS_PER_WORKER_OID,
1995    variant: LogVariant::Compute(ComputeLog::PeekCurrent),
1996    access: vec![PUBLIC_SELECT],
1997});
1998
1999pub static MZ_COMPUTE_LIR_MAPPING_PER_WORKER: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2000    name: "mz_compute_lir_mapping_per_worker",
2001    schema: MZ_INTROSPECTION_SCHEMA,
2002    oid: oid::LOG_MZ_COMPUTE_LIR_MAPPING_PER_WORKER_OID,
2003    variant: LogVariant::Compute(ComputeLog::LirMapping),
2004    access: vec![PUBLIC_SELECT],
2005});
2006
2007pub static MZ_PEEK_DURATIONS_HISTOGRAM_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2008    name: "mz_peek_durations_histogram_raw",
2009    schema: MZ_INTROSPECTION_SCHEMA,
2010    oid: oid::LOG_MZ_PEEK_DURATIONS_HISTOGRAM_RAW_OID,
2011    variant: LogVariant::Compute(ComputeLog::PeekDuration),
2012    access: vec![PUBLIC_SELECT],
2013});
2014
2015pub static MZ_ARRANGEMENT_HEAP_SIZE_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2016    name: "mz_arrangement_heap_size_raw",
2017    schema: MZ_INTROSPECTION_SCHEMA,
2018    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_SIZE_RAW_OID,
2019    variant: LogVariant::Compute(ComputeLog::ArrangementHeapSize),
2020    access: vec![PUBLIC_SELECT],
2021});
2022
2023pub static MZ_ARRANGEMENT_HEAP_CAPACITY_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2024    name: "mz_arrangement_heap_capacity_raw",
2025    schema: MZ_INTROSPECTION_SCHEMA,
2026    oid: oid::LOG_MZ_ARRANGEMENT_HEAP_CAPACITY_RAW_OID,
2027    variant: LogVariant::Compute(ComputeLog::ArrangementHeapCapacity),
2028    access: vec![PUBLIC_SELECT],
2029});
2030
2031pub static MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW: LazyLock<BuiltinLog> =
2032    LazyLock::new(|| BuiltinLog {
2033        name: "mz_arrangement_heap_allocations_raw",
2034        schema: MZ_INTROSPECTION_SCHEMA,
2035        oid: oid::LOG_MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW_OID,
2036        variant: LogVariant::Compute(ComputeLog::ArrangementHeapAllocations),
2037        access: vec![PUBLIC_SELECT],
2038    });
2039
2040pub static MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> =
2041    LazyLock::new(|| BuiltinLog {
2042        name: "mz_message_batch_counts_received_raw",
2043        schema: MZ_INTROSPECTION_SCHEMA,
2044        oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW_OID,
2045        variant: LogVariant::Timely(TimelyLog::BatchesReceived),
2046        access: vec![PUBLIC_SELECT],
2047    });
2048
2049pub static MZ_MESSAGE_BATCH_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2050    name: "mz_message_batch_counts_sent_raw",
2051    schema: MZ_INTROSPECTION_SCHEMA,
2052    oid: oid::LOG_MZ_MESSAGE_BATCH_COUNTS_SENT_RAW_OID,
2053    variant: LogVariant::Timely(TimelyLog::BatchesSent),
2054    access: vec![PUBLIC_SELECT],
2055});
2056
2057pub static MZ_MESSAGE_COUNTS_RECEIVED_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2058    name: "mz_message_counts_received_raw",
2059    schema: MZ_INTROSPECTION_SCHEMA,
2060    oid: oid::LOG_MZ_MESSAGE_COUNTS_RECEIVED_RAW_OID,
2061    variant: LogVariant::Timely(TimelyLog::MessagesReceived),
2062    access: vec![PUBLIC_SELECT],
2063});
2064
2065pub static MZ_MESSAGE_COUNTS_SENT_RAW: LazyLock<BuiltinLog> = LazyLock::new(|| BuiltinLog {
2066    name: "mz_message_counts_sent_raw",
2067    schema: MZ_INTROSPECTION_SCHEMA,
2068    oid: oid::LOG_MZ_MESSAGE_COUNTS_SENT_RAW_OID,
2069    variant: LogVariant::Timely(TimelyLog::MessagesSent),
2070    access: vec![PUBLIC_SELECT],
2071});
2072
2073pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW: LazyLock<BuiltinLog> =
2074    LazyLock::new(|| BuiltinLog {
2075        name: "mz_dataflow_operator_reachability_raw",
2076        schema: MZ_INTROSPECTION_SCHEMA,
2077        oid: oid::LOG_MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW_OID,
2078        variant: LogVariant::Timely(TimelyLog::Reachability),
2079        access: vec![PUBLIC_SELECT],
2080    });
2081
2082pub static MZ_ICEBERG_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2083    name: "mz_iceberg_sinks",
2084    schema: MZ_CATALOG_SCHEMA,
2085    oid: oid::TABLE_MZ_ICEBERG_SINKS_OID,
2086    desc: RelationDesc::builder()
2087        .with_column("id", SqlScalarType::String.nullable(false))
2088        .with_column("namespace", SqlScalarType::String.nullable(false))
2089        .with_column("table", SqlScalarType::String.nullable(false))
2090        .finish(),
2091    column_comments: BTreeMap::from_iter([
2092        ("id", "The ID of the sink."),
2093        (
2094            "namespace",
2095            "The namespace of the Iceberg table into which the sink is writing.",
2096        ),
2097        ("table", "The Iceberg table into which the sink is writing."),
2098    ]),
2099    is_retained_metrics_object: false,
2100    access: vec![PUBLIC_SELECT],
2101});
2102
2103pub static MZ_KAFKA_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2104    name: "mz_kafka_sinks",
2105    schema: MZ_CATALOG_SCHEMA,
2106    oid: oid::TABLE_MZ_KAFKA_SINKS_OID,
2107    desc: RelationDesc::builder()
2108        .with_column("id", SqlScalarType::String.nullable(false))
2109        .with_column("topic", SqlScalarType::String.nullable(false))
2110        .with_key(vec![0])
2111        .finish(),
2112    column_comments: BTreeMap::from_iter([
2113        ("id", "The ID of the sink."),
2114        (
2115            "topic",
2116            "The name of the Kafka topic into which the sink is writing.",
2117        ),
2118    ]),
2119    is_retained_metrics_object: false,
2120    access: vec![PUBLIC_SELECT],
2121});
2122pub static MZ_KAFKA_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2123    name: "mz_kafka_connections",
2124    schema: MZ_CATALOG_SCHEMA,
2125    oid: oid::TABLE_MZ_KAFKA_CONNECTIONS_OID,
2126    desc: RelationDesc::builder()
2127        .with_column("id", SqlScalarType::String.nullable(false))
2128        .with_column(
2129            "brokers",
2130            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
2131        )
2132        .with_column("sink_progress_topic", SqlScalarType::String.nullable(false))
2133        .finish(),
2134    column_comments: BTreeMap::from_iter([
2135        ("id", "The ID of the connection."),
2136        (
2137            "brokers",
2138            "The addresses of the Kafka brokers to connect to.",
2139        ),
2140        (
2141            "sink_progress_topic",
2142            "The name of the Kafka topic where any sinks associated with this connection will track their progress information and other metadata. The contents of this topic are unspecified.",
2143        ),
2144    ]),
2145    is_retained_metrics_object: false,
2146    access: vec![PUBLIC_SELECT],
2147});
2148pub static MZ_KAFKA_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2149    name: "mz_kafka_sources",
2150    schema: MZ_CATALOG_SCHEMA,
2151    oid: oid::TABLE_MZ_KAFKA_SOURCES_OID,
2152    desc: RelationDesc::builder()
2153        .with_column("id", SqlScalarType::String.nullable(false))
2154        .with_column("group_id_prefix", SqlScalarType::String.nullable(false))
2155        .with_column("topic", SqlScalarType::String.nullable(false))
2156        .finish(),
2157    column_comments: BTreeMap::from_iter([
2158        (
2159            "id",
2160            "The ID of the Kafka source. Corresponds to `mz_catalog.mz_sources.id`.",
2161        ),
2162        (
2163            "group_id_prefix",
2164            "The value of the `GROUP ID PREFIX` connection option.",
2165        ),
2166        (
2167            "topic",
2168            "The name of the Kafka topic the source is reading from.",
2169        ),
2170    ]),
2171    is_retained_metrics_object: false,
2172    access: vec![PUBLIC_SELECT],
2173});
2174pub static MZ_POSTGRES_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2175    name: "mz_postgres_sources",
2176    schema: MZ_INTERNAL_SCHEMA,
2177    oid: oid::TABLE_MZ_POSTGRES_SOURCES_OID,
2178    desc: RelationDesc::builder()
2179        .with_column("id", SqlScalarType::String.nullable(false))
2180        .with_column("replication_slot", SqlScalarType::String.nullable(false))
2181        .with_column("timeline_id", SqlScalarType::UInt64.nullable(true))
2182        .finish(),
2183    column_comments: BTreeMap::from_iter([
2184        (
2185            "id",
2186            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
2187        ),
2188        (
2189            "replication_slot",
2190            "The name of the replication slot in the PostgreSQL database that Materialize will create and stream data from.",
2191        ),
2192        (
2193            "timeline_id",
2194            "The PostgreSQL timeline ID determined on source creation.",
2195        ),
2196    ]),
2197    is_retained_metrics_object: false,
2198    access: vec![PUBLIC_SELECT],
2199});
2200pub static MZ_POSTGRES_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2201    name: "mz_postgres_source_tables",
2202    schema: MZ_INTERNAL_SCHEMA,
2203    oid: oid::TABLE_MZ_POSTGRES_SOURCE_TABLES_OID,
2204    desc: RelationDesc::builder()
2205        .with_column("id", SqlScalarType::String.nullable(false))
2206        .with_column("schema_name", SqlScalarType::String.nullable(false))
2207        .with_column("table_name", SqlScalarType::String.nullable(false))
2208        .finish(),
2209    column_comments: BTreeMap::from_iter([
2210        (
2211            "id",
2212            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2213        ),
2214        (
2215            "schema_name",
2216            "The schema of the upstream table being ingested.",
2217        ),
2218        (
2219            "table_name",
2220            "The name of the upstream table being ingested.",
2221        ),
2222    ]),
2223    is_retained_metrics_object: true,
2224    access: vec![PUBLIC_SELECT],
2225});
2226pub static MZ_MYSQL_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2227    name: "mz_mysql_source_tables",
2228    schema: MZ_INTERNAL_SCHEMA,
2229    oid: oid::TABLE_MZ_MYSQL_SOURCE_TABLES_OID,
2230    desc: RelationDesc::builder()
2231        .with_column("id", SqlScalarType::String.nullable(false))
2232        .with_column("schema_name", SqlScalarType::String.nullable(false))
2233        .with_column("table_name", SqlScalarType::String.nullable(false))
2234        .finish(),
2235    column_comments: BTreeMap::from_iter([
2236        (
2237            "id",
2238            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2239        ),
2240        (
2241            "schema_name",
2242            "The schema (or, database) of the upstream table being ingested.",
2243        ),
2244        (
2245            "table_name",
2246            "The name of the upstream table being ingested.",
2247        ),
2248    ]),
2249    is_retained_metrics_object: true,
2250    access: vec![PUBLIC_SELECT],
2251});
2252pub static MZ_SQL_SERVER_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2253    name: "mz_sql_server_source_tables",
2254    schema: MZ_INTERNAL_SCHEMA,
2255    oid: oid::TABLE_MZ_SQL_SERVER_SOURCE_TABLES_OID,
2256    desc: RelationDesc::builder()
2257        .with_column("id", SqlScalarType::String.nullable(false))
2258        .with_column("schema_name", SqlScalarType::String.nullable(false))
2259        .with_column("table_name", SqlScalarType::String.nullable(false))
2260        .finish(),
2261    column_comments: BTreeMap::from_iter([
2262        (
2263            "id",
2264            "The ID of the subsource or table. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id`.",
2265        ),
2266        (
2267            "schema_name",
2268            "The schema of the upstream table being ingested.",
2269        ),
2270        (
2271            "table_name",
2272            "The name of the upstream table being ingested.",
2273        ),
2274    ]),
2275    is_retained_metrics_object: true,
2276    access: vec![PUBLIC_SELECT],
2277});
2278pub static MZ_KAFKA_SOURCE_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2279    name: "mz_kafka_source_tables",
2280    schema: MZ_INTERNAL_SCHEMA,
2281    oid: oid::TABLE_MZ_KAFKA_SOURCE_TABLES_OID,
2282    desc: RelationDesc::builder()
2283        .with_column("id", SqlScalarType::String.nullable(false))
2284        .with_column("topic", SqlScalarType::String.nullable(false))
2285        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2286        .with_column("key_format", SqlScalarType::String.nullable(true))
2287        .with_column("value_format", SqlScalarType::String.nullable(true))
2288        .finish(),
2289    column_comments: BTreeMap::from_iter([
2290        (
2291            "id",
2292            "The ID of the table. Corresponds to `mz_catalog.mz_tables.id`.",
2293        ),
2294        ("topic", "The topic being ingested."),
2295        (
2296            "envelope_type",
2297            "The envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2298        ),
2299        (
2300            "key_format",
2301            "The format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2302        ),
2303        (
2304            "value_format",
2305            "The format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2306        ),
2307    ]),
2308    is_retained_metrics_object: true,
2309    access: vec![PUBLIC_SELECT],
2310});
2311pub static MZ_OBJECT_DEPENDENCIES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2312    name: "mz_object_dependencies",
2313    schema: MZ_INTERNAL_SCHEMA,
2314    oid: oid::TABLE_MZ_OBJECT_DEPENDENCIES_OID,
2315    desc: RelationDesc::builder()
2316        .with_column("object_id", SqlScalarType::String.nullable(false))
2317        .with_column(
2318            "referenced_object_id",
2319            SqlScalarType::String.nullable(false),
2320        )
2321        .finish(),
2322    column_comments: BTreeMap::from_iter([
2323        (
2324            "object_id",
2325            "The ID of the dependent object. Corresponds to `mz_objects.id`.",
2326        ),
2327        (
2328            "referenced_object_id",
2329            "The ID of the referenced object. Corresponds to `mz_objects.id`.",
2330        ),
2331    ]),
2332    is_retained_metrics_object: true,
2333    access: vec![PUBLIC_SELECT],
2334});
2335pub static MZ_COMPUTE_DEPENDENCIES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
2336    name: "mz_compute_dependencies",
2337    schema: MZ_INTERNAL_SCHEMA,
2338    oid: oid::SOURCE_MZ_COMPUTE_DEPENDENCIES_OID,
2339    data_source: IntrospectionType::ComputeDependencies.into(),
2340    desc: RelationDesc::builder()
2341        .with_column("object_id", SqlScalarType::String.nullable(false))
2342        .with_column("dependency_id", SqlScalarType::String.nullable(false))
2343        .finish(),
2344    column_comments: BTreeMap::from_iter([
2345        (
2346            "object_id",
2347            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions`.",
2348        ),
2349        (
2350            "dependency_id",
2351            "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`.",
2352        ),
2353    ]),
2354    is_retained_metrics_object: false,
2355    access: vec![PUBLIC_SELECT],
2356});
2357
2358pub static MZ_DATABASES: LazyLock<BuiltinMaterializedView> =
2359    LazyLock::new(|| BuiltinMaterializedView {
2360        name: "mz_databases",
2361        schema: MZ_CATALOG_SCHEMA,
2362        oid: oid::MV_MZ_DATABASES_OID,
2363        desc: RelationDesc::builder()
2364            .with_column("id", SqlScalarType::String.nullable(false))
2365            .with_column("oid", SqlScalarType::Oid.nullable(false))
2366            .with_column("name", SqlScalarType::String.nullable(false))
2367            .with_column("owner_id", SqlScalarType::String.nullable(false))
2368            .with_column(
2369                "privileges",
2370                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2371            )
2372            .with_key(vec![0])
2373            .with_key(vec![1])
2374            .finish(),
2375        column_comments: BTreeMap::from_iter([
2376            ("id", "Materialize's unique ID for the database."),
2377            ("oid", "A PostgreSQL-compatible OID for the database."),
2378            ("name", "The name of the database."),
2379            (
2380                "owner_id",
2381                "The role ID of the owner of the database. Corresponds to `mz_roles.id`.",
2382            ),
2383            ("privileges", "The privileges belonging to the database."),
2384        ]),
2385        sql: "
2386IN CLUSTER mz_catalog_server
2387WITH (
2388    ASSERT NOT NULL id,
2389    ASSERT NOT NULL oid,
2390    ASSERT NOT NULL name,
2391    ASSERT NOT NULL owner_id,
2392    ASSERT NOT NULL privileges
2393) AS
2394SELECT
2395    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
2396    (data->'value'->>'oid')::oid AS oid,
2397    data->'value'->>'name' AS name,
2398    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2399    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges
2400FROM mz_internal.mz_catalog_raw
2401WHERE data->>'kind' = 'Database'",
2402        is_retained_metrics_object: false,
2403        access: vec![PUBLIC_SELECT],
2404    });
2405
2406pub static MZ_SCHEMAS: LazyLock<BuiltinMaterializedView> =
2407    LazyLock::new(|| BuiltinMaterializedView {
2408        name: "mz_schemas",
2409        schema: MZ_CATALOG_SCHEMA,
2410        oid: oid::MV_MZ_SCHEMAS_OID,
2411        desc: RelationDesc::builder()
2412            .with_column("id", SqlScalarType::String.nullable(false))
2413            .with_column("oid", SqlScalarType::Oid.nullable(false))
2414            .with_column("database_id", SqlScalarType::String.nullable(true))
2415            .with_column("name", SqlScalarType::String.nullable(false))
2416            .with_column("owner_id", SqlScalarType::String.nullable(false))
2417            .with_column(
2418                "privileges",
2419                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2420            )
2421            .with_key(vec![0])
2422            .with_key(vec![1])
2423            .finish(),
2424        column_comments: BTreeMap::from_iter([
2425            ("id", "Materialize's unique ID for the schema."),
2426            ("oid", "A PostgreSQL-compatible oid for the schema."),
2427            (
2428                "database_id",
2429                "The ID of the database containing the schema. Corresponds to `mz_databases.id`.",
2430            ),
2431            ("name", "The name of the schema."),
2432            (
2433                "owner_id",
2434                "The role ID of the owner of the schema. Corresponds to `mz_roles.id`.",
2435            ),
2436            ("privileges", "The privileges belonging to the schema."),
2437        ]),
2438        sql: "
2439IN CLUSTER mz_catalog_server
2440WITH (
2441    ASSERT NOT NULL id,
2442    ASSERT NOT NULL oid,
2443    ASSERT NOT NULL name,
2444    ASSERT NOT NULL owner_id,
2445    ASSERT NOT NULL privileges
2446) AS
2447SELECT
2448    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
2449    (data->'value'->>'oid')::oid AS oid,
2450    CASE WHEN data->'value'->'database_id' != 'null'
2451         THEN mz_internal.parse_catalog_id(data->'value'->'database_id')
2452    END AS database_id,
2453    data->'value'->>'name' AS name,
2454    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2455    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges
2456FROM mz_internal.mz_catalog_raw
2457WHERE data->>'kind' = 'Schema'",
2458        is_retained_metrics_object: false,
2459        access: vec![PUBLIC_SELECT],
2460    });
2461
2462pub static MZ_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2463    name: "mz_columns",
2464    schema: MZ_CATALOG_SCHEMA,
2465    oid: oid::TABLE_MZ_COLUMNS_OID,
2466    desc: RelationDesc::builder()
2467        .with_column("id", SqlScalarType::String.nullable(false)) // not a key
2468        .with_column("name", SqlScalarType::String.nullable(false))
2469        .with_column("position", SqlScalarType::UInt64.nullable(false))
2470        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2471        .with_column("type", SqlScalarType::String.nullable(false))
2472        .with_column("default", SqlScalarType::String.nullable(true))
2473        .with_column("type_oid", SqlScalarType::Oid.nullable(false))
2474        .with_column("type_mod", SqlScalarType::Int32.nullable(false))
2475        .finish(),
2476    column_comments: BTreeMap::from_iter([
2477        (
2478            "id",
2479            "The unique ID of the table, source, or view containing the column.",
2480        ),
2481        ("name", "The name of the column."),
2482        (
2483            "position",
2484            "The 1-indexed position of the column in its containing table, source, or view.",
2485        ),
2486        ("nullable", "Can the column contain a `NULL` value?"),
2487        ("type", "The data type of the column."),
2488        ("default", "The default expression of the column."),
2489        (
2490            "type_oid",
2491            "The OID of the type of the column (references `mz_types`).",
2492        ),
2493        ("type_mod", "The packed type identifier of the column."),
2494    ]),
2495    is_retained_metrics_object: false,
2496    access: vec![PUBLIC_SELECT],
2497});
2498pub static MZ_INDEXES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2499    name: "mz_indexes",
2500    schema: MZ_CATALOG_SCHEMA,
2501    oid: oid::TABLE_MZ_INDEXES_OID,
2502    desc: RelationDesc::builder()
2503        .with_column("id", SqlScalarType::String.nullable(false))
2504        .with_column("oid", SqlScalarType::Oid.nullable(false))
2505        .with_column("name", SqlScalarType::String.nullable(false))
2506        .with_column("on_id", SqlScalarType::String.nullable(false))
2507        .with_column("cluster_id", SqlScalarType::String.nullable(false))
2508        .with_column("owner_id", SqlScalarType::String.nullable(false))
2509        .with_column("create_sql", SqlScalarType::String.nullable(false))
2510        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2511        .with_key(vec![0])
2512        .with_key(vec![1])
2513        .finish(),
2514    column_comments: BTreeMap::from_iter([
2515        ("id", "Materialize's unique ID for the index."),
2516        ("oid", "A PostgreSQL-compatible OID for the index."),
2517        ("name", "The name of the index."),
2518        (
2519            "on_id",
2520            "The ID of the relation on which the index is built.",
2521        ),
2522        (
2523            "cluster_id",
2524            "The ID of the cluster in which the index is built.",
2525        ),
2526        (
2527            "owner_id",
2528            "The role ID of the owner of the index. Corresponds to `mz_roles.id`.",
2529        ),
2530        ("create_sql", "The `CREATE` SQL statement for the index."),
2531        (
2532            "redacted_create_sql",
2533            "The redacted `CREATE` SQL statement for the index.",
2534        ),
2535    ]),
2536    is_retained_metrics_object: false,
2537    access: vec![PUBLIC_SELECT],
2538});
2539pub static MZ_INDEX_COLUMNS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2540    name: "mz_index_columns",
2541    schema: MZ_CATALOG_SCHEMA,
2542    oid: oid::TABLE_MZ_INDEX_COLUMNS_OID,
2543    desc: RelationDesc::builder()
2544        .with_column("index_id", SqlScalarType::String.nullable(false))
2545        .with_column("index_position", SqlScalarType::UInt64.nullable(false))
2546        .with_column("on_position", SqlScalarType::UInt64.nullable(true))
2547        .with_column("on_expression", SqlScalarType::String.nullable(true))
2548        .with_column("nullable", SqlScalarType::Bool.nullable(false))
2549        .finish(),
2550    column_comments: BTreeMap::from_iter([
2551        (
2552            "index_id",
2553            "The ID of the index which contains this column. Corresponds to `mz_indexes.id`.",
2554        ),
2555        (
2556            "index_position",
2557            "The 1-indexed position of this column within the index. (The order of columns in an index does not necessarily match the order of columns in the relation on which the index is built.)",
2558        ),
2559        (
2560            "on_position",
2561            "If not `NULL`, specifies the 1-indexed position of a column in the relation on which this index is built that determines the value of this index column.",
2562        ),
2563        (
2564            "on_expression",
2565            "If not `NULL`, specifies a SQL expression that is evaluated to compute the value of this index column. The expression may contain references to any of the columns of the relation.",
2566        ),
2567        (
2568            "nullable",
2569            "Can this column of the index evaluate to `NULL`?",
2570        ),
2571    ]),
2572    is_retained_metrics_object: false,
2573    access: vec![PUBLIC_SELECT],
2574});
2575pub static MZ_TABLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2576    name: "mz_tables",
2577    schema: MZ_CATALOG_SCHEMA,
2578    oid: oid::TABLE_MZ_TABLES_OID,
2579    desc: RelationDesc::builder()
2580        .with_column("id", SqlScalarType::String.nullable(false))
2581        .with_column("oid", SqlScalarType::Oid.nullable(false))
2582        .with_column("schema_id", SqlScalarType::String.nullable(false))
2583        .with_column("name", SqlScalarType::String.nullable(false))
2584        .with_column("owner_id", SqlScalarType::String.nullable(false))
2585        .with_column(
2586            "privileges",
2587            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2588        )
2589        .with_column("create_sql", SqlScalarType::String.nullable(true))
2590        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2591        .with_column("source_id", SqlScalarType::String.nullable(true))
2592        .with_key(vec![0])
2593        .with_key(vec![1])
2594        .finish(),
2595    column_comments: BTreeMap::from_iter([
2596        ("id", "Materialize's unique ID for the table."),
2597        ("oid", "A PostgreSQL-compatible OID for the table."),
2598        (
2599            "schema_id",
2600            "The ID of the schema to which the table belongs. Corresponds to `mz_schemas.id`.",
2601        ),
2602        ("name", "The name of the table."),
2603        (
2604            "owner_id",
2605            "The role ID of the owner of the table. Corresponds to `mz_roles.id`.",
2606        ),
2607        ("privileges", "The privileges belonging to the table."),
2608        ("create_sql", "The `CREATE` SQL statement for the table."),
2609        (
2610            "redacted_create_sql",
2611            "The redacted `CREATE` SQL statement for the table.",
2612        ),
2613        (
2614            "source_id",
2615            "The ID of the source associated with the table, if any. Corresponds to `mz_sources.id`.",
2616        ),
2617    ]),
2618    is_retained_metrics_object: true,
2619    access: vec![PUBLIC_SELECT],
2620});
2621
2622pub static MZ_CONNECTIONS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
2623    BuiltinMaterializedView {
2624        name: "mz_connections",
2625        schema: MZ_CATALOG_SCHEMA,
2626        oid: oid::MV_MZ_CONNECTIONS_OID,
2627        desc: RelationDesc::builder()
2628            .with_column("id", SqlScalarType::String.nullable(false))
2629            .with_column("oid", SqlScalarType::Oid.nullable(false))
2630            .with_column("schema_id", SqlScalarType::String.nullable(false))
2631            .with_column("name", SqlScalarType::String.nullable(false))
2632            .with_column("type", SqlScalarType::String.nullable(false))
2633            .with_column("owner_id", SqlScalarType::String.nullable(false))
2634            .with_column(
2635                "privileges",
2636                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2637            )
2638            .with_column("create_sql", SqlScalarType::String.nullable(false))
2639            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2640            .with_key(vec![0])
2641            .with_key(vec![1])
2642            .finish(),
2643        column_comments: BTreeMap::from_iter([
2644            ("id", "The unique ID of the connection."),
2645            ("oid", "A PostgreSQL-compatible OID for the connection."),
2646            (
2647                "schema_id",
2648                "The ID of the schema to which the connection belongs. Corresponds to `mz_schemas.id`.",
2649            ),
2650            ("name", "The name of the connection."),
2651            (
2652                "type",
2653                "The type of the connection: `confluent-schema-registry`, `kafka`, `postgres`, or `ssh-tunnel`.",
2654            ),
2655            (
2656                "owner_id",
2657                "The role ID of the owner of the connection. Corresponds to `mz_roles.id`.",
2658            ),
2659            ("privileges", "The privileges belonging to the connection."),
2660            (
2661                "create_sql",
2662                "The `CREATE` SQL statement for the connection.",
2663            ),
2664            (
2665                "redacted_create_sql",
2666                "The redacted `CREATE` SQL statement for the connection.",
2667            ),
2668        ]),
2669        sql: "
2670IN CLUSTER mz_catalog_server
2671WITH (
2672    ASSERT NOT NULL id,
2673    ASSERT NOT NULL oid,
2674    ASSERT NOT NULL schema_id,
2675    ASSERT NOT NULL name,
2676    ASSERT NOT NULL type,
2677    ASSERT NOT NULL owner_id,
2678    ASSERT NOT NULL privileges,
2679    ASSERT NOT NULL create_sql,
2680    ASSERT NOT NULL redacted_create_sql
2681) AS
2682SELECT
2683    mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
2684    (data->'value'->>'oid')::oid AS oid,
2685    mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,
2686    data->'value'->>'name' AS name,
2687    mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'connection_type' AS type,
2688    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2689    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
2690    data->'value'->'definition'->'V1'->>'create_sql' AS create_sql,
2691    mz_internal.redact_sql(data->'value'->'definition'->'V1'->>'create_sql') AS redacted_create_sql
2692FROM mz_internal.mz_catalog_raw
2693WHERE
2694    data->>'kind' = 'Item' AND
2695    mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'type' = 'connection'",
2696        is_retained_metrics_object: false,
2697        access: vec![PUBLIC_SELECT],
2698    }
2699});
2700
2701pub static MZ_SSH_TUNNEL_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2702    name: "mz_ssh_tunnel_connections",
2703    schema: MZ_CATALOG_SCHEMA,
2704    oid: oid::TABLE_MZ_SSH_TUNNEL_CONNECTIONS_OID,
2705    desc: RelationDesc::builder()
2706        .with_column("id", SqlScalarType::String.nullable(false))
2707        .with_column("public_key_1", SqlScalarType::String.nullable(false))
2708        .with_column("public_key_2", SqlScalarType::String.nullable(false))
2709        .finish(),
2710    column_comments: BTreeMap::from_iter([
2711        ("id", "The ID of the connection."),
2712        (
2713            "public_key_1",
2714            "The first public key associated with the SSH tunnel.",
2715        ),
2716        (
2717            "public_key_2",
2718            "The second public key associated with the SSH tunnel.",
2719        ),
2720    ]),
2721    is_retained_metrics_object: false,
2722    access: vec![PUBLIC_SELECT],
2723});
2724pub static MZ_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2725    name: "mz_sources",
2726    schema: MZ_CATALOG_SCHEMA,
2727    oid: oid::TABLE_MZ_SOURCES_OID,
2728    desc: RelationDesc::builder()
2729        .with_column("id", SqlScalarType::String.nullable(false))
2730        .with_column("oid", SqlScalarType::Oid.nullable(false))
2731        .with_column("schema_id", SqlScalarType::String.nullable(false))
2732        .with_column("name", SqlScalarType::String.nullable(false))
2733        .with_column("type", SqlScalarType::String.nullable(false))
2734        .with_column("connection_id", SqlScalarType::String.nullable(true))
2735        .with_column("size", SqlScalarType::String.nullable(true))
2736        .with_column("envelope_type", SqlScalarType::String.nullable(true))
2737        .with_column("key_format", SqlScalarType::String.nullable(true))
2738        .with_column("value_format", SqlScalarType::String.nullable(true))
2739        .with_column("cluster_id", SqlScalarType::String.nullable(true))
2740        .with_column("owner_id", SqlScalarType::String.nullable(false))
2741        .with_column(
2742            "privileges",
2743            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2744        )
2745        .with_column("create_sql", SqlScalarType::String.nullable(true))
2746        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
2747        .with_key(vec![0])
2748        .with_key(vec![1])
2749        .finish(),
2750    column_comments: BTreeMap::from_iter([
2751        ("id", "Materialize's unique ID for the source."),
2752        ("oid", "A PostgreSQL-compatible OID for the source."),
2753        (
2754            "schema_id",
2755            "The ID of the schema to which the source belongs. Corresponds to `mz_schemas.id`.",
2756        ),
2757        ("name", "The name of the source."),
2758        (
2759            "type",
2760            "The type of the source: `kafka`, `mysql`, `postgres`, `load-generator`, `progress`, or `subsource`.",
2761        ),
2762        (
2763            "connection_id",
2764            "The ID of the connection associated with the source, if any. Corresponds to `mz_connections.id`.",
2765        ),
2766        ("size", "*Deprecated* The size of the source."),
2767        (
2768            "envelope_type",
2769            "For Kafka sources, the envelope type: `none`, `upsert`, or `debezium`. `NULL` for other source types.",
2770        ),
2771        (
2772            "key_format",
2773            "For Kafka sources, the format of the Kafka message key: `avro`, `csv`, `regex`, `bytes`, `json`, `text`, or `NULL`.",
2774        ),
2775        (
2776            "value_format",
2777            "For Kafka sources, the format of the Kafka message value: `avro`, `csv`, `regex`, `bytes`, `json`, `text`. `NULL` for other source types.",
2778        ),
2779        (
2780            "cluster_id",
2781            "The ID of the cluster maintaining the source. Corresponds to `mz_clusters.id`.",
2782        ),
2783        (
2784            "owner_id",
2785            "The role ID of the owner of the source. Corresponds to `mz_roles.id`.",
2786        ),
2787        ("privileges", "The privileges granted on the source."),
2788        ("create_sql", "The `CREATE` SQL statement for the source."),
2789        (
2790            "redacted_create_sql",
2791            "The redacted `CREATE` SQL statement for the source.",
2792        ),
2793    ]),
2794    is_retained_metrics_object: true,
2795    access: vec![PUBLIC_SELECT],
2796});
2797pub static MZ_SINKS: LazyLock<BuiltinTable> = LazyLock::new(|| {
2798    BuiltinTable {
2799        name: "mz_sinks",
2800        schema: MZ_CATALOG_SCHEMA,
2801        oid: oid::TABLE_MZ_SINKS_OID,
2802        desc: RelationDesc::builder()
2803            .with_column("id", SqlScalarType::String.nullable(false))
2804            .with_column("oid", SqlScalarType::Oid.nullable(false))
2805            .with_column("schema_id", SqlScalarType::String.nullable(false))
2806            .with_column("name", SqlScalarType::String.nullable(false))
2807            .with_column("type", SqlScalarType::String.nullable(false))
2808            .with_column("connection_id", SqlScalarType::String.nullable(true))
2809            .with_column("size", SqlScalarType::String.nullable(true))
2810            .with_column("envelope_type", SqlScalarType::String.nullable(true))
2811            // This `format` column is deprecated and replaced by the `key_format` and `value_format` columns
2812            // below. This should be removed in the future.
2813            .with_column("format", SqlScalarType::String.nullable(true))
2814            .with_column("key_format", SqlScalarType::String.nullable(true))
2815            .with_column("value_format", SqlScalarType::String.nullable(true))
2816            .with_column("cluster_id", SqlScalarType::String.nullable(false))
2817            .with_column("owner_id", SqlScalarType::String.nullable(false))
2818            .with_column("create_sql", SqlScalarType::String.nullable(false))
2819            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2820            .with_key(vec![0])
2821            .with_key(vec![1])
2822            .finish(),
2823        column_comments: BTreeMap::from_iter([
2824            ("id", "Materialize's unique ID for the sink."),
2825            ("oid", "A PostgreSQL-compatible OID for the sink."),
2826            (
2827                "schema_id",
2828                "The ID of the schema to which the sink belongs. Corresponds to `mz_schemas.id`.",
2829            ),
2830            ("name", "The name of the sink."),
2831            ("type", "The type of the sink: `kafka`."),
2832            (
2833                "connection_id",
2834                "The ID of the connection associated with the sink, if any. Corresponds to `mz_connections.id`.",
2835            ),
2836            ("size", "The size of the sink."),
2837            (
2838                "envelope_type",
2839                "The envelope of the sink: `upsert`, or `debezium`.",
2840            ),
2841            (
2842                "format",
2843                "*Deprecated* The format of the Kafka messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2844            ),
2845            (
2846                "key_format",
2847                "The format of the Kafka message key for messages produced by the sink: `avro`, `json`, `bytes`, `text`, or `NULL`.",
2848            ),
2849            (
2850                "value_format",
2851                "The format of the Kafka message value for messages produced by the sink: `avro`, `json`, `text`, or `bytes`.",
2852            ),
2853            (
2854                "cluster_id",
2855                "The ID of the cluster maintaining the sink. Corresponds to `mz_clusters.id`.",
2856            ),
2857            (
2858                "owner_id",
2859                "The role ID of the owner of the sink. Corresponds to `mz_roles.id`.",
2860            ),
2861            ("create_sql", "The `CREATE` SQL statement for the sink."),
2862            (
2863                "redacted_create_sql",
2864                "The redacted `CREATE` SQL statement for the sink.",
2865            ),
2866        ]),
2867        is_retained_metrics_object: true,
2868        access: vec![PUBLIC_SELECT],
2869    }
2870});
2871pub static MZ_VIEWS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
2872    name: "mz_views",
2873    schema: MZ_CATALOG_SCHEMA,
2874    oid: oid::TABLE_MZ_VIEWS_OID,
2875    desc: RelationDesc::builder()
2876        .with_column("id", SqlScalarType::String.nullable(false))
2877        .with_column("oid", SqlScalarType::Oid.nullable(false))
2878        .with_column("schema_id", SqlScalarType::String.nullable(false))
2879        .with_column("name", SqlScalarType::String.nullable(false))
2880        .with_column("definition", SqlScalarType::String.nullable(false))
2881        .with_column("owner_id", SqlScalarType::String.nullable(false))
2882        .with_column(
2883            "privileges",
2884            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2885        )
2886        .with_column("create_sql", SqlScalarType::String.nullable(false))
2887        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2888        .with_key(vec![0])
2889        .with_key(vec![1])
2890        .finish(),
2891    column_comments: BTreeMap::from_iter([
2892        ("id", "Materialize's unique ID for the view."),
2893        ("oid", "A PostgreSQL-compatible OID for the view."),
2894        (
2895            "schema_id",
2896            "The ID of the schema to which the view belongs. Corresponds to `mz_schemas.id`.",
2897        ),
2898        ("name", "The name of the view."),
2899        ("definition", "The view definition (a `SELECT` query)."),
2900        (
2901            "owner_id",
2902            "The role ID of the owner of the view. Corresponds to `mz_roles.id`.",
2903        ),
2904        ("privileges", "The privileges belonging to the view."),
2905        ("create_sql", "The `CREATE` SQL statement for the view."),
2906        (
2907            "redacted_create_sql",
2908            "The redacted `CREATE` SQL statement for the view.",
2909        ),
2910    ]),
2911    is_retained_metrics_object: false,
2912    access: vec![PUBLIC_SELECT],
2913});
2914
2915pub static MZ_MATERIALIZED_VIEWS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
2916    BuiltinMaterializedView {
2917        name: "mz_materialized_views",
2918        schema: MZ_CATALOG_SCHEMA,
2919        oid: oid::MV_MZ_MATERIALIZED_VIEWS_OID,
2920        desc: RelationDesc::builder()
2921            .with_column("id", SqlScalarType::String.nullable(false))
2922            .with_column("oid", SqlScalarType::Oid.nullable(false))
2923            .with_column("schema_id", SqlScalarType::String.nullable(false))
2924            .with_column("name", SqlScalarType::String.nullable(false))
2925            .with_column("cluster_id", SqlScalarType::String.nullable(false))
2926            .with_column("definition", SqlScalarType::String.nullable(false))
2927            .with_column("owner_id", SqlScalarType::String.nullable(false))
2928            .with_column(
2929                "privileges",
2930                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
2931            )
2932            .with_column("create_sql", SqlScalarType::String.nullable(false))
2933            .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
2934            .with_key(vec![0])
2935            .with_key(vec![1])
2936            .finish(),
2937        column_comments: BTreeMap::from_iter([
2938            ("id", "Materialize's unique ID for the materialized view."),
2939            (
2940                "oid",
2941                "A PostgreSQL-compatible OID for the materialized view.",
2942            ),
2943            (
2944                "schema_id",
2945                "The ID of the schema to which the materialized view belongs. Corresponds to `mz_schemas.id`.",
2946            ),
2947            ("name", "The name of the materialized view."),
2948            (
2949                "cluster_id",
2950                "The ID of the cluster maintaining the materialized view. Corresponds to `mz_clusters.id`.",
2951            ),
2952            (
2953                "definition",
2954                "The materialized view definition (a `SELECT` query).",
2955            ),
2956            (
2957                "owner_id",
2958                "The role ID of the owner of the materialized view. Corresponds to `mz_roles.id`.",
2959            ),
2960            (
2961                "privileges",
2962                "The privileges belonging to the materialized view.",
2963            ),
2964            (
2965                "create_sql",
2966                "The `CREATE` SQL statement for the materialized view.",
2967            ),
2968            (
2969                "redacted_create_sql",
2970                "The redacted `CREATE` SQL statement for the materialized view.",
2971            ),
2972        ]),
2973        sql: Box::leak(format!("
2974IN CLUSTER mz_catalog_server
2975WITH (
2976    ASSERT NOT NULL id,
2977    ASSERT NOT NULL oid,
2978    ASSERT NOT NULL schema_id,
2979    ASSERT NOT NULL name,
2980    ASSERT NOT NULL cluster_id,
2981    ASSERT NOT NULL definition,
2982    ASSERT NOT NULL owner_id,
2983    ASSERT NOT NULL privileges,
2984    ASSERT NOT NULL create_sql,
2985    ASSERT NOT NULL redacted_create_sql
2986) AS
2987WITH
2988    user_mvs AS (
2989        SELECT
2990            mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
2991            (data->'value'->>'oid')::oid AS oid,
2992            mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,
2993            data->'value'->>'name' AS name,
2994            mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'cluster_id' AS cluster_id,
2995            mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'definition' AS definition,
2996            mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
2997            mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
2998            data->'value'->'definition'->'V1'->>'create_sql' AS create_sql,
2999            mz_internal.redact_sql(data->'value'->'definition'->'V1'->>'create_sql') AS redacted_create_sql
3000        FROM mz_internal.mz_catalog_raw
3001        WHERE
3002            data->>'kind' = 'Item' AND
3003            mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'type' = 'materialized-view'
3004    ),
3005    builtin_mappings AS (
3006        SELECT
3007            data->'key'->>'schema_name' AS schema_name,
3008            data->'key'->>'object_name' AS name,
3009            's' || (data->'value'->>'catalog_id') AS id
3010        FROM mz_internal.mz_catalog_raw
3011        WHERE
3012            data->>'kind' = 'GidMapping' AND
3013            data->'key'->>'object_type' = '5'
3014    ),
3015    builtin_mvs AS (
3016        SELECT
3017            m.id,
3018            mv.oid,
3019            s.id AS schema_id,
3020            mv.name,
3021            c.id AS cluster_id,
3022            mv.definition,
3023            '{MZ_SYSTEM_ROLE_ID}' AS owner_id,
3024            mv.privileges,
3025            mv.create_sql,
3026            mz_internal.redact_sql(mv.create_sql) AS redacted_create_sql
3027        FROM mz_internal.mz_builtin_materialized_views mv
3028        JOIN builtin_mappings m USING (schema_name, name)
3029        JOIN mz_schemas s ON s.name = mv.schema_name
3030        JOIN mz_clusters c ON c.name = mv.cluster_name
3031        WHERE s.database_id IS NULL
3032    )
3033SELECT * FROM user_mvs
3034UNION ALL
3035SELECT * FROM builtin_mvs").into_boxed_str()),
3036        is_retained_metrics_object: false,
3037        access: vec![PUBLIC_SELECT],
3038    }
3039});
3040
3041pub static MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
3042    BuiltinTable {
3043        name: "mz_materialized_view_refresh_strategies",
3044        schema: MZ_INTERNAL_SCHEMA,
3045        oid: oid::TABLE_MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES_OID,
3046        desc: RelationDesc::builder()
3047            .with_column(
3048                "materialized_view_id",
3049                SqlScalarType::String.nullable(false),
3050            )
3051            .with_column("type", SqlScalarType::String.nullable(false))
3052            .with_column("interval", SqlScalarType::Interval.nullable(true))
3053            .with_column(
3054                "aligned_to",
3055                SqlScalarType::TimestampTz { precision: None }.nullable(true),
3056            )
3057            .with_column(
3058                "at",
3059                SqlScalarType::TimestampTz { precision: None }.nullable(true),
3060            )
3061            .finish(),
3062        column_comments: BTreeMap::from_iter([
3063            (
3064                "materialized_view_id",
3065                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
3066            ),
3067            (
3068                "type",
3069                "`at`, `every`, or `on-commit`. Default: `on-commit`",
3070            ),
3071            (
3072                "interval",
3073                "The refresh interval of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
3074            ),
3075            (
3076                "aligned_to",
3077                "The `ALIGNED TO` option of a `REFRESH EVERY` option, or `NULL` if the `type` is not `every`.",
3078            ),
3079            (
3080                "at",
3081                "The time of a `REFRESH AT`, or `NULL` if the `type` is not `at`.",
3082            ),
3083        ]),
3084        is_retained_metrics_object: false,
3085        access: vec![PUBLIC_SELECT],
3086    }
3087});
3088pub static MZ_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3089    name: "mz_types",
3090    schema: MZ_CATALOG_SCHEMA,
3091    oid: oid::TABLE_MZ_TYPES_OID,
3092    desc: RelationDesc::builder()
3093        .with_column("id", SqlScalarType::String.nullable(false))
3094        .with_column("oid", SqlScalarType::Oid.nullable(false))
3095        .with_column("schema_id", SqlScalarType::String.nullable(false))
3096        .with_column("name", SqlScalarType::String.nullable(false))
3097        .with_column("category", SqlScalarType::String.nullable(false))
3098        .with_column("owner_id", SqlScalarType::String.nullable(false))
3099        .with_column(
3100            "privileges",
3101            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3102        )
3103        .with_column("create_sql", SqlScalarType::String.nullable(true))
3104        .with_column("redacted_create_sql", SqlScalarType::String.nullable(true))
3105        .with_key(vec![0])
3106        .with_key(vec![1])
3107        .finish(),
3108    column_comments: BTreeMap::from_iter([
3109        ("id", "Materialize's unique ID for the type."),
3110        ("oid", "A PostgreSQL-compatible OID for the type."),
3111        (
3112            "schema_id",
3113            "The ID of the schema to which the type belongs. Corresponds to `mz_schemas.id`.",
3114        ),
3115        ("name", "The name of the type."),
3116        ("category", "The category of the type."),
3117        (
3118            "owner_id",
3119            "The role ID of the owner of the type. Corresponds to `mz_roles.id`.",
3120        ),
3121        ("privileges", "The privileges belonging to the type."),
3122        ("create_sql", "The `CREATE` SQL statement for the type."),
3123        (
3124            "redacted_create_sql",
3125            "The redacted `CREATE` SQL statement for the type.",
3126        ),
3127    ]),
3128    is_retained_metrics_object: false,
3129    access: vec![PUBLIC_SELECT],
3130});
3131pub static MZ_CONTINUAL_TASKS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3132    name: "mz_continual_tasks",
3133    schema: MZ_INTERNAL_SCHEMA,
3134    oid: oid::TABLE_MZ_CONTINUAL_TASKS_OID,
3135    desc: RelationDesc::builder()
3136        .with_column("id", SqlScalarType::String.nullable(false))
3137        .with_column("oid", SqlScalarType::Oid.nullable(false))
3138        .with_column("schema_id", SqlScalarType::String.nullable(false))
3139        .with_column("name", SqlScalarType::String.nullable(false))
3140        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3141        .with_column("definition", SqlScalarType::String.nullable(false))
3142        .with_column("owner_id", SqlScalarType::String.nullable(false))
3143        .with_column(
3144            "privileges",
3145            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3146        )
3147        .with_column("create_sql", SqlScalarType::String.nullable(false))
3148        .with_column("redacted_create_sql", SqlScalarType::String.nullable(false))
3149        .with_key(vec![0])
3150        .with_key(vec![1])
3151        .finish(),
3152    column_comments: BTreeMap::new(),
3153    is_retained_metrics_object: false,
3154    access: vec![PUBLIC_SELECT],
3155});
3156
3157pub static MZ_NETWORK_POLICIES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3158    BuiltinMaterializedView {
3159        name: "mz_network_policies",
3160        schema: MZ_INTERNAL_SCHEMA,
3161        oid: oid::MV_MZ_NETWORK_POLICIES_OID,
3162        desc: RelationDesc::builder()
3163            .with_column("id", SqlScalarType::String.nullable(false))
3164            .with_column("name", SqlScalarType::String.nullable(false))
3165            .with_column("owner_id", SqlScalarType::String.nullable(false))
3166            .with_column(
3167                "privileges",
3168                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3169            )
3170            .with_column("oid", SqlScalarType::Oid.nullable(false))
3171            .with_key(vec![0])
3172            .with_key(vec![4])
3173            .finish(),
3174        column_comments: BTreeMap::from_iter([
3175            ("id", "The ID of the network policy."),
3176            ("name", "The name of the network policy."),
3177            (
3178                "owner_id",
3179                "The role ID of the owner of the network policy. Corresponds to `mz_catalog.mz_roles.id`.",
3180            ),
3181            (
3182                "privileges",
3183                "The privileges belonging to the network policy.",
3184            ),
3185            ("oid", "A PostgreSQL-compatible OID for the network policy."),
3186        ]),
3187        sql: "
3188IN CLUSTER mz_catalog_server
3189WITH (
3190    ASSERT NOT NULL id,
3191    ASSERT NOT NULL name,
3192    ASSERT NOT NULL owner_id,
3193    ASSERT NOT NULL privileges,
3194    ASSERT NOT NULL oid
3195) AS
3196SELECT
3197    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
3198    data->'value'->>'name' AS name,
3199    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
3200    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges,
3201    (data->'value'->>'oid')::oid AS oid
3202FROM mz_internal.mz_catalog_raw
3203WHERE data->>'kind' = 'NetworkPolicy'",
3204        is_retained_metrics_object: false,
3205        access: vec![PUBLIC_SELECT],
3206    }
3207});
3208
3209pub static MZ_NETWORK_POLICY_RULES: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3210    BuiltinMaterializedView {
3211        name: "mz_network_policy_rules",
3212        schema: MZ_INTERNAL_SCHEMA,
3213        oid: oid::MV_MZ_NETWORK_POLICY_RULES_OID,
3214        desc: RelationDesc::builder()
3215            .with_column("name", SqlScalarType::String.nullable(false))
3216            .with_column("policy_id", SqlScalarType::String.nullable(false))
3217            .with_column("action", SqlScalarType::String.nullable(false))
3218            .with_column("address", SqlScalarType::String.nullable(false))
3219            .with_column("direction", SqlScalarType::String.nullable(false))
3220            .finish(),
3221        column_comments: BTreeMap::from_iter([
3222            (
3223                "name",
3224                "The name of the network policy rule. Can be combined with `policy_id` to form a unique identifier.",
3225            ),
3226            (
3227                "policy_id",
3228                "The ID the network policy the rule is part of. Corresponds to `mz_network_policy_rules.id`.",
3229            ),
3230            (
3231                "action",
3232                "The action of the rule. `allow` is the only supported action.",
3233            ),
3234            ("address", "The address the rule will take action on."),
3235            (
3236                "direction",
3237                "The direction of traffic the rule applies to. `ingress` is the only supported direction.",
3238            ),
3239        ]),
3240        sql: "
3241IN CLUSTER mz_catalog_server
3242WITH (
3243    ASSERT NOT NULL name,
3244    ASSERT NOT NULL policy_id,
3245    ASSERT NOT NULL action,
3246    ASSERT NOT NULL address,
3247    ASSERT NOT NULL direction
3248) AS
3249SELECT
3250    rule->>'name' AS name,
3251    mz_internal.parse_catalog_id(data->'key'->'id') AS policy_id,
3252    lower(rule->>'action') AS action,
3253    rule->>'address' AS address,
3254    lower(rule->>'direction') AS direction
3255FROM
3256    mz_internal.mz_catalog_raw,
3257    jsonb_array_elements(data->'value'->'rules') AS rule
3258WHERE data->>'kind' = 'NetworkPolicy'",
3259        is_retained_metrics_object: false,
3260        access: vec![PUBLIC_SELECT],
3261    }
3262});
3263
3264/// PostgreSQL-specific metadata about types that doesn't make sense to expose
3265/// in the `mz_types` table as part of our public, stable API.
3266pub static MZ_TYPE_PG_METADATA: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3267    name: "mz_type_pg_metadata",
3268    schema: MZ_INTERNAL_SCHEMA,
3269    oid: oid::TABLE_MZ_TYPE_PG_METADATA_OID,
3270    desc: RelationDesc::builder()
3271        .with_column("id", SqlScalarType::String.nullable(false))
3272        .with_column("typinput", SqlScalarType::Oid.nullable(false))
3273        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
3274        .finish(),
3275    column_comments: BTreeMap::new(),
3276    is_retained_metrics_object: false,
3277    access: vec![PUBLIC_SELECT],
3278});
3279pub static MZ_ARRAY_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3280    name: "mz_array_types",
3281    schema: MZ_CATALOG_SCHEMA,
3282    oid: oid::TABLE_MZ_ARRAY_TYPES_OID,
3283    desc: RelationDesc::builder()
3284        .with_column("id", SqlScalarType::String.nullable(false))
3285        .with_column("element_id", SqlScalarType::String.nullable(false))
3286        .finish(),
3287    column_comments: BTreeMap::from_iter([
3288        ("id", "The ID of the array type."),
3289        ("element_id", "The ID of the array's element type."),
3290    ]),
3291    is_retained_metrics_object: false,
3292    access: vec![PUBLIC_SELECT],
3293});
3294pub static MZ_BASE_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3295    name: "mz_base_types",
3296    schema: MZ_CATALOG_SCHEMA,
3297    oid: oid::TABLE_MZ_BASE_TYPES_OID,
3298    desc: RelationDesc::builder()
3299        .with_column("id", SqlScalarType::String.nullable(false))
3300        .finish(),
3301    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3302    is_retained_metrics_object: false,
3303    access: vec![PUBLIC_SELECT],
3304});
3305pub static MZ_LIST_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3306    name: "mz_list_types",
3307    schema: MZ_CATALOG_SCHEMA,
3308    oid: oid::TABLE_MZ_LIST_TYPES_OID,
3309    desc: RelationDesc::builder()
3310        .with_column("id", SqlScalarType::String.nullable(false))
3311        .with_column("element_id", SqlScalarType::String.nullable(false))
3312        .with_column(
3313            "element_modifiers",
3314            SqlScalarType::List {
3315                element_type: Box::new(SqlScalarType::Int64),
3316                custom_id: None,
3317            }
3318            .nullable(true),
3319        )
3320        .finish(),
3321    column_comments: BTreeMap::from_iter([
3322        ("id", "The ID of the list type."),
3323        ("element_id", "The IID of the list's element type."),
3324        (
3325            "element_modifiers",
3326            "The element type modifiers, or `NULL` if none.",
3327        ),
3328    ]),
3329    is_retained_metrics_object: false,
3330    access: vec![PUBLIC_SELECT],
3331});
3332pub static MZ_MAP_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3333    name: "mz_map_types",
3334    schema: MZ_CATALOG_SCHEMA,
3335    oid: oid::TABLE_MZ_MAP_TYPES_OID,
3336    desc: RelationDesc::builder()
3337        .with_column("id", SqlScalarType::String.nullable(false))
3338        .with_column("key_id", SqlScalarType::String.nullable(false))
3339        .with_column("value_id", SqlScalarType::String.nullable(false))
3340        .with_column(
3341            "key_modifiers",
3342            SqlScalarType::List {
3343                element_type: Box::new(SqlScalarType::Int64),
3344                custom_id: None,
3345            }
3346            .nullable(true),
3347        )
3348        .with_column(
3349            "value_modifiers",
3350            SqlScalarType::List {
3351                element_type: Box::new(SqlScalarType::Int64),
3352                custom_id: None,
3353            }
3354            .nullable(true),
3355        )
3356        .finish(),
3357    column_comments: BTreeMap::from_iter([
3358        ("id", "The ID of the map type."),
3359        ("key_id", "The ID of the map's key type."),
3360        ("value_id", "The ID of the map's value type."),
3361        (
3362            "key_modifiers",
3363            "The key type modifiers, or `NULL` if none.",
3364        ),
3365        (
3366            "value_modifiers",
3367            "The value type modifiers, or `NULL` if none.",
3368        ),
3369    ]),
3370    is_retained_metrics_object: false,
3371    access: vec![PUBLIC_SELECT],
3372});
3373pub static MZ_ROLES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3374    name: "mz_roles",
3375    schema: MZ_CATALOG_SCHEMA,
3376    oid: oid::TABLE_MZ_ROLES_OID,
3377    desc: RelationDesc::builder()
3378        .with_column("id", SqlScalarType::String.nullable(false))
3379        .with_column("oid", SqlScalarType::Oid.nullable(false))
3380        .with_column("name", SqlScalarType::String.nullable(false))
3381        .with_column("inherit", SqlScalarType::Bool.nullable(false))
3382        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(true))
3383        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
3384        .with_key(vec![0])
3385        .with_key(vec![1])
3386        .finish(),
3387    column_comments: BTreeMap::from_iter([
3388        ("id", "Materialize's unique ID for the role."),
3389        ("oid", "A PostgreSQL-compatible OID for the role."),
3390        ("name", "The name of the role."),
3391        (
3392            "inherit",
3393            "Indicates whether the role has inheritance of privileges.",
3394        ),
3395        ("rolcanlogin", "Indicates whether the role can log in."),
3396        ("rolsuper", "Indicates whether the role is a superuser."),
3397    ]),
3398    is_retained_metrics_object: false,
3399    access: vec![PUBLIC_SELECT],
3400});
3401
3402pub static MZ_ROLE_MEMBERS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3403    BuiltinMaterializedView {
3404        name: "mz_role_members",
3405        schema: MZ_CATALOG_SCHEMA,
3406        oid: oid::MV_MZ_ROLE_MEMBERS_OID,
3407        desc: RelationDesc::builder()
3408            .with_column("role_id", SqlScalarType::String.nullable(false))
3409            .with_column("member", SqlScalarType::String.nullable(false))
3410            .with_column("grantor", SqlScalarType::String.nullable(false))
3411            .finish(),
3412        column_comments: BTreeMap::from_iter([
3413            (
3414                "role_id",
3415                "The ID of the role the `member` is a member of. Corresponds to `mz_roles.id`.",
3416            ),
3417            (
3418                "member",
3419                "The ID of the role that is a member of `role_id`. Corresponds to `mz_roles.id`.",
3420            ),
3421            (
3422                "grantor",
3423                "The ID of the role that granted membership of `member` to `role_id`. Corresponds to `mz_roles.id`.",
3424            ),
3425        ]),
3426        sql: "
3427IN CLUSTER mz_catalog_server
3428WITH (
3429    ASSERT NOT NULL role_id,
3430    ASSERT NOT NULL member,
3431    ASSERT NOT NULL grantor
3432) AS
3433SELECT
3434    mz_internal.parse_catalog_id(entry->'key') AS role_id,
3435    mz_internal.parse_catalog_id(data->'key'->'id') AS member,
3436    mz_internal.parse_catalog_id(entry->'value') AS grantor
3437FROM
3438    mz_internal.mz_catalog_raw,
3439    jsonb_array_elements(data->'value'->'membership'->'map') AS entry
3440WHERE data->>'kind' = 'Role'",
3441        is_retained_metrics_object: false,
3442        access: vec![PUBLIC_SELECT],
3443    }
3444});
3445
3446pub static MZ_ROLE_PARAMETERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3447    name: "mz_role_parameters",
3448    schema: MZ_CATALOG_SCHEMA,
3449    oid: oid::TABLE_MZ_ROLE_PARAMETERS_OID,
3450    desc: RelationDesc::builder()
3451        .with_column("role_id", SqlScalarType::String.nullable(false))
3452        .with_column("parameter_name", SqlScalarType::String.nullable(false))
3453        .with_column("parameter_value", SqlScalarType::String.nullable(false))
3454        .finish(),
3455    column_comments: BTreeMap::from_iter([
3456        (
3457            "role_id",
3458            "The ID of the role whose configuration parameter default is set. Corresponds to `mz_roles.id`.",
3459        ),
3460        (
3461            "parameter_name",
3462            "The configuration parameter name. One of the supported configuration parameters.",
3463        ),
3464        (
3465            "parameter_value",
3466            "The default value of the parameter for the given role. Can be either a single value, or a comma-separated list of values for configuration parameters that accept a list.",
3467        ),
3468    ]),
3469    is_retained_metrics_object: false,
3470    access: vec![PUBLIC_SELECT],
3471});
3472pub static MZ_ROLE_AUTH: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3473    name: "mz_role_auth",
3474    schema: MZ_CATALOG_SCHEMA,
3475    oid: oid::TABLE_MZ_ROLE_AUTH_OID,
3476    desc: RelationDesc::builder()
3477        .with_column("role_id", SqlScalarType::String.nullable(false))
3478        .with_column("role_oid", SqlScalarType::Oid.nullable(false))
3479        .with_column("password_hash", SqlScalarType::String.nullable(true))
3480        .with_column(
3481            "updated_at",
3482            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3483        )
3484        .finish(),
3485    column_comments: BTreeMap::from_iter([
3486        (
3487            "role_id",
3488            "The ID of the role. Corresponds to `mz_roles.id`.",
3489        ),
3490        ("role_oid", "A PostgreSQL-compatible OID for the role."),
3491        (
3492            "password_hash",
3493            "The hashed password for the role, if any. Uses the `SCRAM-SHA-256` algorithm.",
3494        ),
3495        (
3496            "updated_at",
3497            "The time at which the password was last updated.",
3498        ),
3499    ]),
3500    is_retained_metrics_object: false,
3501    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
3502});
3503pub static MZ_PSEUDO_TYPES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3504    name: "mz_pseudo_types",
3505    schema: MZ_CATALOG_SCHEMA,
3506    oid: oid::TABLE_MZ_PSEUDO_TYPES_OID,
3507    desc: RelationDesc::builder()
3508        .with_column("id", SqlScalarType::String.nullable(false))
3509        .finish(),
3510    column_comments: BTreeMap::from_iter([("id", "The ID of the type.")]),
3511    is_retained_metrics_object: false,
3512    access: vec![PUBLIC_SELECT],
3513});
3514pub static MZ_FUNCTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| {
3515    BuiltinTable {
3516        name: "mz_functions",
3517        schema: MZ_CATALOG_SCHEMA,
3518        oid: oid::TABLE_MZ_FUNCTIONS_OID,
3519        desc: RelationDesc::builder()
3520            .with_column("id", SqlScalarType::String.nullable(false)) // not a key!
3521            .with_column("oid", SqlScalarType::Oid.nullable(false))
3522            .with_column("schema_id", SqlScalarType::String.nullable(false))
3523            .with_column("name", SqlScalarType::String.nullable(false))
3524            .with_column(
3525                "argument_type_ids",
3526                SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3527            )
3528            .with_column(
3529                "variadic_argument_type_id",
3530                SqlScalarType::String.nullable(true),
3531            )
3532            .with_column("return_type_id", SqlScalarType::String.nullable(true))
3533            .with_column("returns_set", SqlScalarType::Bool.nullable(false))
3534            .with_column("owner_id", SqlScalarType::String.nullable(false))
3535            .finish(),
3536        column_comments: BTreeMap::from_iter([
3537            ("id", "Materialize's unique ID for the function."),
3538            ("oid", "A PostgreSQL-compatible OID for the function."),
3539            (
3540                "schema_id",
3541                "The ID of the schema to which the function belongs. Corresponds to `mz_schemas.id`.",
3542            ),
3543            ("name", "The name of the function."),
3544            (
3545                "argument_type_ids",
3546                "The ID of each argument's type. Each entry refers to `mz_types.id`.",
3547            ),
3548            (
3549                "variadic_argument_type_id",
3550                "The ID of the variadic argument's type, or `NULL` if the function does not have a variadic argument. Refers to `mz_types.id`.",
3551            ),
3552            (
3553                "return_type_id",
3554                "The returned value's type, or `NULL` if the function does not return a value. Refers to `mz_types.id`. Note that for table functions with > 1 column, this type corresponds to [`record`].",
3555            ),
3556            (
3557                "returns_set",
3558                "Whether the function returns a set, i.e. the function is a table function.",
3559            ),
3560            (
3561                "owner_id",
3562                "The role ID of the owner of the function. Corresponds to `mz_roles.id`.",
3563            ),
3564        ]),
3565        is_retained_metrics_object: false,
3566        access: vec![PUBLIC_SELECT],
3567    }
3568});
3569pub static MZ_OPERATORS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3570    name: "mz_operators",
3571    schema: MZ_CATALOG_SCHEMA,
3572    oid: oid::TABLE_MZ_OPERATORS_OID,
3573    desc: RelationDesc::builder()
3574        .with_column("oid", SqlScalarType::Oid.nullable(false))
3575        .with_column("name", SqlScalarType::String.nullable(false))
3576        .with_column(
3577            "argument_type_ids",
3578            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
3579        )
3580        .with_column("return_type_id", SqlScalarType::String.nullable(true))
3581        .finish(),
3582    column_comments: BTreeMap::new(),
3583    is_retained_metrics_object: false,
3584    access: vec![PUBLIC_SELECT],
3585});
3586pub static MZ_AGGREGATES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3587    name: "mz_aggregates",
3588    schema: MZ_INTERNAL_SCHEMA,
3589    oid: oid::TABLE_MZ_AGGREGATES_OID,
3590    desc: RelationDesc::builder()
3591        .with_column("oid", SqlScalarType::Oid.nullable(false))
3592        .with_column("agg_kind", SqlScalarType::String.nullable(false))
3593        .with_column("agg_num_direct_args", SqlScalarType::Int16.nullable(false))
3594        .finish(),
3595    column_comments: BTreeMap::new(),
3596    is_retained_metrics_object: false,
3597    access: vec![PUBLIC_SELECT],
3598});
3599
3600pub static MZ_CLUSTERS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3601    name: "mz_clusters",
3602    schema: MZ_CATALOG_SCHEMA,
3603    oid: oid::TABLE_MZ_CLUSTERS_OID,
3604    desc: RelationDesc::builder()
3605        .with_column("id", SqlScalarType::String.nullable(false))
3606        .with_column("name", SqlScalarType::String.nullable(false))
3607        .with_column("owner_id", SqlScalarType::String.nullable(false))
3608        .with_column(
3609            "privileges",
3610            SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3611        )
3612        .with_column("managed", SqlScalarType::Bool.nullable(false))
3613        .with_column("size", SqlScalarType::String.nullable(true))
3614        .with_column("replication_factor", SqlScalarType::UInt32.nullable(true))
3615        .with_column("disk", SqlScalarType::Bool.nullable(true))
3616        .with_column(
3617            "availability_zones",
3618            SqlScalarType::List {
3619                element_type: Box::new(SqlScalarType::String),
3620                custom_id: None,
3621            }
3622            .nullable(true),
3623        )
3624        .with_column(
3625            "introspection_debugging",
3626            SqlScalarType::Bool.nullable(true),
3627        )
3628        .with_column(
3629            "introspection_interval",
3630            SqlScalarType::Interval.nullable(true),
3631        )
3632        .with_key(vec![0])
3633        .finish(),
3634    column_comments: BTreeMap::from_iter([
3635        ("id", "Materialize's unique ID for the cluster."),
3636        ("name", "The name of the cluster."),
3637        (
3638            "owner_id",
3639            "The role ID of the owner of the cluster. Corresponds to `mz_roles.id`.",
3640        ),
3641        ("privileges", "The privileges belonging to the cluster."),
3642        (
3643            "managed",
3644            "Whether the cluster is a managed cluster with automatically managed replicas.",
3645        ),
3646        (
3647            "size",
3648            "If the cluster is managed, the desired size of the cluster's replicas. `NULL` for unmanaged clusters.",
3649        ),
3650        (
3651            "replication_factor",
3652            "If the cluster is managed, the desired number of replicas of the cluster. `NULL` for unmanaged clusters.",
3653        ),
3654        (
3655            "disk",
3656            "**Unstable** If the cluster is managed, `true` if the replicas have the `DISK` option . `NULL` for unmanaged clusters.",
3657        ),
3658        (
3659            "availability_zones",
3660            "**Unstable** If the cluster is managed, the list of availability zones specified in `AVAILABILITY ZONES`. `NULL` for unmanaged clusters.",
3661        ),
3662        (
3663            "introspection_debugging",
3664            "Whether introspection of the gathering of the introspection data is enabled.",
3665        ),
3666        (
3667            "introspection_interval",
3668            "The interval at which to collect introspection data.",
3669        ),
3670    ]),
3671    is_retained_metrics_object: false,
3672    access: vec![PUBLIC_SELECT],
3673});
3674
3675pub static MZ_CLUSTER_WORKLOAD_CLASSES: LazyLock<BuiltinMaterializedView> =
3676    LazyLock::new(|| BuiltinMaterializedView {
3677        name: "mz_cluster_workload_classes",
3678        schema: MZ_INTERNAL_SCHEMA,
3679        oid: oid::MV_MZ_CLUSTER_WORKLOAD_CLASSES_OID,
3680        desc: RelationDesc::builder()
3681            .with_column("id", SqlScalarType::String.nullable(false))
3682            .with_column("workload_class", SqlScalarType::String.nullable(true))
3683            .with_key(vec![0])
3684            .finish(),
3685        column_comments: BTreeMap::new(),
3686        sql: "
3687IN CLUSTER mz_catalog_server
3688WITH (
3689    ASSERT NOT NULL id
3690) AS
3691SELECT
3692    mz_internal.parse_catalog_id(data->'key'->'id') AS id,
3693    CASE WHEN data->'value'->'config'->'workload_class' != 'null'
3694         THEN data->'value'->'config'->>'workload_class'
3695    END AS workload_class
3696FROM mz_internal.mz_catalog_raw
3697WHERE data->>'kind' = 'Cluster'",
3698        is_retained_metrics_object: false,
3699        access: vec![PUBLIC_SELECT],
3700    });
3701
3702pub const MZ_CLUSTER_WORKLOAD_CLASSES_IND: BuiltinIndex = BuiltinIndex {
3703    name: "mz_cluster_workload_classes_ind",
3704    schema: MZ_INTERNAL_SCHEMA,
3705    oid: oid::INDEX_MZ_CLUSTER_WORKLOAD_CLASSES_IND_OID,
3706    sql: "IN CLUSTER mz_catalog_server
3707ON mz_internal.mz_cluster_workload_classes (id)",
3708    is_retained_metrics_object: false,
3709};
3710
3711pub static MZ_CLUSTER_SCHEDULES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3712    name: "mz_cluster_schedules",
3713    schema: MZ_INTERNAL_SCHEMA,
3714    oid: oid::TABLE_MZ_CLUSTER_SCHEDULES_OID,
3715    desc: RelationDesc::builder()
3716        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3717        .with_column("type", SqlScalarType::String.nullable(false))
3718        .with_column(
3719            "refresh_hydration_time_estimate",
3720            SqlScalarType::Interval.nullable(true),
3721        )
3722        .finish(),
3723    column_comments: BTreeMap::from_iter([
3724        (
3725            "cluster_id",
3726            "The ID of the cluster. Corresponds to `mz_clusters.id`.",
3727        ),
3728        ("type", "`on-refresh`, or `manual`. Default: `manual`"),
3729        (
3730            "refresh_hydration_time_estimate",
3731            "The interval given in the `HYDRATION TIME ESTIMATE` option.",
3732        ),
3733    ]),
3734    is_retained_metrics_object: false,
3735    access: vec![PUBLIC_SELECT],
3736});
3737
3738pub static MZ_SECRETS: LazyLock<BuiltinMaterializedView> = LazyLock::new(|| {
3739    BuiltinMaterializedView {
3740        name: "mz_secrets",
3741        schema: MZ_CATALOG_SCHEMA,
3742        oid: oid::MV_MZ_SECRETS_OID,
3743        desc: RelationDesc::builder()
3744            .with_column("id", SqlScalarType::String.nullable(false))
3745            .with_column("oid", SqlScalarType::Oid.nullable(false))
3746            .with_column("schema_id", SqlScalarType::String.nullable(false))
3747            .with_column("name", SqlScalarType::String.nullable(false))
3748            .with_column("owner_id", SqlScalarType::String.nullable(false))
3749            .with_column(
3750                "privileges",
3751                SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false),
3752            )
3753            .finish(),
3754        column_comments: BTreeMap::from_iter([
3755            ("id", "The unique ID of the secret."),
3756            ("oid", "A PostgreSQL-compatible oid for the secret."),
3757            (
3758                "schema_id",
3759                "The ID of the schema to which the secret belongs. Corresponds to `mz_schemas.id`.",
3760            ),
3761            ("name", "The name of the secret."),
3762            (
3763                "owner_id",
3764                "The role ID of the owner of the secret. Corresponds to `mz_roles.id`.",
3765            ),
3766            ("privileges", "The privileges belonging to the secret."),
3767        ]),
3768        sql: "
3769IN CLUSTER mz_catalog_server
3770WITH (
3771    ASSERT NOT NULL id,
3772    ASSERT NOT NULL oid,
3773    ASSERT NOT NULL schema_id,
3774    ASSERT NOT NULL name,
3775    ASSERT NOT NULL owner_id,
3776    ASSERT NOT NULL privileges
3777) AS
3778SELECT
3779    mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
3780    (data->'value'->>'oid')::oid AS oid,
3781    mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,
3782    data->'value'->>'name' AS name,
3783    mz_internal.parse_catalog_id(data->'value'->'owner_id') AS owner_id,
3784    mz_internal.parse_catalog_privileges(data->'value'->'privileges') AS privileges
3785FROM mz_internal.mz_catalog_raw
3786WHERE
3787    data->>'kind' = 'Item' AND
3788    mz_internal.parse_catalog_create_sql(data->'value'->'definition'->'V1'->>'create_sql')->>'type' = 'secret'",
3789        is_retained_metrics_object: false,
3790        access: vec![PUBLIC_SELECT],
3791    }
3792});
3793
3794pub static MZ_CLUSTER_REPLICAS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3795    name: "mz_cluster_replicas",
3796    schema: MZ_CATALOG_SCHEMA,
3797    oid: oid::TABLE_MZ_CLUSTER_REPLICAS_OID,
3798    desc: RelationDesc::builder()
3799        .with_column("id", SqlScalarType::String.nullable(false))
3800        .with_column("name", SqlScalarType::String.nullable(false))
3801        .with_column("cluster_id", SqlScalarType::String.nullable(false))
3802        .with_column("size", SqlScalarType::String.nullable(true))
3803        // `NULL` for un-orchestrated clusters and for replicas where the user
3804        // hasn't specified them.
3805        .with_column("availability_zone", SqlScalarType::String.nullable(true))
3806        .with_column("owner_id", SqlScalarType::String.nullable(false))
3807        .with_column("disk", SqlScalarType::Bool.nullable(true))
3808        .finish(),
3809    column_comments: BTreeMap::from_iter([
3810        ("id", "Materialize's unique ID for the cluster replica."),
3811        ("name", "The name of the cluster replica."),
3812        (
3813            "cluster_id",
3814            "The ID of the cluster to which the replica belongs. Corresponds to `mz_clusters.id`.",
3815        ),
3816        (
3817            "size",
3818            "The cluster replica's size, selected during creation.",
3819        ),
3820        (
3821            "availability_zone",
3822            "The availability zone in which the cluster is running.",
3823        ),
3824        (
3825            "owner_id",
3826            "The role ID of the owner of the cluster replica. Corresponds to `mz_roles.id`.",
3827        ),
3828        ("disk", "If the replica has a local disk."),
3829    ]),
3830    is_retained_metrics_object: true,
3831    access: vec![PUBLIC_SELECT],
3832});
3833
3834pub static MZ_INTERNAL_CLUSTER_REPLICAS: LazyLock<BuiltinMaterializedView> =
3835    LazyLock::new(|| BuiltinMaterializedView {
3836        name: "mz_internal_cluster_replicas",
3837        schema: MZ_INTERNAL_SCHEMA,
3838        oid: oid::MV_MZ_INTERNAL_CLUSTER_REPLICAS_OID,
3839        desc: RelationDesc::builder()
3840            .with_column("id", SqlScalarType::String.nullable(false))
3841            .with_key(vec![0])
3842            .finish(),
3843        column_comments: BTreeMap::from_iter([(
3844            "id",
3845            "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3846        )]),
3847        sql: "
3848IN CLUSTER mz_catalog_server
3849WITH (
3850    ASSERT NOT NULL id
3851) AS
3852SELECT mz_internal.parse_catalog_id(data->'key'->'id') AS id
3853FROM mz_internal.mz_catalog_raw
3854WHERE
3855    data->>'kind' = 'ClusterReplica' AND
3856    (data->'value'->'config'->'location'->'Managed'->>'internal')::bool = true",
3857        is_retained_metrics_object: false,
3858        access: vec![PUBLIC_SELECT],
3859    });
3860
3861pub static MZ_PENDING_CLUSTER_REPLICAS: LazyLock<BuiltinMaterializedView> =
3862    LazyLock::new(|| BuiltinMaterializedView {
3863        name: "mz_pending_cluster_replicas",
3864        schema: MZ_INTERNAL_SCHEMA,
3865        oid: oid::MV_MZ_PENDING_CLUSTER_REPLICAS_OID,
3866        desc: RelationDesc::builder()
3867            .with_column("id", SqlScalarType::String.nullable(false))
3868            .with_key(vec![0])
3869            .finish(),
3870        column_comments: BTreeMap::from_iter([(
3871            "id",
3872            "The ID of a cluster replica. Corresponds to `mz_cluster_replicas.id`.",
3873        )]),
3874        sql: "
3875IN CLUSTER mz_catalog_server
3876WITH (
3877    ASSERT NOT NULL id
3878) AS
3879SELECT mz_internal.parse_catalog_id(data->'key'->'id') AS id
3880FROM mz_internal.mz_catalog_raw
3881WHERE
3882    data->>'kind' = 'ClusterReplica' AND
3883    (data->'value'->'config'->'location'->'Managed'->>'pending')::bool = true",
3884        is_retained_metrics_object: false,
3885        access: vec![PUBLIC_SELECT],
3886    });
3887
3888pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
3889    BuiltinSource {
3890        name: "mz_cluster_replica_status_history",
3891        schema: MZ_INTERNAL_SCHEMA,
3892        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3893        data_source: IntrospectionType::ReplicaStatusHistory.into(),
3894        desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3895        column_comments: BTreeMap::from_iter([
3896            ("replica_id", "The ID of a cluster replica."),
3897            ("process_id", "The ID of a process within the replica."),
3898            (
3899                "status",
3900                "The status of the cluster replica: `online` or `offline`.",
3901            ),
3902            (
3903                "reason",
3904                "If the cluster replica is in an `offline` state, the reason (if available). For example, `oom-killed`.",
3905            ),
3906            (
3907                "occurred_at",
3908                "Wall-clock timestamp at which the event occurred.",
3909            ),
3910        ]),
3911        is_retained_metrics_object: false,
3912        access: vec![PUBLIC_SELECT],
3913    }
3914});
3915
3916pub static MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
3917    || {
3918        BuiltinContinualTask {
3919            name: "mz_cluster_replica_status_history_ct",
3920            schema: MZ_INTERNAL_SCHEMA,
3921            oid: oid::CT_MZ_CLUSTER_REPLICA_STATUS_HISTORY_OID,
3922            desc: REPLICA_STATUS_HISTORY_DESC.clone(),
3923            sql: "
3924IN CLUSTER mz_catalog_server
3925ON INPUT mz_internal.mz_cluster_replica_status_history AS (
3926    DELETE FROM mz_internal.mz_cluster_replica_status_history_ct WHERE occurred_at + '30d' < mz_now();
3927    INSERT INTO mz_internal.mz_cluster_replica_status_history_ct SELECT * FROM mz_internal.mz_cluster_replica_status_history;
3928)",
3929            access: vec![PUBLIC_SELECT],
3930        }
3931    },
3932);
3933
3934pub static MZ_CLUSTER_REPLICA_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
3935    name: "mz_cluster_replica_statuses",
3936    schema: MZ_INTERNAL_SCHEMA,
3937    oid: oid::VIEW_MZ_CLUSTER_REPLICA_STATUSES_OID,
3938    desc: RelationDesc::builder()
3939        .with_column("replica_id", SqlScalarType::String.nullable(false))
3940        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
3941        .with_column("status", SqlScalarType::String.nullable(false))
3942        .with_column("reason", SqlScalarType::String.nullable(true))
3943        .with_column(
3944            "updated_at",
3945            SqlScalarType::TimestampTz { precision: None }.nullable(false),
3946        )
3947        .with_key(vec![0, 1])
3948        .finish(),
3949    column_comments: BTreeMap::from_iter([
3950        (
3951            "replica_id",
3952            "Materialize's unique ID for the cluster replica.",
3953        ),
3954        (
3955            "process_id",
3956            "The ID of the process within the cluster replica.",
3957        ),
3958        (
3959            "status",
3960            "The status of the cluster replica: `online` or `offline`.",
3961        ),
3962        (
3963            "reason",
3964            "If the cluster replica is in a `offline` state, the reason (if available). For example, `oom-killed`.",
3965        ),
3966        (
3967            "updated_at",
3968            "The time at which the status was last updated.",
3969        ),
3970    ]),
3971    sql: "
3972SELECT
3973    DISTINCT ON (replica_id, process_id)
3974    replica_id,
3975    process_id,
3976    status,
3977    reason,
3978    occurred_at as updated_at
3979FROM mz_internal.mz_cluster_replica_status_history
3980JOIN mz_cluster_replicas r ON r.id = replica_id
3981ORDER BY replica_id, process_id, occurred_at DESC",
3982    access: vec![PUBLIC_SELECT],
3983});
3984
3985pub static MZ_CLUSTER_REPLICA_SIZES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
3986    name: "mz_cluster_replica_sizes",
3987    schema: MZ_CATALOG_SCHEMA,
3988    oid: oid::TABLE_MZ_CLUSTER_REPLICA_SIZES_OID,
3989    desc: RelationDesc::builder()
3990        .with_column("size", SqlScalarType::String.nullable(false))
3991        .with_column("processes", SqlScalarType::UInt64.nullable(false))
3992        .with_column("workers", SqlScalarType::UInt64.nullable(false))
3993        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(false))
3994        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(false))
3995        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
3996        .with_column(
3997            "credits_per_hour",
3998            SqlScalarType::Numeric { max_scale: None }.nullable(false),
3999        )
4000        .finish(),
4001    column_comments: BTreeMap::from_iter([
4002        ("size", "The human-readable replica size."),
4003        ("processes", "The number of processes in the replica."),
4004        (
4005            "workers",
4006            "The number of Timely Dataflow workers per process.",
4007        ),
4008        (
4009            "cpu_nano_cores",
4010            "The CPU allocation per process, in billionths of a vCPU core.",
4011        ),
4012        (
4013            "memory_bytes",
4014            "The RAM allocation per process, in billionths of a vCPU core.",
4015        ),
4016        ("disk_bytes", "The disk allocation per process."),
4017        (
4018            "credits_per_hour",
4019            "The number of compute credits consumed per hour.",
4020        ),
4021    ]),
4022    is_retained_metrics_object: true,
4023    access: vec![PUBLIC_SELECT],
4024});
4025
4026pub static MZ_AUDIT_EVENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
4027    name: "mz_audit_events",
4028    schema: MZ_CATALOG_SCHEMA,
4029    oid: oid::TABLE_MZ_AUDIT_EVENTS_OID,
4030    desc: RelationDesc::builder()
4031        .with_column("id", SqlScalarType::UInt64.nullable(false))
4032        .with_column("event_type", SqlScalarType::String.nullable(false))
4033        .with_column("object_type", SqlScalarType::String.nullable(false))
4034        .with_column("details", SqlScalarType::Jsonb.nullable(false))
4035        .with_column("user", SqlScalarType::String.nullable(true))
4036        .with_column(
4037            "occurred_at",
4038            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4039        )
4040        .with_key(vec![0])
4041        .finish(),
4042    column_comments: BTreeMap::from_iter([
4043        (
4044            "id",
4045            "Materialize's unique, monotonically increasing ID for the event.",
4046        ),
4047        (
4048            "event_type",
4049            "The type of the event: `create`, `drop`, or `alter`.",
4050        ),
4051        (
4052            "object_type",
4053            "The type of the affected object: `cluster`, `cluster-replica`, `connection`, `database`, `function`, `index`, `materialized-view`, `role`, `schema`, `secret`, `sink`, `source`, `table`, `type`, or `view`.",
4054        ),
4055        (
4056            "details",
4057            "Additional details about the event. The shape of the details varies based on `event_type` and `object_type`.",
4058        ),
4059        (
4060            "user",
4061            "The user who triggered the event, or `NULL` if triggered by the system.",
4062        ),
4063        (
4064            "occurred_at",
4065            "The time at which the event occurred. Guaranteed to be in order of event creation. Events created in the same transaction will have identical values.",
4066        ),
4067    ]),
4068    is_retained_metrics_object: false,
4069    access: vec![PUBLIC_SELECT],
4070});
4071
4072pub static MZ_SOURCE_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4073    name: "mz_source_status_history",
4074    schema: MZ_INTERNAL_SCHEMA,
4075    oid: oid::SOURCE_MZ_SOURCE_STATUS_HISTORY_OID,
4076    data_source: IntrospectionType::SourceStatusHistory.into(),
4077    desc: MZ_SOURCE_STATUS_HISTORY_DESC.clone(),
4078    column_comments: BTreeMap::from_iter([
4079        (
4080            "occurred_at",
4081            "Wall-clock timestamp of the source status change.",
4082        ),
4083        (
4084            "source_id",
4085            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4086        ),
4087        (
4088            "status",
4089            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4090        ),
4091        (
4092            "error",
4093            "If the source is in an error state, the error message.",
4094        ),
4095        (
4096            "details",
4097            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4098        ),
4099        (
4100            "replica_id",
4101            "The ID of the replica that an instance of a source is running on.",
4102        ),
4103    ]),
4104    is_retained_metrics_object: false,
4105    access: vec![PUBLIC_SELECT],
4106});
4107
4108pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(
4109    || BuiltinSource {
4110        name: "mz_aws_privatelink_connection_status_history",
4111        schema: MZ_INTERNAL_SCHEMA,
4112        oid: oid::SOURCE_MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_OID,
4113        data_source: DataSourceDesc::Introspection(
4114            IntrospectionType::PrivatelinkConnectionStatusHistory,
4115        ),
4116        desc: MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY_DESC.clone(),
4117        column_comments: BTreeMap::from_iter([
4118            ("occurred_at", "Wall-clock timestamp of the status change."),
4119            (
4120                "connection_id",
4121                "The unique identifier of the AWS PrivateLink connection. Corresponds to `mz_catalog.mz_connections.id`.",
4122            ),
4123            (
4124                "status",
4125                "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`.",
4126            ),
4127        ]),
4128        is_retained_metrics_object: false,
4129        access: vec![PUBLIC_SELECT],
4130    },
4131);
4132
4133pub static MZ_AWS_PRIVATELINK_CONNECTION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| {
4134    BuiltinView {
4135        name: "mz_aws_privatelink_connection_statuses",
4136        schema: MZ_INTERNAL_SCHEMA,
4137        oid: oid::VIEW_MZ_AWS_PRIVATELINK_CONNECTION_STATUSES_OID,
4138        desc: RelationDesc::builder()
4139            .with_column("id", SqlScalarType::String.nullable(false))
4140            .with_column("name", SqlScalarType::String.nullable(false))
4141            .with_column(
4142                "last_status_change_at",
4143                SqlScalarType::TimestampTz { precision: None }.nullable(true),
4144            )
4145            .with_column("status", SqlScalarType::String.nullable(true))
4146            .with_key(vec![0])
4147            .finish(),
4148        column_comments: BTreeMap::from_iter([
4149            (
4150                "id",
4151                "The ID of the connection. Corresponds to `mz_catalog.mz_connections.id`.",
4152            ),
4153            ("name", "The name of the connection."),
4154            (
4155                "last_status_change_at",
4156                "Wall-clock timestamp of the connection status change.",
4157            ),
4158            (
4159                "status",
4160                "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`.",
4161            ),
4162        ]),
4163        sql: "
4164    WITH statuses_w_last_status AS (
4165        SELECT
4166            connection_id,
4167            occurred_at,
4168            status,
4169            lag(status) OVER (PARTITION BY connection_id ORDER BY occurred_at) AS last_status
4170        FROM mz_internal.mz_aws_privatelink_connection_status_history
4171    ),
4172    latest_events AS (
4173        -- Only take the most recent transition for each ID
4174        SELECT DISTINCT ON(connection_id) connection_id, occurred_at, status
4175        FROM statuses_w_last_status
4176        -- Only keep first status transitions
4177        WHERE status <> last_status OR last_status IS NULL
4178        ORDER BY connection_id, occurred_at DESC
4179    )
4180    SELECT
4181        conns.id,
4182        name,
4183        occurred_at as last_status_change_at,
4184        status
4185    FROM latest_events
4186    JOIN mz_catalog.mz_connections AS conns
4187    ON conns.id = latest_events.connection_id",
4188        access: vec![PUBLIC_SELECT],
4189    }
4190});
4191
4192pub static MZ_STATEMENT_EXECUTION_HISTORY: LazyLock<BuiltinSource> =
4193    LazyLock::new(|| BuiltinSource {
4194        name: "mz_statement_execution_history",
4195        schema: MZ_INTERNAL_SCHEMA,
4196        oid: oid::SOURCE_MZ_STATEMENT_EXECUTION_HISTORY_OID,
4197        data_source: IntrospectionType::StatementExecutionHistory.into(),
4198        desc: MZ_STATEMENT_EXECUTION_HISTORY_DESC.clone(),
4199        column_comments: BTreeMap::new(),
4200        is_retained_metrics_object: false,
4201        access: vec![MONITOR_SELECT],
4202    });
4203
4204pub static MZ_STATEMENT_EXECUTION_HISTORY_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4205    BuiltinView {
4206    name: "mz_statement_execution_history_redacted",
4207    schema: MZ_INTERNAL_SCHEMA,
4208    oid: oid::VIEW_MZ_STATEMENT_EXECUTION_HISTORY_REDACTED_OID,
4209    // everything but `params` and `error_message`
4210    desc: RelationDesc::builder()
4211        .with_column("id", SqlScalarType::Uuid.nullable(false))
4212        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4213        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4214        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4215        .with_column("application_name", SqlScalarType::String.nullable(false))
4216        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4217        .with_column("database_name", SqlScalarType::String.nullable(false))
4218        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4219        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4220        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4221        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4222        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4223        .with_column("mz_version", SqlScalarType::String.nullable(false))
4224        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4225        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4226        .with_column("finished_status", SqlScalarType::String.nullable(true))
4227        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4228        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4229        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4230        .finish(),
4231    column_comments: BTreeMap::new(),
4232    sql: "
4233SELECT id, prepared_statement_id, sample_rate, cluster_id, application_name,
4234cluster_name, database_name, search_path, transaction_isolation, execution_timestamp, transaction_id,
4235transient_index_id, mz_version, began_at, finished_at, finished_status,
4236result_size, rows_returned, execution_strategy
4237FROM mz_internal.mz_statement_execution_history",
4238    access: vec![SUPPORT_SELECT, ANALYTICS_SELECT, MONITOR_REDACTED_SELECT, MONITOR_SELECT],
4239}
4240});
4241
4242pub static MZ_PREPARED_STATEMENT_HISTORY: LazyLock<BuiltinSource> =
4243    LazyLock::new(|| BuiltinSource {
4244        name: "mz_prepared_statement_history",
4245        schema: MZ_INTERNAL_SCHEMA,
4246        oid: oid::SOURCE_MZ_PREPARED_STATEMENT_HISTORY_OID,
4247        data_source: IntrospectionType::PreparedStatementHistory.into(),
4248        desc: MZ_PREPARED_STATEMENT_HISTORY_DESC.clone(),
4249        column_comments: BTreeMap::new(),
4250        is_retained_metrics_object: false,
4251        access: vec![
4252            SUPPORT_SELECT,
4253            ANALYTICS_SELECT,
4254            MONITOR_REDACTED_SELECT,
4255            MONITOR_SELECT,
4256        ],
4257    });
4258
4259pub static MZ_SQL_TEXT: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4260    name: "mz_sql_text",
4261    schema: MZ_INTERNAL_SCHEMA,
4262    oid: oid::SOURCE_MZ_SQL_TEXT_OID,
4263    desc: MZ_SQL_TEXT_DESC.clone(),
4264    data_source: IntrospectionType::SqlText.into(),
4265    column_comments: BTreeMap::new(),
4266    is_retained_metrics_object: false,
4267    access: vec![MONITOR_SELECT],
4268});
4269
4270pub static MZ_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4271    name: "mz_sql_text_redacted",
4272    schema: MZ_INTERNAL_SCHEMA,
4273    oid: oid::VIEW_MZ_SQL_TEXT_REDACTED_OID,
4274    desc: RelationDesc::builder()
4275        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4276        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4277        .finish(),
4278    column_comments: BTreeMap::new(),
4279    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_sql_text",
4280    access: vec![
4281        MONITOR_SELECT,
4282        MONITOR_REDACTED_SELECT,
4283        SUPPORT_SELECT,
4284        ANALYTICS_SELECT,
4285    ],
4286});
4287
4288pub static MZ_RECENT_SQL_TEXT: LazyLock<BuiltinView> = LazyLock::new(|| {
4289    BuiltinView {
4290        name: "mz_recent_sql_text",
4291        schema: MZ_INTERNAL_SCHEMA,
4292        oid: oid::VIEW_MZ_RECENT_SQL_TEXT_OID,
4293        // This should always be 1 day more than the interval in
4294        // `MZ_RECENT_THINNED_ACTIVITY_LOG` , because `prepared_day`
4295        // is rounded down to the nearest day.  Thus something that actually happened three days ago
4296        // could have a `prepared day` anywhere from 3 to 4 days back.
4297        desc: RelationDesc::builder()
4298            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4299            .with_column("sql", SqlScalarType::String.nullable(false))
4300            .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4301            .with_key(vec![0, 1, 2])
4302            .finish(),
4303        column_comments: BTreeMap::new(),
4304        sql: "SELECT DISTINCT sql_hash, sql, redacted_sql FROM mz_internal.mz_sql_text WHERE prepared_day + INTERVAL '4 days' >= mz_now()",
4305        access: vec![MONITOR_SELECT],
4306    }
4307});
4308
4309pub static MZ_RECENT_SQL_TEXT_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4310    name: "mz_recent_sql_text_redacted",
4311    schema: MZ_INTERNAL_SCHEMA,
4312    oid: oid::VIEW_MZ_RECENT_SQL_TEXT_REDACTED_OID,
4313    desc: RelationDesc::builder()
4314        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4315        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4316        .finish(),
4317    column_comments: BTreeMap::new(),
4318    sql: "SELECT sql_hash, redacted_sql FROM mz_internal.mz_recent_sql_text",
4319    access: vec![
4320        MONITOR_SELECT,
4321        MONITOR_REDACTED_SELECT,
4322        SUPPORT_SELECT,
4323        ANALYTICS_SELECT,
4324    ],
4325});
4326
4327pub static MZ_RECENT_SQL_TEXT_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
4328    name: "mz_recent_sql_text_ind",
4329    schema: MZ_INTERNAL_SCHEMA,
4330    oid: oid::INDEX_MZ_RECENT_SQL_TEXT_IND_OID,
4331    sql: "IN CLUSTER mz_catalog_server ON mz_internal.mz_recent_sql_text (sql_hash)",
4332    is_retained_metrics_object: false,
4333});
4334
4335pub static MZ_SESSION_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4336    name: "mz_session_history",
4337    schema: MZ_INTERNAL_SCHEMA,
4338    oid: oid::SOURCE_MZ_SESSION_HISTORY_OID,
4339    data_source: IntrospectionType::SessionHistory.into(),
4340    desc: MZ_SESSION_HISTORY_DESC.clone(),
4341    column_comments: BTreeMap::from_iter([
4342        (
4343            "session_id",
4344            "The globally unique ID of the session. Corresponds to `mz_sessions.id`.",
4345        ),
4346        (
4347            "connected_at",
4348            "The time at which the session was established.",
4349        ),
4350        (
4351            "initial_application_name",
4352            "The `application_name` session metadata field.",
4353        ),
4354        (
4355            "authenticated_user",
4356            "The name of the user for which the session was established.",
4357        ),
4358    ]),
4359    is_retained_metrics_object: false,
4360    access: vec![PUBLIC_SELECT],
4361});
4362
4363pub static MZ_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4364    BuiltinView {
4365        name: "mz_activity_log_thinned",
4366        schema: MZ_INTERNAL_SCHEMA,
4367        oid: oid::VIEW_MZ_ACTIVITY_LOG_THINNED_OID,
4368        desc: RelationDesc::builder()
4369            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4370            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4371            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4372            .with_column("application_name", SqlScalarType::String.nullable(false))
4373            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4374            .with_column("database_name", SqlScalarType::String.nullable(false))
4375            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4376            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4377            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4378            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4379            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4380            .with_column("mz_version", SqlScalarType::String.nullable(false))
4381            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4382            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4383            .with_column("finished_status", SqlScalarType::String.nullable(true))
4384            .with_column("error_message", SqlScalarType::String.nullable(true))
4385            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4386            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4387            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4388            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4389            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4390            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4391            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4392            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4393            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4394            .with_column("statement_type", SqlScalarType::String.nullable(true))
4395            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4396            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4397            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4398            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4399            .finish(),
4400        column_comments: BTreeMap::new(),
4401        sql: "
4402SELECT mseh.id AS execution_id, sample_rate, cluster_id, application_name, cluster_name, database_name, search_path,
4403transaction_isolation, execution_timestamp, transient_index_id, params, mz_version, began_at, finished_at, finished_status,
4404error_message, result_size, rows_returned, execution_strategy, transaction_id,
4405mpsh.id AS prepared_statement_id, sql_hash, mpsh.name AS prepared_statement_name,
4406mpsh.session_id, prepared_at, statement_type, throttled_count,
4407connected_at, initial_application_name, authenticated_user
4408FROM mz_internal.mz_statement_execution_history mseh,
4409     mz_internal.mz_prepared_statement_history mpsh,
4410     mz_internal.mz_session_history msh
4411WHERE mseh.prepared_statement_id = mpsh.id
4412AND mpsh.session_id = msh.session_id",
4413        access: vec![MONITOR_SELECT],
4414    }
4415});
4416
4417pub static MZ_RECENT_ACTIVITY_LOG_THINNED: LazyLock<BuiltinView> = LazyLock::new(|| {
4418    BuiltinView {
4419        name: "mz_recent_activity_log_thinned",
4420        schema: MZ_INTERNAL_SCHEMA,
4421        oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_THINNED_OID,
4422        desc: RelationDesc::builder()
4423            .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4424            .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4425            .with_column("cluster_id", SqlScalarType::String.nullable(true))
4426            .with_column("application_name", SqlScalarType::String.nullable(false))
4427            .with_column("cluster_name", SqlScalarType::String.nullable(true))
4428            .with_column("database_name", SqlScalarType::String.nullable(false))
4429            .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4430            .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4431            .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4432            .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4433            .with_column("params", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false))
4434            .with_column("mz_version", SqlScalarType::String.nullable(false))
4435            .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4436            .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4437            .with_column("finished_status", SqlScalarType::String.nullable(true))
4438            .with_column("error_message", SqlScalarType::String.nullable(true))
4439            .with_column("result_size", SqlScalarType::Int64.nullable(true))
4440            .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4441            .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4442            .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4443            .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4444            .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4445            .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4446            .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4447            .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4448            .with_column("statement_type", SqlScalarType::String.nullable(true))
4449            .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4450            .with_column("connected_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4451            .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4452            .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4453            .finish(),
4454        column_comments: BTreeMap::new(),
4455        // We use a temporal window of 2 days rather than 1 day for `mz_session_history`'s `connected_at` since a statement execution at
4456        // 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.
4457        sql:
4458        "SELECT * FROM mz_internal.mz_activity_log_thinned WHERE prepared_at + INTERVAL '1 day' > mz_now()
4459AND began_at + INTERVAL '1 day' > mz_now() AND connected_at + INTERVAL '2 days' > mz_now()",
4460        access: vec![MONITOR_SELECT],
4461    }
4462});
4463
4464pub static MZ_RECENT_ACTIVITY_LOG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4465    name: "mz_recent_activity_log",
4466    schema: MZ_INTERNAL_SCHEMA,
4467    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_OID,
4468    desc: RelationDesc::builder()
4469        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4470        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4471        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4472        .with_column("application_name", SqlScalarType::String.nullable(false))
4473        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4474        .with_column("database_name", SqlScalarType::String.nullable(false))
4475        .with_column(
4476            "search_path",
4477            SqlScalarType::List {
4478                element_type: Box::new(SqlScalarType::String),
4479                custom_id: None,
4480            }
4481            .nullable(false),
4482        )
4483        .with_column(
4484            "transaction_isolation",
4485            SqlScalarType::String.nullable(false),
4486        )
4487        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4488        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4489        .with_column(
4490            "params",
4491            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
4492        )
4493        .with_column("mz_version", SqlScalarType::String.nullable(false))
4494        .with_column(
4495            "began_at",
4496            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4497        )
4498        .with_column(
4499            "finished_at",
4500            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4501        )
4502        .with_column("finished_status", SqlScalarType::String.nullable(true))
4503        .with_column("error_message", SqlScalarType::String.nullable(true))
4504        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4505        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4506        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4507        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4508        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4509        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4510        .with_column(
4511            "prepared_statement_name",
4512            SqlScalarType::String.nullable(false),
4513        )
4514        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4515        .with_column(
4516            "prepared_at",
4517            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4518        )
4519        .with_column("statement_type", SqlScalarType::String.nullable(true))
4520        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4521        .with_column(
4522            "connected_at",
4523            SqlScalarType::TimestampTz { precision: None }.nullable(false),
4524        )
4525        .with_column(
4526            "initial_application_name",
4527            SqlScalarType::String.nullable(false),
4528        )
4529        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4530        .with_column("sql", SqlScalarType::String.nullable(false))
4531        .finish(),
4532    column_comments: BTreeMap::from_iter([
4533        (
4534            "execution_id",
4535            "An ID that is unique for each executed statement.",
4536        ),
4537        (
4538            "sample_rate",
4539            "The actual rate at which the statement was sampled.",
4540        ),
4541        (
4542            "cluster_id",
4543            "The ID of the cluster the statement execution was directed to. Corresponds to mz_clusters.id.",
4544        ),
4545        (
4546            "application_name",
4547            "The value of the `application_name` configuration parameter at execution time.",
4548        ),
4549        (
4550            "cluster_name",
4551            "The name of the cluster with ID `cluster_id` at execution time.",
4552        ),
4553        (
4554            "database_name",
4555            "The value of the `database` configuration parameter at execution time.",
4556        ),
4557        (
4558            "search_path",
4559            "The value of the `search_path` configuration parameter at execution time.",
4560        ),
4561        (
4562            "transaction_isolation",
4563            "The value of the `transaction_isolation` configuration parameter at execution time.",
4564        ),
4565        (
4566            "execution_timestamp",
4567            "The logical timestamp at which execution was scheduled.",
4568        ),
4569        (
4570            "transient_index_id",
4571            "The internal index of the compute dataflow created for the query, if any.",
4572        ),
4573        (
4574            "params",
4575            "The parameters with which the statement was executed.",
4576        ),
4577        (
4578            "mz_version",
4579            "The version of Materialize that was running when the statement was executed.",
4580        ),
4581        (
4582            "began_at",
4583            "The wall-clock time at which the statement began executing.",
4584        ),
4585        (
4586            "finished_at",
4587            "The wall-clock time at which the statement finished executing.",
4588        ),
4589        (
4590            "finished_status",
4591            "The final status of the statement (e.g., `success`, `canceled`, `error`, or `aborted`). `aborted` means that Materialize exited before the statement finished executing.",
4592        ),
4593        (
4594            "error_message",
4595            "The error message, if the statement failed.",
4596        ),
4597        (
4598            "result_size",
4599            "The size in bytes of the result, for statements that return rows.",
4600        ),
4601        (
4602            "rows_returned",
4603            "The number of rows returned, for statements that return rows.",
4604        ),
4605        (
4606            "execution_strategy",
4607            "For `SELECT` queries, the strategy for executing the query. `constant` means computed in the control plane without the involvement of a cluster, `fast-path` means read by a cluster directly from an in-memory index, and `standard` means computed by a temporary dataflow.",
4608        ),
4609        (
4610            "transaction_id",
4611            "The ID of the transaction that the statement was part of. Note that transaction IDs are only unique per session.",
4612        ),
4613        (
4614            "prepared_statement_id",
4615            "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`).",
4616        ),
4617        (
4618            "sql_hash",
4619            "An opaque value uniquely identifying the text of the query.",
4620        ),
4621        (
4622            "prepared_statement_name",
4623            "The name given by the client library to the prepared statement.",
4624        ),
4625        (
4626            "session_id",
4627            "An ID that is unique for each session. Corresponds to mz_sessions.id.",
4628        ),
4629        (
4630            "prepared_at",
4631            "The time at which the statement was prepared.",
4632        ),
4633        (
4634            "statement_type",
4635            "The _type_ of the statement, e.g. `select` for a `SELECT` query, or `NULL` if the statement was empty.",
4636        ),
4637        (
4638            "throttled_count",
4639            "The number of statement executions that were dropped due to throttling before the current one was seen. If you have a very high volume of queries and need to log them without throttling, contact our team.",
4640        ),
4641        (
4642            "connected_at",
4643            "The time at which the session was established.",
4644        ),
4645        (
4646            "initial_application_name",
4647            "The initial value of `application_name` at the beginning of the session.",
4648        ),
4649        (
4650            "authenticated_user",
4651            "The name of the user for which the session was established.",
4652        ),
4653        ("sql", "The SQL text of the statement."),
4654    ]),
4655    sql: "SELECT mralt.*, mrst.sql
4656FROM mz_internal.mz_recent_activity_log_thinned mralt,
4657     mz_internal.mz_recent_sql_text mrst
4658WHERE mralt.sql_hash = mrst.sql_hash",
4659    access: vec![MONITOR_SELECT],
4660});
4661
4662pub static MZ_RECENT_ACTIVITY_LOG_REDACTED: LazyLock<BuiltinView> = LazyLock::new(|| {
4663    BuiltinView {
4664    name: "mz_recent_activity_log_redacted",
4665    schema: MZ_INTERNAL_SCHEMA,
4666    oid: oid::VIEW_MZ_RECENT_ACTIVITY_LOG_REDACTED_OID,
4667    // Includes all the columns in mz_recent_activity_log_thinned except 'error_message'.
4668    desc: RelationDesc::builder()
4669        .with_column("execution_id", SqlScalarType::Uuid.nullable(false))
4670        .with_column("sample_rate", SqlScalarType::Float64.nullable(false))
4671        .with_column("cluster_id", SqlScalarType::String.nullable(true))
4672        .with_column("application_name", SqlScalarType::String.nullable(false))
4673        .with_column("cluster_name", SqlScalarType::String.nullable(true))
4674        .with_column("database_name", SqlScalarType::String.nullable(false))
4675        .with_column("search_path", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(false))
4676        .with_column("transaction_isolation", SqlScalarType::String.nullable(false))
4677        .with_column("execution_timestamp", SqlScalarType::UInt64.nullable(true))
4678        .with_column("transient_index_id", SqlScalarType::String.nullable(true))
4679        .with_column("mz_version", SqlScalarType::String.nullable(false))
4680        .with_column("began_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4681        .with_column("finished_at", SqlScalarType::TimestampTz { precision: None }.nullable(true))
4682        .with_column("finished_status", SqlScalarType::String.nullable(true))
4683        .with_column("result_size", SqlScalarType::Int64.nullable(true))
4684        .with_column("rows_returned", SqlScalarType::Int64.nullable(true))
4685        .with_column("execution_strategy", SqlScalarType::String.nullable(true))
4686        .with_column("transaction_id", SqlScalarType::UInt64.nullable(false))
4687        .with_column("prepared_statement_id", SqlScalarType::Uuid.nullable(false))
4688        .with_column("sql_hash", SqlScalarType::Bytes.nullable(false))
4689        .with_column("prepared_statement_name", SqlScalarType::String.nullable(false))
4690        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
4691        .with_column("prepared_at", SqlScalarType::TimestampTz { precision: None }.nullable(false))
4692        .with_column("statement_type", SqlScalarType::String.nullable(true))
4693        .with_column("throttled_count", SqlScalarType::UInt64.nullable(false))
4694        .with_column("initial_application_name", SqlScalarType::String.nullable(false))
4695        .with_column("authenticated_user", SqlScalarType::String.nullable(false))
4696        .with_column("redacted_sql", SqlScalarType::String.nullable(false))
4697        .finish(),
4698    column_comments: BTreeMap::new(),
4699    sql: "SELECT mralt.execution_id, mralt.sample_rate, mralt.cluster_id, mralt.application_name,
4700    mralt.cluster_name, mralt.database_name, mralt.search_path, mralt.transaction_isolation, mralt.execution_timestamp,
4701    mralt.transient_index_id, mralt.mz_version, mralt.began_at, mralt.finished_at,
4702    mralt.finished_status, mralt.result_size, mralt.rows_returned, mralt.execution_strategy, mralt.transaction_id,
4703    mralt.prepared_statement_id, mralt.sql_hash, mralt.prepared_statement_name, mralt.session_id,
4704    mralt.prepared_at, mralt.statement_type, mralt.throttled_count,
4705    mralt.initial_application_name, mralt.authenticated_user,
4706    mrst.redacted_sql
4707FROM mz_internal.mz_recent_activity_log_thinned mralt,
4708     mz_internal.mz_recent_sql_text mrst
4709WHERE mralt.sql_hash = mrst.sql_hash",
4710    access: vec![MONITOR_SELECT, MONITOR_REDACTED_SELECT, SUPPORT_SELECT, ANALYTICS_SELECT],
4711}
4712});
4713
4714pub static MZ_STATEMENT_LIFECYCLE_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| {
4715    BuiltinSource {
4716        name: "mz_statement_lifecycle_history",
4717        schema: MZ_INTERNAL_SCHEMA,
4718        oid: oid::SOURCE_MZ_STATEMENT_LIFECYCLE_HISTORY_OID,
4719        desc: RelationDesc::builder()
4720            .with_column("statement_id", SqlScalarType::Uuid.nullable(false))
4721            .with_column("event_type", SqlScalarType::String.nullable(false))
4722            .with_column(
4723                "occurred_at",
4724                SqlScalarType::TimestampTz { precision: None }.nullable(false),
4725            )
4726            .finish(),
4727        data_source: IntrospectionType::StatementLifecycleHistory.into(),
4728        column_comments: BTreeMap::from_iter([
4729            (
4730                "statement_id",
4731                "The ID of the execution event. Corresponds to `mz_recent_activity_log.execution_id`",
4732            ),
4733            (
4734                "event_type",
4735                "The type of lifecycle event, e.g. `'execution-began'`, `'storage-dependencies-finished'`, `'compute-dependencies-finished'`, or `'execution-finished'`",
4736            ),
4737            ("occurred_at", "The time at which the event took place."),
4738        ]),
4739        is_retained_metrics_object: false,
4740        // TODO[btv]: Maybe this should be public instead of
4741        // `MONITOR_REDACTED`, but since that would be a backwards-compatible
4742        // change, we probably don't need to worry about it now.
4743        access: vec![
4744            SUPPORT_SELECT,
4745            ANALYTICS_SELECT,
4746            MONITOR_REDACTED_SELECT,
4747            MONITOR_SELECT,
4748        ],
4749    }
4750});
4751
4752pub static MZ_SOURCE_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4753    name: "mz_source_statuses",
4754    schema: MZ_INTERNAL_SCHEMA,
4755    oid: oid::VIEW_MZ_SOURCE_STATUSES_OID,
4756    desc: RelationDesc::builder()
4757        .with_column("id", SqlScalarType::String.nullable(false))
4758        .with_column("name", SqlScalarType::String.nullable(false))
4759        .with_column("type", SqlScalarType::String.nullable(false))
4760        .with_column(
4761            "last_status_change_at",
4762            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4763        )
4764        .with_column("status", SqlScalarType::String.nullable(false))
4765        .with_column("error", SqlScalarType::String.nullable(true))
4766        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4767        .finish(),
4768    column_comments: BTreeMap::from_iter([
4769        (
4770            "id",
4771            "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
4772        ),
4773        ("name", "The name of the source."),
4774        ("type", "The type of the source."),
4775        (
4776            "last_status_change_at",
4777            "Wall-clock timestamp of the source status change.",
4778        ),
4779        (
4780            "status",
4781            "The status of the source: one of `created`, `starting`, `running`, `paused`, `stalled`, `failed`, or `dropped`.",
4782        ),
4783        (
4784            "error",
4785            "If the source is in an error state, the error message.",
4786        ),
4787        (
4788            "details",
4789            "Additional metadata provided by the source. In case of error, may contain a `hint` field with helpful suggestions.",
4790        ),
4791    ]),
4792    sql: "
4793    WITH
4794    -- The status history contains per-replica events and source-global events.
4795    -- For the latter, replica_id is NULL. We turn these into '<source>', so that
4796    -- we can treat them uniformly below.
4797    uniform_status_history AS
4798    (
4799        SELECT
4800            s.source_id,
4801            COALESCE(s.replica_id, '<source>') as replica_id,
4802            s.occurred_at,
4803            s.status,
4804            s.error,
4805            s.details
4806        FROM mz_internal.mz_source_status_history s
4807    ),
4808    -- For getting the latest events, we first determine the latest per-replica
4809    -- events here and then apply precedence rules below.
4810    latest_per_replica_events AS
4811    (
4812        SELECT DISTINCT ON (source_id, replica_id)
4813            occurred_at, source_id, replica_id, status, error, details
4814        FROM uniform_status_history
4815        ORDER BY source_id, replica_id, occurred_at DESC
4816    ),
4817    -- We have a precedence list that determines the overall status in case
4818    -- there is differing per-replica (including source-global) statuses. If
4819    -- there is no 'dropped' status, and any replica reports 'running', the
4820    -- overall status is 'running' even if there might be some replica that has
4821    -- errors or is paused.
4822    latest_events AS
4823    (
4824       SELECT DISTINCT ON (source_id)
4825            source_id,
4826            occurred_at,
4827            status,
4828            error,
4829            details
4830        FROM latest_per_replica_events
4831        ORDER BY source_id, CASE status
4832                    WHEN 'dropped' THEN 1
4833                    WHEN 'running' THEN 2
4834                    WHEN 'stalled' THEN 3
4835                    WHEN 'starting' THEN 4
4836                    WHEN 'paused' THEN 5
4837                    WHEN 'ceased' THEN 6
4838                    ELSE 7  -- For any other status values
4839                END
4840    ),
4841    -- Determine which sources are subsources and which are parent sources
4842    subsources AS
4843    (
4844        SELECT subsources.id AS self, sources.id AS parent
4845        FROM
4846            mz_catalog.mz_sources AS subsources
4847                JOIN
4848                    mz_internal.mz_object_dependencies AS deps
4849                    ON subsources.id = deps.object_id
4850                JOIN mz_catalog.mz_sources AS sources ON sources.id = deps.referenced_object_id
4851    ),
4852    -- Determine which sources are source tables
4853    tables AS
4854    (
4855        SELECT tables.id AS self, tables.source_id AS parent, tables.name
4856        FROM mz_catalog.mz_tables AS tables
4857        WHERE tables.source_id IS NOT NULL
4858    ),
4859    -- Determine which collection's ID to use for the status
4860    id_of_status_to_use AS
4861    (
4862        SELECT
4863            self_events.source_id,
4864            -- If self not errored, but parent is, use parent; else self
4865            CASE
4866                WHEN
4867                    self_events.status <> 'ceased' AND
4868                    parent_events.status = 'stalled'
4869                THEN parent_events.source_id
4870                ELSE self_events.source_id
4871            END AS id_to_use
4872        FROM
4873            latest_events AS self_events
4874                LEFT JOIN subsources ON self_events.source_id = subsources.self
4875                LEFT JOIN tables ON self_events.source_id = tables.self
4876                LEFT JOIN
4877                    latest_events AS parent_events
4878                    ON parent_events.source_id = COALESCE(subsources.parent, tables.parent)
4879    ),
4880    -- Swap out events for the ID of the event we plan to use instead
4881    latest_events_to_use AS
4882    (
4883        SELECT occurred_at, s.source_id, status, error, details
4884        FROM
4885            id_of_status_to_use AS s
4886                JOIN latest_events AS e ON e.source_id = s.id_to_use
4887    ),
4888    combined AS (
4889        SELECT
4890            mz_sources.id,
4891            mz_sources.name,
4892            mz_sources.type,
4893            occurred_at,
4894            status,
4895            error,
4896            details
4897        FROM
4898            mz_catalog.mz_sources
4899            LEFT JOIN latest_events_to_use AS e ON mz_sources.id = e.source_id
4900        UNION ALL
4901        SELECT
4902            tables.self AS id,
4903            tables.name,
4904            'table' AS type,
4905            occurred_at,
4906            status,
4907            error,
4908            details
4909        FROM
4910            tables
4911            LEFT JOIN latest_events_to_use AS e ON tables.self = e.source_id
4912    )
4913SELECT
4914    id,
4915    name,
4916    type,
4917    occurred_at AS last_status_change_at,
4918    -- TODO(parkmycar): Report status of webhook source once database-issues#5986 is closed.
4919    CASE
4920        WHEN
4921            type = 'webhook' OR
4922            type = 'progress'
4923        THEN 'running'
4924        ELSE COALESCE(status, 'created')
4925    END AS status,
4926    error,
4927    details
4928FROM combined
4929WHERE id NOT LIKE 's%';",
4930    access: vec![PUBLIC_SELECT],
4931});
4932
4933pub static MZ_SINK_STATUS_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
4934    name: "mz_sink_status_history",
4935    schema: MZ_INTERNAL_SCHEMA,
4936    oid: oid::SOURCE_MZ_SINK_STATUS_HISTORY_OID,
4937    data_source: IntrospectionType::SinkStatusHistory.into(),
4938    desc: MZ_SINK_STATUS_HISTORY_DESC.clone(),
4939    column_comments: BTreeMap::from_iter([
4940        (
4941            "occurred_at",
4942            "Wall-clock timestamp of the sink status change.",
4943        ),
4944        (
4945            "sink_id",
4946            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4947        ),
4948        (
4949            "status",
4950            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4951        ),
4952        (
4953            "error",
4954            "If the sink is in an error state, the error message.",
4955        ),
4956        (
4957            "details",
4958            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
4959        ),
4960        (
4961            "replica_id",
4962            "The ID of the replica that an instance of a sink is running on.",
4963        ),
4964    ]),
4965    is_retained_metrics_object: false,
4966    access: vec![PUBLIC_SELECT],
4967});
4968
4969pub static MZ_SINK_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
4970    name: "mz_sink_statuses",
4971    schema: MZ_INTERNAL_SCHEMA,
4972    oid: oid::VIEW_MZ_SINK_STATUSES_OID,
4973    desc: RelationDesc::builder()
4974        .with_column("id", SqlScalarType::String.nullable(false))
4975        .with_column("name", SqlScalarType::String.nullable(false))
4976        .with_column("type", SqlScalarType::String.nullable(false))
4977        .with_column(
4978            "last_status_change_at",
4979            SqlScalarType::TimestampTz { precision: None }.nullable(true),
4980        )
4981        .with_column("status", SqlScalarType::String.nullable(false))
4982        .with_column("error", SqlScalarType::String.nullable(true))
4983        .with_column("details", SqlScalarType::Jsonb.nullable(true))
4984        .finish(),
4985    column_comments: BTreeMap::from_iter([
4986        (
4987            "id",
4988            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
4989        ),
4990        ("name", "The name of the sink."),
4991        ("type", "The type of the sink."),
4992        (
4993            "last_status_change_at",
4994            "Wall-clock timestamp of the sink status change.",
4995        ),
4996        (
4997            "status",
4998            "The status of the sink: one of `created`, `starting`, `running`, `stalled`, `failed`, or `dropped`.",
4999        ),
5000        (
5001            "error",
5002            "If the sink is in an error state, the error message.",
5003        ),
5004        (
5005            "details",
5006            "Additional metadata provided by the sink. In case of error, may contain a `hint` field with helpful suggestions.",
5007        ),
5008    ]),
5009    sql: "
5010WITH
5011-- The status history contains per-replica events and sink-global events.
5012-- For the latter, replica_id is NULL. We turn these into '<sink>', so that
5013-- we can treat them uniformly below.
5014uniform_status_history AS
5015(
5016    SELECT
5017        s.sink_id,
5018        COALESCE(s.replica_id, '<sink>') as replica_id,
5019        s.occurred_at,
5020        s.status,
5021        s.error,
5022        s.details
5023    FROM mz_internal.mz_sink_status_history s
5024),
5025-- For getting the latest events, we first determine the latest per-replica
5026-- events here and then apply precedence rules below.
5027latest_per_replica_events AS
5028(
5029    SELECT DISTINCT ON (sink_id, replica_id)
5030        occurred_at, sink_id, replica_id, status, error, details
5031    FROM uniform_status_history
5032    ORDER BY sink_id, replica_id, occurred_at DESC
5033),
5034-- We have a precedence list that determines the overall status in case
5035-- there is differing per-replica (including sink-global) statuses. If
5036-- there is no 'dropped' status, and any replica reports 'running', the
5037-- overall status is 'running' even if there might be some replica that has
5038-- errors or is paused.
5039latest_events AS
5040(
5041    SELECT DISTINCT ON (sink_id)
5042        sink_id,
5043        occurred_at,
5044        status,
5045        error,
5046        details
5047    FROM latest_per_replica_events
5048    ORDER BY sink_id, CASE status
5049                WHEN 'dropped' THEN 1
5050                WHEN 'running' THEN 2
5051                WHEN 'stalled' THEN 3
5052                WHEN 'starting' THEN 4
5053                WHEN 'paused' THEN 5
5054                WHEN 'ceased' THEN 6
5055                ELSE 7  -- For any other status values
5056            END
5057)
5058SELECT
5059    mz_sinks.id,
5060    name,
5061    mz_sinks.type,
5062    occurred_at as last_status_change_at,
5063    coalesce(status, 'created') as status,
5064    error,
5065    details
5066FROM mz_catalog.mz_sinks
5067LEFT JOIN latest_events ON mz_sinks.id = latest_events.sink_id
5068WHERE
5069    -- This is a convenient way to filter out system sinks, like the status_history table itself.
5070    mz_sinks.id NOT LIKE 's%'",
5071    access: vec![PUBLIC_SELECT],
5072});
5073
5074pub static MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION: LazyLock<SystemObjectDescription> =
5075    LazyLock::new(|| SystemObjectDescription {
5076        schema_name: MZ_STORAGE_USAGE_BY_SHARD.schema.to_string(),
5077        object_type: CatalogItemType::Table,
5078        object_name: MZ_STORAGE_USAGE_BY_SHARD.name.to_string(),
5079    });
5080
5081pub static MZ_STORAGE_USAGE_BY_SHARD: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5082    name: "mz_storage_usage_by_shard",
5083    schema: MZ_INTERNAL_SCHEMA,
5084    oid: oid::TABLE_MZ_STORAGE_USAGE_BY_SHARD_OID,
5085    desc: RelationDesc::builder()
5086        .with_column("id", SqlScalarType::UInt64.nullable(false))
5087        .with_column("shard_id", SqlScalarType::String.nullable(true))
5088        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
5089        .with_column(
5090            "collection_timestamp",
5091            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5092        )
5093        .finish(),
5094    column_comments: BTreeMap::new(),
5095    is_retained_metrics_object: false,
5096    access: vec![PUBLIC_SELECT],
5097});
5098
5099pub static MZ_EGRESS_IPS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5100    name: "mz_egress_ips",
5101    schema: MZ_CATALOG_SCHEMA,
5102    oid: oid::TABLE_MZ_EGRESS_IPS_OID,
5103    desc: RelationDesc::builder()
5104        .with_column("egress_ip", SqlScalarType::String.nullable(false))
5105        .with_column("prefix_length", SqlScalarType::Int32.nullable(false))
5106        .with_column("cidr", SqlScalarType::String.nullable(false))
5107        .finish(),
5108    column_comments: BTreeMap::from_iter([
5109        ("egress_ip", "The start of the range of IP addresses."),
5110        (
5111            "prefix_length",
5112            "The number of leading bits in the CIDR netmask.",
5113        ),
5114        ("cidr", "The CIDR representation."),
5115    ]),
5116    is_retained_metrics_object: false,
5117    access: vec![PUBLIC_SELECT],
5118});
5119
5120pub static MZ_AWS_PRIVATELINK_CONNECTIONS: LazyLock<BuiltinTable> =
5121    LazyLock::new(|| BuiltinTable {
5122        name: "mz_aws_privatelink_connections",
5123        schema: MZ_CATALOG_SCHEMA,
5124        oid: oid::TABLE_MZ_AWS_PRIVATELINK_CONNECTIONS_OID,
5125        desc: RelationDesc::builder()
5126            .with_column("id", SqlScalarType::String.nullable(false))
5127            .with_column("principal", SqlScalarType::String.nullable(false))
5128            .finish(),
5129        column_comments: BTreeMap::from_iter([
5130            ("id", "The ID of the connection."),
5131            (
5132                "principal",
5133                "The AWS Principal that Materialize will use to connect to the VPC endpoint.",
5134            ),
5135        ]),
5136        is_retained_metrics_object: false,
5137        access: vec![PUBLIC_SELECT],
5138    });
5139
5140pub static MZ_AWS_CONNECTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5141    name: "mz_aws_connections",
5142    schema: MZ_INTERNAL_SCHEMA,
5143    oid: oid::TABLE_MZ_AWS_CONNECTIONS_OID,
5144    desc: RelationDesc::builder()
5145        .with_column("id", SqlScalarType::String.nullable(false))
5146        .with_column("endpoint", SqlScalarType::String.nullable(true))
5147        .with_column("region", SqlScalarType::String.nullable(true))
5148        .with_column("access_key_id", SqlScalarType::String.nullable(true))
5149        .with_column(
5150            "access_key_id_secret_id",
5151            SqlScalarType::String.nullable(true),
5152        )
5153        .with_column(
5154            "secret_access_key_secret_id",
5155            SqlScalarType::String.nullable(true),
5156        )
5157        .with_column("session_token", SqlScalarType::String.nullable(true))
5158        .with_column(
5159            "session_token_secret_id",
5160            SqlScalarType::String.nullable(true),
5161        )
5162        .with_column("assume_role_arn", SqlScalarType::String.nullable(true))
5163        .with_column(
5164            "assume_role_session_name",
5165            SqlScalarType::String.nullable(true),
5166        )
5167        .with_column("principal", SqlScalarType::String.nullable(true))
5168        .with_column("external_id", SqlScalarType::String.nullable(true))
5169        .with_column("example_trust_policy", SqlScalarType::Jsonb.nullable(true))
5170        .finish(),
5171    column_comments: BTreeMap::from_iter([
5172        ("id", "The ID of the connection."),
5173        ("endpoint", "The value of the `ENDPOINT` option, if set."),
5174        ("region", "The value of the `REGION` option, if set."),
5175        (
5176            "access_key_id",
5177            "The value of the `ACCESS KEY ID` option, if provided in line.",
5178        ),
5179        (
5180            "access_key_id_secret_id",
5181            "The ID of the secret referenced by the `ACCESS KEY ID` option, if provided via a secret.",
5182        ),
5183        (
5184            "secret_access_key_secret_id",
5185            "The ID of the secret referenced by the `SECRET ACCESS KEY` option, if set.",
5186        ),
5187        (
5188            "session_token",
5189            "The value of the `SESSION TOKEN` option, if provided in line.",
5190        ),
5191        (
5192            "session_token_secret_id",
5193            "The ID of the secret referenced by the `SESSION TOKEN` option, if provided via a secret.",
5194        ),
5195        (
5196            "assume_role_arn",
5197            "The value of the `ASSUME ROLE ARN` option, if set.",
5198        ),
5199        (
5200            "assume_role_session_name",
5201            "The value of the `ASSUME ROLE SESSION NAME` option, if set.",
5202        ),
5203        (
5204            "principal",
5205            "The ARN of the AWS principal Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
5206        ),
5207        (
5208            "external_id",
5209            "The external ID Materialize will use when assuming the provided role, if the connection is configured to use role assumption.",
5210        ),
5211        (
5212            "example_trust_policy",
5213            "An example of an IAM role trust policy that allows this connection's principal and external ID to assume the role.",
5214        ),
5215    ]),
5216    is_retained_metrics_object: false,
5217    access: vec![PUBLIC_SELECT],
5218});
5219
5220pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY: LazyLock<BuiltinSource> =
5221    LazyLock::new(|| BuiltinSource {
5222        name: "mz_cluster_replica_metrics_history",
5223        schema: MZ_INTERNAL_SCHEMA,
5224        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
5225        data_source: IntrospectionType::ReplicaMetricsHistory.into(),
5226        desc: REPLICA_METRICS_HISTORY_DESC.clone(),
5227        column_comments: BTreeMap::from_iter([
5228            ("replica_id", "The ID of a cluster replica."),
5229            ("process_id", "The ID of a process within the replica."),
5230            (
5231                "cpu_nano_cores",
5232                "Approximate CPU usage, in billionths of a vCPU core.",
5233            ),
5234            ("memory_bytes", "Approximate memory usage, in bytes."),
5235            ("disk_bytes", "Approximate disk usage, in bytes."),
5236            (
5237                "occurred_at",
5238                "Wall-clock timestamp at which the event occurred.",
5239            ),
5240            (
5241                "heap_bytes",
5242                "Approximate heap (RAM + swap) usage, in bytes.",
5243            ),
5244            ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
5245        ]),
5246        is_retained_metrics_object: false,
5247        access: vec![PUBLIC_SELECT],
5248    });
5249
5250pub static MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(
5251    || {
5252        BuiltinContinualTask {
5253            name: "mz_cluster_replica_metrics_history_ct",
5254            schema: MZ_INTERNAL_SCHEMA,
5255            oid: oid::CT_MZ_CLUSTER_REPLICA_METRICS_HISTORY_OID,
5256            desc: REPLICA_METRICS_HISTORY_DESC.clone(),
5257            sql: "
5258IN CLUSTER mz_catalog_server
5259ON INPUT mz_internal.mz_cluster_replica_metrics_history AS (
5260    DELETE FROM mz_internal.mz_cluster_replica_metrics_history_ct WHERE occurred_at + '30d' < mz_now();
5261    INSERT INTO mz_internal.mz_cluster_replica_metrics_history_ct SELECT * FROM mz_internal.mz_cluster_replica_metrics_history;
5262)",
5263            access: vec![PUBLIC_SELECT],
5264        }
5265    },
5266);
5267
5268pub static MZ_CLUSTER_REPLICA_METRICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5269    name: "mz_cluster_replica_metrics",
5270    schema: MZ_INTERNAL_SCHEMA,
5271    oid: oid::VIEW_MZ_CLUSTER_REPLICA_METRICS_OID,
5272    desc: RelationDesc::builder()
5273        .with_column("replica_id", SqlScalarType::String.nullable(false))
5274        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
5275        .with_column("cpu_nano_cores", SqlScalarType::UInt64.nullable(true))
5276        .with_column("memory_bytes", SqlScalarType::UInt64.nullable(true))
5277        .with_column("disk_bytes", SqlScalarType::UInt64.nullable(true))
5278        .with_column("heap_bytes", SqlScalarType::UInt64.nullable(true))
5279        .with_column("heap_limit", SqlScalarType::UInt64.nullable(true))
5280        .with_key(vec![0, 1])
5281        .finish(),
5282    column_comments: BTreeMap::from_iter([
5283        ("replica_id", "The ID of a cluster replica."),
5284        ("process_id", "The ID of a process within the replica."),
5285        (
5286            "cpu_nano_cores",
5287            "Approximate CPU usage, in billionths of a vCPU core.",
5288        ),
5289        ("memory_bytes", "Approximate RAM usage, in bytes."),
5290        ("disk_bytes", "Approximate disk usage, in bytes."),
5291        (
5292            "heap_bytes",
5293            "Approximate heap (RAM + swap) usage, in bytes.",
5294        ),
5295        ("heap_limit", "Available heap (RAM + swap) space, in bytes."),
5296    ]),
5297    sql: "
5298SELECT
5299    DISTINCT ON (replica_id, process_id)
5300    replica_id,
5301    process_id,
5302    cpu_nano_cores,
5303    memory_bytes,
5304    disk_bytes,
5305    heap_bytes,
5306    heap_limit
5307FROM mz_internal.mz_cluster_replica_metrics_history
5308JOIN mz_cluster_replicas r ON r.id = replica_id
5309ORDER BY replica_id, process_id, occurred_at DESC",
5310    access: vec![PUBLIC_SELECT],
5311});
5312
5313pub static MZ_CLUSTER_REPLICA_FRONTIERS: LazyLock<BuiltinSource> =
5314    LazyLock::new(|| BuiltinSource {
5315        name: "mz_cluster_replica_frontiers",
5316        schema: MZ_CATALOG_SCHEMA,
5317        oid: oid::SOURCE_MZ_CLUSTER_REPLICA_FRONTIERS_OID,
5318        data_source: IntrospectionType::ReplicaFrontiers.into(),
5319        desc: RelationDesc::builder()
5320            .with_column("object_id", SqlScalarType::String.nullable(false))
5321            .with_column("replica_id", SqlScalarType::String.nullable(false))
5322            .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5323            .finish(),
5324        column_comments: BTreeMap::from_iter([
5325            (
5326                "object_id",
5327                "The ID of the source, sink, index, materialized view, or subscription.",
5328            ),
5329            ("replica_id", "The ID of a cluster replica."),
5330            (
5331                "write_frontier",
5332                "The next timestamp at which the output may change.",
5333            ),
5334        ]),
5335        is_retained_metrics_object: false,
5336        access: vec![PUBLIC_SELECT],
5337    });
5338
5339pub static MZ_CLUSTER_REPLICA_FRONTIERS_IND: LazyLock<BuiltinIndex> =
5340    LazyLock::new(|| BuiltinIndex {
5341        name: "mz_cluster_replica_frontiers_ind",
5342        schema: MZ_CATALOG_SCHEMA,
5343        oid: oid::INDEX_MZ_CLUSTER_REPLICA_FRONTIERS_IND_OID,
5344        sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_cluster_replica_frontiers (object_id)",
5345        is_retained_metrics_object: false,
5346    });
5347
5348pub static MZ_FRONTIERS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5349    name: "mz_frontiers",
5350    schema: MZ_INTERNAL_SCHEMA,
5351    oid: oid::SOURCE_MZ_FRONTIERS_OID,
5352    data_source: IntrospectionType::Frontiers.into(),
5353    desc: RelationDesc::builder()
5354        .with_column("object_id", SqlScalarType::String.nullable(false))
5355        .with_column("read_frontier", SqlScalarType::MzTimestamp.nullable(true))
5356        .with_column("write_frontier", SqlScalarType::MzTimestamp.nullable(true))
5357        .finish(),
5358    column_comments: BTreeMap::from_iter([
5359        (
5360            "object_id",
5361            "The ID of the source, sink, table, index, materialized view, or subscription.",
5362        ),
5363        (
5364            "read_frontier",
5365            "The earliest timestamp at which the output is still readable.",
5366        ),
5367        (
5368            "write_frontier",
5369            "The next timestamp at which the output may change.",
5370        ),
5371    ]),
5372    is_retained_metrics_object: false,
5373    access: vec![PUBLIC_SELECT],
5374});
5375
5376/// DEPRECATED and scheduled for removal! Use `mz_frontiers` instead.
5377pub static MZ_GLOBAL_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5378    name: "mz_global_frontiers",
5379    schema: MZ_INTERNAL_SCHEMA,
5380    oid: oid::VIEW_MZ_GLOBAL_FRONTIERS_OID,
5381    desc: RelationDesc::builder()
5382        .with_column("object_id", SqlScalarType::String.nullable(false))
5383        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
5384        .finish(),
5385    column_comments: BTreeMap::new(),
5386    sql: "
5387SELECT object_id, write_frontier AS time
5388FROM mz_internal.mz_frontiers
5389WHERE write_frontier IS NOT NULL",
5390    access: vec![PUBLIC_SELECT],
5391});
5392
5393pub static MZ_WALLCLOCK_LAG_HISTORY: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5394    name: "mz_wallclock_lag_history",
5395    schema: MZ_INTERNAL_SCHEMA,
5396    oid: oid::SOURCE_MZ_WALLCLOCK_LAG_HISTORY_OID,
5397    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5398    data_source: IntrospectionType::WallclockLagHistory.into(),
5399    column_comments: BTreeMap::from_iter([
5400        (
5401            "object_id",
5402            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5403        ),
5404        (
5405            "replica_id",
5406            "The ID of a replica computing the object, or `NULL` for persistent objects. Corresponds to `mz_cluster_replicas.id`.",
5407        ),
5408        (
5409            "lag",
5410            "The amount of time the object's write frontier lags behind wallclock time.",
5411        ),
5412        (
5413            "occurred_at",
5414            "Wall-clock timestamp at which the event occurred.",
5415        ),
5416    ]),
5417    is_retained_metrics_object: false,
5418    access: vec![PUBLIC_SELECT],
5419});
5420
5421pub static MZ_WALLCLOCK_LAG_HISTORY_CT: LazyLock<BuiltinContinualTask> = LazyLock::new(|| {
5422    BuiltinContinualTask {
5423    name: "mz_wallclock_lag_history_ct",
5424    schema: MZ_INTERNAL_SCHEMA,
5425    oid: oid::CT_MZ_WALLCLOCK_LAG_HISTORY_OID,
5426    desc: WALLCLOCK_LAG_HISTORY_DESC.clone(),
5427    sql: "
5428IN CLUSTER mz_catalog_server
5429ON INPUT mz_internal.mz_wallclock_lag_history AS (
5430    DELETE FROM mz_internal.mz_wallclock_lag_history_ct WHERE occurred_at + '30d' < mz_now();
5431    INSERT INTO mz_internal.mz_wallclock_lag_history_ct SELECT * FROM mz_internal.mz_wallclock_lag_history;
5432)",
5433            access: vec![PUBLIC_SELECT],
5434        }
5435});
5436
5437pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5438    name: "mz_wallclock_global_lag_history",
5439    schema: MZ_INTERNAL_SCHEMA,
5440    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTORY_OID,
5441    desc: RelationDesc::builder()
5442        .with_column("object_id", SqlScalarType::String.nullable(false))
5443        .with_column("lag", SqlScalarType::Interval.nullable(true))
5444        .with_column(
5445            "occurred_at",
5446            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5447        )
5448        .with_key(vec![0, 2])
5449        .finish(),
5450    column_comments: BTreeMap::from_iter([
5451        (
5452            "object_id",
5453            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5454        ),
5455        (
5456            "lag",
5457            "The minimum wallclock lag observed for the object during the minute.",
5458        ),
5459        (
5460            "occurred_at",
5461            "The minute-aligned timestamp of the observation.",
5462        ),
5463    ]),
5464    sql: "
5465WITH times_binned AS (
5466    SELECT
5467        object_id,
5468        lag,
5469        date_trunc('minute', occurred_at) AS occurred_at
5470    FROM mz_internal.mz_wallclock_lag_history
5471)
5472SELECT
5473    object_id,
5474    min(lag) AS lag,
5475    occurred_at
5476FROM times_binned
5477GROUP BY object_id, occurred_at
5478OPTIONS (AGGREGATE INPUT GROUP SIZE = 1)",
5479    access: vec![PUBLIC_SELECT],
5480});
5481
5482pub static MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| {
5483    BuiltinView {
5484        name: "mz_wallclock_global_lag_recent_history",
5485        schema: MZ_INTERNAL_SCHEMA,
5486        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_OID,
5487        desc: RelationDesc::builder()
5488            .with_column("object_id", SqlScalarType::String.nullable(false))
5489            .with_column("lag", SqlScalarType::Interval.nullable(true))
5490            .with_column(
5491                "occurred_at",
5492                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5493            )
5494            .with_key(vec![0, 2])
5495            .finish(),
5496        column_comments: BTreeMap::from_iter([
5497            (
5498                "object_id",
5499                "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5500            ),
5501            (
5502                "lag",
5503                "The minimum wallclock lag observed for the object during the minute.",
5504            ),
5505            (
5506                "occurred_at",
5507                "The minute-aligned timestamp of the observation.",
5508            ),
5509        ]),
5510        sql: "
5511SELECT object_id, lag, occurred_at
5512FROM mz_internal.mz_wallclock_global_lag_history
5513WHERE occurred_at + '1 day' > mz_now()",
5514        access: vec![PUBLIC_SELECT],
5515    }
5516});
5517
5518pub static MZ_WALLCLOCK_GLOBAL_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5519    name: "mz_wallclock_global_lag",
5520    schema: MZ_INTERNAL_SCHEMA,
5521    oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_OID,
5522    desc: RelationDesc::builder()
5523        .with_column("object_id", SqlScalarType::String.nullable(false))
5524        .with_column("lag", SqlScalarType::Interval.nullable(true))
5525        .with_key(vec![0])
5526        .finish(),
5527    column_comments: BTreeMap::from_iter([
5528        (
5529            "object_id",
5530            "The ID of the table, source, materialized view, index, or sink. Corresponds to `mz_objects.id`.",
5531        ),
5532        (
5533            "lag",
5534            "The amount of time the object's write frontier lags behind wallclock time.",
5535        ),
5536    ]),
5537    sql: "
5538SELECT DISTINCT ON (object_id) object_id, lag
5539FROM mz_internal.mz_wallclock_global_lag_recent_history
5540WHERE occurred_at + '5 minutes' > mz_now()
5541ORDER BY object_id, occurred_at DESC",
5542    access: vec![PUBLIC_SELECT],
5543});
5544
5545pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW: LazyLock<BuiltinSource> =
5546    LazyLock::new(|| BuiltinSource {
5547        name: "mz_wallclock_global_lag_histogram_raw",
5548        schema: MZ_INTERNAL_SCHEMA,
5549        oid: oid::SOURCE_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_OID,
5550        desc: WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW_DESC.clone(),
5551        column_comments: BTreeMap::new(),
5552        data_source: IntrospectionType::WallclockLagHistogram.into(),
5553        is_retained_metrics_object: false,
5554        access: vec![PUBLIC_SELECT],
5555    });
5556
5557pub static MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM: LazyLock<BuiltinView> =
5558    LazyLock::new(|| BuiltinView {
5559        name: "mz_wallclock_global_lag_histogram",
5560        schema: MZ_INTERNAL_SCHEMA,
5561        oid: oid::VIEW_MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_OID,
5562        desc: RelationDesc::builder()
5563            .with_column(
5564                "period_start",
5565                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5566            )
5567            .with_column(
5568                "period_end",
5569                SqlScalarType::TimestampTz { precision: None }.nullable(false),
5570            )
5571            .with_column("object_id", SqlScalarType::String.nullable(false))
5572            .with_column("lag_seconds", SqlScalarType::UInt64.nullable(true))
5573            .with_column("labels", SqlScalarType::Jsonb.nullable(false))
5574            .with_column("count", SqlScalarType::Int64.nullable(false))
5575            .with_key(vec![0, 1, 2, 3, 4])
5576            .finish(),
5577        column_comments: BTreeMap::new(),
5578        sql: "
5579SELECT *, count(*) AS count
5580FROM mz_internal.mz_wallclock_global_lag_histogram_raw
5581GROUP BY period_start, period_end, object_id, lag_seconds, labels",
5582        access: vec![PUBLIC_SELECT],
5583    });
5584
5585pub static MZ_MATERIALIZED_VIEW_REFRESHES: LazyLock<BuiltinSource> = LazyLock::new(|| {
5586    BuiltinSource {
5587        name: "mz_materialized_view_refreshes",
5588        schema: MZ_INTERNAL_SCHEMA,
5589        oid: oid::SOURCE_MZ_MATERIALIZED_VIEW_REFRESHES_OID,
5590        data_source: DataSourceDesc::Introspection(
5591            IntrospectionType::ComputeMaterializedViewRefreshes,
5592        ),
5593        desc: RelationDesc::builder()
5594            .with_column(
5595                "materialized_view_id",
5596                SqlScalarType::String.nullable(false),
5597            )
5598            .with_column(
5599                "last_completed_refresh",
5600                SqlScalarType::MzTimestamp.nullable(true),
5601            )
5602            .with_column("next_refresh", SqlScalarType::MzTimestamp.nullable(true))
5603            .finish(),
5604        column_comments: BTreeMap::from_iter([
5605            (
5606                "materialized_view_id",
5607                "The ID of the materialized view. Corresponds to `mz_catalog.mz_materialized_views.id`",
5608            ),
5609            (
5610                "last_completed_refresh",
5611                "The time of the last successfully completed refresh. `NULL` if the materialized view hasn't completed any refreshes yet.",
5612            ),
5613            (
5614                "next_refresh",
5615                "The time of the next scheduled refresh. `NULL` if the materialized view has no future scheduled refreshes.",
5616            ),
5617        ]),
5618        is_retained_metrics_object: false,
5619        access: vec![PUBLIC_SELECT],
5620    }
5621});
5622
5623pub static MZ_SUBSCRIPTIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5624    name: "mz_subscriptions",
5625    schema: MZ_INTERNAL_SCHEMA,
5626    oid: oid::TABLE_MZ_SUBSCRIPTIONS_OID,
5627    desc: RelationDesc::builder()
5628        .with_column("id", SqlScalarType::String.nullable(false))
5629        .with_column("session_id", SqlScalarType::Uuid.nullable(false))
5630        .with_column("cluster_id", SqlScalarType::String.nullable(false))
5631        .with_column(
5632            "created_at",
5633            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5634        )
5635        .with_column(
5636            "referenced_object_ids",
5637            SqlScalarType::List {
5638                element_type: Box::new(SqlScalarType::String),
5639                custom_id: None,
5640            }
5641            .nullable(false),
5642        )
5643        .finish(),
5644    column_comments: BTreeMap::from_iter([
5645        ("id", "The ID of the subscription."),
5646        (
5647            "session_id",
5648            "The ID of the session that runs the subscription. Corresponds to `mz_sessions.id`.",
5649        ),
5650        (
5651            "cluster_id",
5652            "The ID of the cluster on which the subscription is running. Corresponds to `mz_clusters.id`.",
5653        ),
5654        (
5655            "created_at",
5656            "The time at which the subscription was created.",
5657        ),
5658        (
5659            "referenced_object_ids",
5660            "The IDs of objects referenced by the subscription. Corresponds to `mz_objects.id`",
5661        ),
5662    ]),
5663    is_retained_metrics_object: false,
5664    access: vec![PUBLIC_SELECT],
5665});
5666
5667pub static MZ_SESSIONS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5668    name: "mz_sessions",
5669    schema: MZ_INTERNAL_SCHEMA,
5670    oid: oid::TABLE_MZ_SESSIONS_OID,
5671    desc: RelationDesc::builder()
5672        .with_column("id", SqlScalarType::Uuid.nullable(false))
5673        .with_column("connection_id", SqlScalarType::UInt32.nullable(false))
5674        .with_column("role_id", SqlScalarType::String.nullable(false))
5675        .with_column("client_ip", SqlScalarType::String.nullable(true))
5676        .with_column(
5677            "connected_at",
5678            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5679        )
5680        .finish(),
5681    column_comments: BTreeMap::from_iter([
5682        ("id", "The globally unique ID of the session."),
5683        (
5684            "connection_id",
5685            "The connection ID of the session. Unique only for active sessions and can be recycled. Corresponds to `pg_backend_pid()`.",
5686        ),
5687        (
5688            "role_id",
5689            "The role ID of the role that the session is logged in as. Corresponds to `mz_catalog.mz_roles`.",
5690        ),
5691        (
5692            "client_ip",
5693            "The IP address of the client that initiated the session.",
5694        ),
5695        (
5696            "connected_at",
5697            "The time at which the session connected to the system.",
5698        ),
5699    ]),
5700    is_retained_metrics_object: false,
5701    access: vec![PUBLIC_SELECT],
5702});
5703
5704pub static MZ_DEFAULT_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5705    name: "mz_default_privileges",
5706    schema: MZ_CATALOG_SCHEMA,
5707    oid: oid::TABLE_MZ_DEFAULT_PRIVILEGES_OID,
5708    desc: RelationDesc::builder()
5709        .with_column("role_id", SqlScalarType::String.nullable(false))
5710        .with_column("database_id", SqlScalarType::String.nullable(true))
5711        .with_column("schema_id", SqlScalarType::String.nullable(true))
5712        .with_column("object_type", SqlScalarType::String.nullable(false))
5713        .with_column("grantee", SqlScalarType::String.nullable(false))
5714        .with_column("privileges", SqlScalarType::String.nullable(false))
5715        .finish(),
5716    column_comments: BTreeMap::from_iter([
5717        (
5718            "role_id",
5719            "Privileges described in this row will be granted on objects created by `role_id`. The role ID `p` stands for the `PUBLIC` pseudo-role and applies to all roles.",
5720        ),
5721        (
5722            "database_id",
5723            "Privileges described in this row will be granted only on objects in the database identified by `database_id` if non-null.",
5724        ),
5725        (
5726            "schema_id",
5727            "Privileges described in this row will be granted only on objects in the schema identified by `schema_id` if non-null.",
5728        ),
5729        (
5730            "object_type",
5731            "Privileges described in this row will be granted only on objects of type `object_type`.",
5732        ),
5733        (
5734            "grantee",
5735            "Privileges described in this row will be granted to `grantee`. The role ID `p` stands for the `PUBLIC` pseudo-role and applies to all roles.",
5736        ),
5737        ("privileges", "The set of privileges that will be granted."),
5738    ]),
5739    is_retained_metrics_object: false,
5740    access: vec![PUBLIC_SELECT],
5741});
5742
5743pub static MZ_SYSTEM_PRIVILEGES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5744    name: "mz_system_privileges",
5745    schema: MZ_CATALOG_SCHEMA,
5746    oid: oid::TABLE_MZ_SYSTEM_PRIVILEGES_OID,
5747    desc: RelationDesc::builder()
5748        .with_column("privileges", SqlScalarType::MzAclItem.nullable(false))
5749        .finish(),
5750    column_comments: BTreeMap::from_iter([(
5751        "privileges",
5752        "The privileges belonging to the system.",
5753    )]),
5754    is_retained_metrics_object: false,
5755    access: vec![PUBLIC_SELECT],
5756});
5757
5758pub static MZ_COMMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5759    name: "mz_comments",
5760    schema: MZ_INTERNAL_SCHEMA,
5761    oid: oid::TABLE_MZ_COMMENTS_OID,
5762    desc: RelationDesc::builder()
5763        .with_column("id", SqlScalarType::String.nullable(false))
5764        .with_column("object_type", SqlScalarType::String.nullable(false))
5765        .with_column("object_sub_id", SqlScalarType::Int32.nullable(true))
5766        .with_column("comment", SqlScalarType::String.nullable(false))
5767        .finish(),
5768    column_comments: BTreeMap::from_iter([
5769        (
5770            "id",
5771            "The ID of the object. Corresponds to `mz_objects.id`.",
5772        ),
5773        (
5774            "object_type",
5775            "The type of object the comment is associated with.",
5776        ),
5777        (
5778            "object_sub_id",
5779            "For a comment on a column of a relation, the column number. `NULL` for other object types.",
5780        ),
5781        ("comment", "The comment itself."),
5782    ]),
5783    is_retained_metrics_object: false,
5784    access: vec![PUBLIC_SELECT],
5785});
5786
5787pub static MZ_SOURCE_REFERENCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5788    name: "mz_source_references",
5789    schema: MZ_INTERNAL_SCHEMA,
5790    oid: oid::TABLE_MZ_SOURCE_REFERENCES_OID,
5791    desc: RelationDesc::builder()
5792        .with_column("source_id", SqlScalarType::String.nullable(false))
5793        .with_column("namespace", SqlScalarType::String.nullable(true))
5794        .with_column("name", SqlScalarType::String.nullable(false))
5795        .with_column(
5796            "updated_at",
5797            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5798        )
5799        .with_column(
5800            "columns",
5801            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
5802        )
5803        .finish(),
5804    column_comments: BTreeMap::new(),
5805    is_retained_metrics_object: false,
5806    access: vec![PUBLIC_SELECT],
5807});
5808
5809pub static MZ_WEBHOOKS_SOURCES: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5810    name: "mz_webhook_sources",
5811    schema: MZ_INTERNAL_SCHEMA,
5812    oid: oid::TABLE_MZ_WEBHOOK_SOURCES_OID,
5813    desc: RelationDesc::builder()
5814        .with_column("id", SqlScalarType::String.nullable(false))
5815        .with_column("name", SqlScalarType::String.nullable(false))
5816        .with_column("url", SqlScalarType::String.nullable(false))
5817        .finish(),
5818    column_comments: BTreeMap::from_iter([
5819        (
5820            "id",
5821            "The ID of the webhook source. Corresponds to `mz_sources.id`.",
5822        ),
5823        ("name", "The name of the webhook source."),
5824        (
5825            "url",
5826            "The URL which can be used to send events to the source.",
5827        ),
5828    ]),
5829    is_retained_metrics_object: false,
5830    access: vec![PUBLIC_SELECT],
5831});
5832
5833pub static MZ_HISTORY_RETENTION_STRATEGIES: LazyLock<BuiltinTable> = LazyLock::new(|| {
5834    BuiltinTable {
5835        name: "mz_history_retention_strategies",
5836        schema: MZ_INTERNAL_SCHEMA,
5837        oid: oid::TABLE_MZ_HISTORY_RETENTION_STRATEGIES_OID,
5838        desc: RelationDesc::builder()
5839            .with_column("id", SqlScalarType::String.nullable(false))
5840            .with_column("strategy", SqlScalarType::String.nullable(false))
5841            .with_column("value", SqlScalarType::Jsonb.nullable(false))
5842            .finish(),
5843        column_comments: BTreeMap::from_iter([
5844            ("id", "The ID of the object."),
5845            (
5846                "strategy",
5847                "The strategy. `FOR` is the only strategy, and means the object's compaction window is the duration of the `value` field.",
5848            ),
5849            (
5850                "value",
5851                "The value of the strategy. For `FOR`, is a number of milliseconds.",
5852            ),
5853        ]),
5854        is_retained_metrics_object: false,
5855        access: vec![PUBLIC_SELECT],
5856    }
5857});
5858
5859pub static MZ_LICENSE_KEYS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5860    name: "mz_license_keys",
5861    schema: MZ_INTERNAL_SCHEMA,
5862    oid: oid::TABLE_MZ_LICENSE_KEYS_OID,
5863    desc: RelationDesc::builder()
5864        .with_column("id", SqlScalarType::String.nullable(false))
5865        .with_column("organization", SqlScalarType::String.nullable(false))
5866        .with_column("environment_id", SqlScalarType::String.nullable(false))
5867        .with_column(
5868            "expiration",
5869            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5870        )
5871        .with_column(
5872            "not_before",
5873            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5874        )
5875        .finish(),
5876    column_comments: BTreeMap::from_iter([
5877        ("id", "The identifier of the license key."),
5878        (
5879            "organization",
5880            "The name of the organization that this license key was issued to.",
5881        ),
5882        (
5883            "environment_id",
5884            "The environment ID that this license key was issued for.",
5885        ),
5886        (
5887            "expiration",
5888            "The date and time when this license key expires.",
5889        ),
5890        (
5891            "not_before",
5892            "The start of the validity period for this license key.",
5893        ),
5894    ]),
5895    is_retained_metrics_object: false,
5896    access: vec![PUBLIC_SELECT],
5897});
5898
5899pub static MZ_REPLACEMENTS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
5900    name: "mz_replacements",
5901    schema: MZ_INTERNAL_SCHEMA,
5902    oid: oid::TABLE_MZ_REPLACEMENTS_OID,
5903    desc: RelationDesc::builder()
5904        .with_column("id", SqlScalarType::String.nullable(false))
5905        .with_column("target_id", SqlScalarType::String.nullable(false))
5906        .finish(),
5907    column_comments: BTreeMap::from_iter([
5908        (
5909            "id",
5910            "The ID of the replacement object. Corresponds to `mz_objects.id`.",
5911        ),
5912        (
5913            "target_id",
5914            "The ID of the replacement target. Corresponds to `mz_objects.id`.",
5915        ),
5916    ]),
5917    is_retained_metrics_object: false,
5918    access: vec![PUBLIC_SELECT],
5919});
5920
5921// These will be replaced with per-replica tables once source/sink multiplexing on
5922// a single cluster is supported.
5923pub static MZ_SOURCE_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5924    name: "mz_source_statistics_raw",
5925    schema: MZ_INTERNAL_SCHEMA,
5926    oid: oid::SOURCE_MZ_SOURCE_STATISTICS_RAW_OID,
5927    data_source: IntrospectionType::StorageSourceStatistics.into(),
5928    desc: MZ_SOURCE_STATISTICS_RAW_DESC.clone(),
5929    column_comments: BTreeMap::new(),
5930    is_retained_metrics_object: true,
5931    access: vec![PUBLIC_SELECT],
5932});
5933pub static MZ_SINK_STATISTICS_RAW: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5934    name: "mz_sink_statistics_raw",
5935    schema: MZ_INTERNAL_SCHEMA,
5936    oid: oid::SOURCE_MZ_SINK_STATISTICS_RAW_OID,
5937    data_source: IntrospectionType::StorageSinkStatistics.into(),
5938    desc: MZ_SINK_STATISTICS_RAW_DESC.clone(),
5939    column_comments: BTreeMap::new(),
5940    is_retained_metrics_object: true,
5941    access: vec![PUBLIC_SELECT],
5942});
5943
5944pub static MZ_STORAGE_SHARDS: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
5945    name: "mz_storage_shards",
5946    schema: MZ_INTERNAL_SCHEMA,
5947    oid: oid::SOURCE_MZ_STORAGE_SHARDS_OID,
5948    data_source: IntrospectionType::ShardMapping.into(),
5949    desc: RelationDesc::builder()
5950        .with_column("object_id", SqlScalarType::String.nullable(false))
5951        .with_column("shard_id", SqlScalarType::String.nullable(false))
5952        .finish(),
5953    column_comments: BTreeMap::new(),
5954    is_retained_metrics_object: false,
5955    access: vec![PUBLIC_SELECT],
5956});
5957
5958pub static MZ_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
5959    name: "mz_storage_usage",
5960    schema: MZ_CATALOG_SCHEMA,
5961    oid: oid::VIEW_MZ_STORAGE_USAGE_OID,
5962    desc: RelationDesc::builder()
5963        .with_column("object_id", SqlScalarType::String.nullable(false))
5964        .with_column("size_bytes", SqlScalarType::UInt64.nullable(false))
5965        .with_column(
5966            "collection_timestamp",
5967            SqlScalarType::TimestampTz { precision: None }.nullable(false),
5968        )
5969        .with_key(vec![0, 2])
5970        .finish(),
5971    column_comments: BTreeMap::from_iter([
5972        (
5973            "object_id",
5974            "The ID of the table, source, or materialized view.",
5975        ),
5976        (
5977            "size_bytes",
5978            "The number of storage bytes used by the object.",
5979        ),
5980        (
5981            "collection_timestamp",
5982            "The time at which storage usage of the object was assessed.",
5983        ),
5984    ]),
5985    sql: "
5986SELECT
5987    object_id,
5988    sum(size_bytes)::uint8 AS size_bytes,
5989    collection_timestamp
5990FROM
5991    mz_internal.mz_storage_shards
5992    JOIN mz_internal.mz_storage_usage_by_shard USING (shard_id)
5993GROUP BY object_id, collection_timestamp",
5994    access: vec![PUBLIC_SELECT],
5995});
5996
5997pub static MZ_RECENT_STORAGE_USAGE: LazyLock<BuiltinView> = LazyLock::new(|| {
5998    BuiltinView {
5999    name: "mz_recent_storage_usage",
6000    schema: MZ_CATALOG_SCHEMA,
6001    oid: oid::VIEW_MZ_RECENT_STORAGE_USAGE_OID,
6002    desc: RelationDesc::builder()
6003        .with_column("object_id", SqlScalarType::String.nullable(false))
6004        .with_column("size_bytes", SqlScalarType::UInt64.nullable(true))
6005        .with_key(vec![0])
6006        .finish(),
6007    column_comments: BTreeMap::from_iter([
6008        ("object_id", "The ID of the table, source, or materialized view."),
6009        ("size_bytes", "The number of storage bytes used by the object in the most recent assessment."),
6010    ]),
6011    sql: "
6012WITH
6013
6014recent_storage_usage_by_shard AS (
6015    SELECT shard_id, size_bytes, collection_timestamp
6016    FROM mz_internal.mz_storage_usage_by_shard
6017    -- Restricting to the last 6 hours makes it feasible to index the view.
6018    WHERE collection_timestamp + '6 hours' >= mz_now()
6019),
6020
6021most_recent_collection_timestamp_by_shard AS (
6022    SELECT shard_id, max(collection_timestamp) AS collection_timestamp
6023    FROM recent_storage_usage_by_shard
6024    GROUP BY shard_id
6025)
6026
6027SELECT
6028    object_id,
6029    sum(size_bytes)::uint8 AS size_bytes
6030FROM
6031    mz_internal.mz_storage_shards
6032    LEFT JOIN most_recent_collection_timestamp_by_shard
6033        ON mz_storage_shards.shard_id = most_recent_collection_timestamp_by_shard.shard_id
6034    LEFT JOIN recent_storage_usage_by_shard
6035        ON mz_storage_shards.shard_id = recent_storage_usage_by_shard.shard_id
6036        AND most_recent_collection_timestamp_by_shard.collection_timestamp = recent_storage_usage_by_shard.collection_timestamp
6037GROUP BY object_id",
6038    access: vec![PUBLIC_SELECT],
6039}
6040});
6041
6042pub static MZ_RECENT_STORAGE_USAGE_IND: LazyLock<BuiltinIndex> = LazyLock::new(|| BuiltinIndex {
6043    name: "mz_recent_storage_usage_ind",
6044    schema: MZ_CATALOG_SCHEMA,
6045    oid: oid::INDEX_MZ_RECENT_STORAGE_USAGE_IND_OID,
6046    sql: "IN CLUSTER mz_catalog_server ON mz_catalog.mz_recent_storage_usage (object_id)",
6047    is_retained_metrics_object: false,
6048});
6049
6050pub static MZ_RELATIONS: LazyLock<BuiltinView> = LazyLock::new(|| {
6051    BuiltinView {
6052        name: "mz_relations",
6053        schema: MZ_CATALOG_SCHEMA,
6054        oid: oid::VIEW_MZ_RELATIONS_OID,
6055        desc: RelationDesc::builder()
6056            .with_column("id", SqlScalarType::String.nullable(false))
6057            .with_column("oid", SqlScalarType::Oid.nullable(false))
6058            .with_column("schema_id", SqlScalarType::String.nullable(false))
6059            .with_column("name", SqlScalarType::String.nullable(false))
6060            .with_column("type", SqlScalarType::String.nullable(false))
6061            .with_column("owner_id", SqlScalarType::String.nullable(false))
6062            .with_column("cluster_id", SqlScalarType::String.nullable(true))
6063            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(false))
6064            .finish(),
6065        column_comments: BTreeMap::from_iter([
6066            ("id", "Materialize's unique ID for the relation."),
6067            ("oid", "A PostgreSQL-compatible OID for the relation."),
6068            ("schema_id", "The ID of the schema to which the relation belongs. Corresponds to `mz_schemas.id`."),
6069            ("name", "The name of the relation."),
6070            ("type", "The type of the relation: either `table`, `source`, `view`, or `materialized view`."),
6071            ("owner_id", "The role ID of the owner of the relation. Corresponds to `mz_roles.id`."),
6072            ("cluster_id", "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types."),
6073            ("privileges", "The privileges belonging to the relation."),
6074        ]),
6075        sql: "
6076      SELECT id, oid, schema_id, name, 'table' AS type, owner_id, NULL::text AS cluster_id, privileges FROM mz_catalog.mz_tables
6077UNION ALL SELECT id, oid, schema_id, name, 'source', owner_id, cluster_id, privileges FROM mz_catalog.mz_sources
6078UNION ALL SELECT id, oid, schema_id, name, 'view', owner_id, NULL::text, privileges FROM mz_catalog.mz_views
6079UNION ALL SELECT id, oid, schema_id, name, 'materialized-view', owner_id, cluster_id, privileges FROM mz_catalog.mz_materialized_views
6080UNION ALL SELECT id, oid, schema_id, name, 'continual-task', owner_id, cluster_id, privileges FROM mz_internal.mz_continual_tasks",
6081        access: vec![PUBLIC_SELECT],
6082    }
6083});
6084
6085pub static MZ_OBJECTS_ID_NAMESPACE_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6086    name: "mz_objects_id_namespace_types",
6087    schema: MZ_INTERNAL_SCHEMA,
6088    oid: oid::VIEW_MZ_OBJECTS_ID_NAMESPACE_TYPES_OID,
6089    desc: RelationDesc::builder()
6090        .with_column("object_type", SqlScalarType::String.nullable(false))
6091        .with_key(vec![0])
6092        .finish(),
6093    column_comments: BTreeMap::new(),
6094    sql: r#"SELECT *
6095    FROM (
6096        VALUES
6097            ('table'),
6098            ('view'),
6099            ('materialized-view'),
6100            ('source'),
6101            ('sink'),
6102            ('index'),
6103            ('connection'),
6104            ('type'),
6105            ('function'),
6106            ('secret')
6107    )
6108    AS _ (object_type)"#,
6109    access: vec![PUBLIC_SELECT],
6110});
6111
6112pub static MZ_OBJECT_OID_ALIAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6113    name: "mz_object_oid_alias",
6114    schema: MZ_INTERNAL_SCHEMA,
6115    oid: oid::VIEW_MZ_OBJECT_OID_ALIAS_OID,
6116    desc: RelationDesc::builder()
6117        .with_column("object_type", SqlScalarType::String.nullable(false))
6118        .with_column("oid_alias", SqlScalarType::String.nullable(false))
6119        .with_key(vec![0])
6120        .finish(),
6121    column_comments: BTreeMap::new(),
6122    sql: "SELECT object_type, oid_alias
6123    FROM (
6124        VALUES
6125            (
6126                'table'::pg_catalog.text,
6127                'regclass'::pg_catalog.text
6128            ),
6129            ('source', 'regclass'),
6130            ('view', 'regclass'),
6131            ('materialized-view', 'regclass'),
6132            ('index', 'regclass'),
6133            ('type', 'regtype'),
6134            ('function', 'regproc')
6135    )
6136    AS _ (object_type, oid_alias);",
6137    access: vec![PUBLIC_SELECT],
6138});
6139
6140pub static MZ_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| {
6141    BuiltinView {
6142        name: "mz_objects",
6143        schema: MZ_CATALOG_SCHEMA,
6144        oid: oid::VIEW_MZ_OBJECTS_OID,
6145        desc: RelationDesc::builder()
6146            .with_column("id", SqlScalarType::String.nullable(false))
6147            .with_column("oid", SqlScalarType::Oid.nullable(false))
6148            .with_column("schema_id", SqlScalarType::String.nullable(false))
6149            .with_column("name", SqlScalarType::String.nullable(false))
6150            .with_column("type", SqlScalarType::String.nullable(false))
6151            .with_column("owner_id", SqlScalarType::String.nullable(false))
6152            .with_column("cluster_id", SqlScalarType::String.nullable(true))
6153            .with_column("privileges", SqlScalarType::Array(Box::new(SqlScalarType::MzAclItem)).nullable(true))
6154            .finish(),
6155        column_comments: BTreeMap::from_iter([
6156            ("id", "Materialize's unique ID for the object."),
6157            ("oid", "A PostgreSQL-compatible OID for the object."),
6158            ("schema_id", "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`."),
6159            ("name", "The name of the object."),
6160            ("type", "The type of the object: one of `table`, `source`, `view`, `materialized-view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`."),
6161            ("owner_id", "The role ID of the owner of the object. Corresponds to `mz_roles.id`."),
6162            ("cluster_id", "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types."),
6163            ("privileges", "The privileges belonging to the object."),
6164        ]),
6165        sql:
6166        "SELECT id, oid, schema_id, name, type, owner_id, cluster_id, privileges FROM mz_catalog.mz_relations
6167UNION ALL
6168    SELECT id, oid, schema_id, name, 'sink', owner_id, cluster_id, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_sinks
6169UNION ALL
6170    SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index', mz_indexes.owner_id, mz_indexes.cluster_id, NULL::mz_catalog.mz_aclitem[]
6171    FROM mz_catalog.mz_indexes
6172    JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
6173UNION ALL
6174    SELECT id, oid, schema_id, name, 'connection', owner_id, NULL::text, privileges FROM mz_catalog.mz_connections
6175UNION ALL
6176    SELECT id, oid, schema_id, name, 'type', owner_id, NULL::text, privileges FROM mz_catalog.mz_types
6177UNION ALL
6178    SELECT id, oid, schema_id, name, 'function', owner_id, NULL::text, NULL::mz_catalog.mz_aclitem[] FROM mz_catalog.mz_functions
6179UNION ALL
6180    SELECT id, oid, schema_id, name, 'secret', owner_id, NULL::text, privileges FROM mz_catalog.mz_secrets",
6181        access: vec![PUBLIC_SELECT],
6182    }
6183});
6184
6185pub static MZ_OBJECT_FULLY_QUALIFIED_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6186    name: "mz_object_fully_qualified_names",
6187    schema: MZ_INTERNAL_SCHEMA,
6188    oid: oid::VIEW_MZ_OBJECT_FULLY_QUALIFIED_NAMES_OID,
6189    desc: RelationDesc::builder()
6190        .with_column("id", SqlScalarType::String.nullable(false))
6191        .with_column("name", SqlScalarType::String.nullable(false))
6192        .with_column("object_type", SqlScalarType::String.nullable(false))
6193        .with_column("schema_id", SqlScalarType::String.nullable(false))
6194        .with_column("schema_name", SqlScalarType::String.nullable(false))
6195        .with_column("database_id", SqlScalarType::String.nullable(true))
6196        .with_column("database_name", SqlScalarType::String.nullable(true))
6197        .with_column("cluster_id", SqlScalarType::String.nullable(true))
6198        .finish(),
6199    column_comments: BTreeMap::from_iter([
6200        ("id", "Materialize's unique ID for the object."),
6201        ("name", "The name of the object."),
6202        (
6203            "object_type",
6204            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6205        ),
6206        (
6207            "schema_id",
6208            "The ID of the schema to which the object belongs. Corresponds to `mz_schemas.id`.",
6209        ),
6210        (
6211            "schema_name",
6212            "The name of the schema to which the object belongs. Corresponds to `mz_schemas.name`.",
6213        ),
6214        (
6215            "database_id",
6216            "The ID of the database to which the object belongs. Corresponds to `mz_databases.id`.",
6217        ),
6218        (
6219            "database_name",
6220            "The name of the database to which the object belongs. Corresponds to `mz_databases.name`.",
6221        ),
6222        (
6223            "cluster_id",
6224            "The ID of the cluster maintaining the source, materialized view, index, or sink. Corresponds to `mz_clusters.id`. `NULL` for other object types.",
6225        ),
6226    ]),
6227    sql: "
6228    SELECT o.id,
6229        o.name,
6230        o.type as object_type,
6231        sc.id as schema_id,
6232        sc.name as schema_name,
6233        db.id as database_id,
6234        db.name as database_name,
6235        o.cluster_id
6236    FROM mz_catalog.mz_objects o
6237    INNER JOIN mz_catalog.mz_schemas sc ON sc.id = o.schema_id
6238    -- LEFT JOIN accounts for objects in the ambient database.
6239    LEFT JOIN mz_catalog.mz_databases db ON db.id = sc.database_id",
6240    access: vec![PUBLIC_SELECT],
6241});
6242
6243pub static MZ_OBJECT_GLOBAL_IDS: LazyLock<BuiltinTable> = LazyLock::new(|| BuiltinTable {
6244    name: "mz_object_global_ids",
6245    schema: MZ_INTERNAL_SCHEMA,
6246    oid: oid::VIEW_MZ_OBJECT_GLOBAL_IDS_OID,
6247    desc: RelationDesc::builder()
6248        .with_column("id", SqlScalarType::String.nullable(false))
6249        .with_column("global_id", SqlScalarType::String.nullable(false))
6250        .finish(),
6251    column_comments: BTreeMap::from_iter([
6252        (
6253            "id",
6254            "The ID of the object. Corresponds to `mz_objects.id`.",
6255        ),
6256        ("global_id", "The global ID of the object."),
6257    ]),
6258    is_retained_metrics_object: false,
6259    access: vec![PUBLIC_SELECT],
6260});
6261
6262// TODO (SangJunBak): Remove once mz_object_history is released and used in the Console https://github.com/MaterializeInc/console/issues/3342
6263pub static MZ_OBJECT_LIFETIMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6264    name: "mz_object_lifetimes",
6265    schema: MZ_INTERNAL_SCHEMA,
6266    oid: oid::VIEW_MZ_OBJECT_LIFETIMES_OID,
6267    desc: RelationDesc::builder()
6268        .with_column("id", SqlScalarType::String.nullable(true))
6269        .with_column("previous_id", SqlScalarType::String.nullable(true))
6270        .with_column("object_type", SqlScalarType::String.nullable(false))
6271        .with_column("event_type", SqlScalarType::String.nullable(false))
6272        .with_column(
6273            "occurred_at",
6274            SqlScalarType::TimestampTz { precision: None }.nullable(false),
6275        )
6276        .finish(),
6277    column_comments: BTreeMap::from_iter([
6278        ("id", "Materialize's unique ID for the object."),
6279        ("previous_id", "The object's previous ID, if one exists."),
6280        (
6281            "object_type",
6282            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6283        ),
6284        (
6285            "event_type",
6286            "The lifetime event, either `create` or `drop`.",
6287        ),
6288        (
6289            "occurred_at",
6290            "Wall-clock timestamp of when the event occurred.",
6291        ),
6292    ]),
6293    sql: "
6294    SELECT
6295        CASE
6296            WHEN a.object_type = 'cluster-replica' THEN a.details ->> 'replica_id'
6297            ELSE a.details ->> 'id'
6298        END id,
6299        a.details ->> 'previous_id' as previous_id,
6300        a.object_type,
6301        a.event_type,
6302        a.occurred_at
6303    FROM mz_catalog.mz_audit_events a
6304    WHERE a.event_type = 'create' OR a.event_type = 'drop'",
6305    access: vec![PUBLIC_SELECT],
6306});
6307
6308pub static MZ_OBJECT_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6309    name: "mz_object_history",
6310    schema: MZ_INTERNAL_SCHEMA,
6311    oid: oid::VIEW_MZ_OBJECT_HISTORY_OID,
6312    desc: RelationDesc::builder()
6313        .with_column("id", SqlScalarType::String.nullable(true))
6314        .with_column("cluster_id", SqlScalarType::String.nullable(true))
6315        .with_column("object_type", SqlScalarType::String.nullable(false))
6316        .with_column(
6317            "created_at",
6318            SqlScalarType::TimestampTz { precision: None }.nullable(true),
6319        )
6320        .with_column(
6321            "dropped_at",
6322            SqlScalarType::TimestampTz { precision: None }.nullable(true),
6323        )
6324        .finish(),
6325    column_comments: BTreeMap::from_iter([
6326        ("id", "Materialize's unique ID for the object."),
6327        (
6328            "cluster_id",
6329            "The object's cluster ID. `NULL` if the object has no associated cluster.",
6330        ),
6331        (
6332            "object_type",
6333            "The type of the object: one of `table`, `source`, `view`, `materialized view`, `sink`, `index`, `connection`, `secret`, `type`, or `function`.",
6334        ),
6335        (
6336            "created_at",
6337            "Wall-clock timestamp of when the object was created. `NULL` for built in system objects.",
6338        ),
6339        (
6340            "dropped_at",
6341            "Wall-clock timestamp of when the object was dropped. `NULL` for built in system objects or if the object hasn't been dropped.",
6342        ),
6343    ]),
6344    sql: r#"
6345    WITH
6346        creates AS
6347        (
6348            SELECT
6349                details ->> 'id' AS id,
6350                -- We need to backfill cluster_id since older object create events don't include the cluster ID in the audit log
6351                COALESCE(details ->> 'cluster_id', objects.cluster_id) AS cluster_id,
6352                object_type,
6353                occurred_at
6354            FROM
6355                mz_catalog.mz_audit_events AS events
6356                    LEFT JOIN mz_catalog.mz_objects AS objects ON details ->> 'id' = objects.id
6357            WHERE event_type = 'create' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
6358        ),
6359        drops AS
6360        (
6361            SELECT details ->> 'id' AS id, occurred_at
6362            FROM mz_catalog.mz_audit_events
6363            WHERE event_type = 'drop' AND object_type IN ( SELECT object_type FROM mz_internal.mz_objects_id_namespace_types )
6364        ),
6365        user_object_history AS
6366        (
6367            SELECT
6368                creates.id,
6369                creates.cluster_id,
6370                creates.object_type,
6371                creates.occurred_at AS created_at,
6372                drops.occurred_at AS dropped_at
6373            FROM creates LEFT JOIN drops ON creates.id = drops.id
6374            WHERE creates.id LIKE 'u%'
6375        ),
6376        -- We need to union built in objects since they aren't in the audit log
6377        built_in_objects AS
6378        (
6379            -- Functions that accept different arguments have different oids but the same id. We deduplicate in this case.
6380            SELECT DISTINCT ON (objects.id)
6381                objects.id,
6382                objects.cluster_id,
6383                objects.type AS object_type,
6384                NULL::timestamptz AS created_at,
6385                NULL::timestamptz AS dropped_at
6386            FROM mz_catalog.mz_objects AS objects
6387            WHERE objects.id LIKE 's%'
6388        )
6389    SELECT * FROM user_object_history UNION ALL (SELECT * FROM built_in_objects)"#,
6390    access: vec![PUBLIC_SELECT],
6391});
6392
6393pub static MZ_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6394    name: "mz_dataflows_per_worker",
6395    schema: MZ_INTROSPECTION_SCHEMA,
6396    oid: oid::VIEW_MZ_DATAFLOWS_PER_WORKER_OID,
6397    desc: RelationDesc::builder()
6398        .with_column("id", SqlScalarType::UInt64.nullable(true))
6399        .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6400        .with_column("name", SqlScalarType::String.nullable(false))
6401        .finish(),
6402    column_comments: BTreeMap::new(),
6403    sql: "SELECT
6404    addrs.address[1] AS id,
6405    ops.worker_id,
6406    ops.name
6407FROM
6408    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6409    mz_introspection.mz_dataflow_operators_per_worker ops
6410WHERE
6411    addrs.id = ops.id AND
6412    addrs.worker_id = ops.worker_id AND
6413    mz_catalog.list_length(addrs.address) = 1",
6414    access: vec![PUBLIC_SELECT],
6415});
6416
6417pub static MZ_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6418    name: "mz_dataflows",
6419    schema: MZ_INTROSPECTION_SCHEMA,
6420    oid: oid::VIEW_MZ_DATAFLOWS_OID,
6421    desc: RelationDesc::builder()
6422        .with_column("id", SqlScalarType::UInt64.nullable(true))
6423        .with_column("name", SqlScalarType::String.nullable(false))
6424        .finish(),
6425    column_comments: BTreeMap::from_iter([
6426        ("id", "The ID of the dataflow."),
6427        ("name", "The internal name of the dataflow."),
6428    ]),
6429    sql: "
6430SELECT id, name
6431FROM mz_introspection.mz_dataflows_per_worker
6432WHERE worker_id = 0::uint8",
6433    access: vec![PUBLIC_SELECT],
6434});
6435
6436pub static MZ_DATAFLOW_ADDRESSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6437    name: "mz_dataflow_addresses",
6438    schema: MZ_INTROSPECTION_SCHEMA,
6439    oid: oid::VIEW_MZ_DATAFLOW_ADDRESSES_OID,
6440    desc: RelationDesc::builder()
6441        .with_column("id", SqlScalarType::UInt64.nullable(false))
6442        .with_column(
6443            "address",
6444            SqlScalarType::List {
6445                element_type: Box::new(SqlScalarType::UInt64),
6446                custom_id: None,
6447            }
6448            .nullable(false),
6449        )
6450        .with_key(vec![0])
6451        .finish(),
6452    column_comments: BTreeMap::from_iter([
6453        (
6454            "id",
6455            "The ID of the channel or operator. Corresponds to `mz_dataflow_channels.id` or `mz_dataflow_operators.id`.",
6456        ),
6457        (
6458            "address",
6459            "A list of scope-local indexes indicating the path from the root to this channel or operator.",
6460        ),
6461    ]),
6462    sql: "
6463SELECT id, address
6464FROM mz_introspection.mz_dataflow_addresses_per_worker
6465WHERE worker_id = 0::uint8",
6466    access: vec![PUBLIC_SELECT],
6467});
6468
6469pub static MZ_DATAFLOW_CHANNELS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6470    name: "mz_dataflow_channels",
6471    schema: MZ_INTROSPECTION_SCHEMA,
6472    oid: oid::VIEW_MZ_DATAFLOW_CHANNELS_OID,
6473    desc: RelationDesc::builder()
6474        .with_column("id", SqlScalarType::UInt64.nullable(false))
6475        .with_column("from_index", SqlScalarType::UInt64.nullable(false))
6476        .with_column("from_port", SqlScalarType::UInt64.nullable(false))
6477        .with_column("to_index", SqlScalarType::UInt64.nullable(false))
6478        .with_column("to_port", SqlScalarType::UInt64.nullable(false))
6479        .with_column("type", SqlScalarType::String.nullable(false))
6480        .with_key(vec![0])
6481        .finish(),
6482    column_comments: BTreeMap::from_iter([
6483        ("id", "The ID of the channel."),
6484        (
6485            "from_index",
6486            "The scope-local index of the source operator. Corresponds to `mz_dataflow_addresses.address`.",
6487        ),
6488        ("from_port", "The source operator's output port."),
6489        (
6490            "to_index",
6491            "The scope-local index of the target operator. Corresponds to `mz_dataflow_addresses.address`.",
6492        ),
6493        ("to_port", "The target operator's input port."),
6494        ("type", "The container type of the channel."),
6495    ]),
6496    sql: "
6497SELECT id, from_index, from_port, to_index, to_port, type
6498FROM mz_introspection.mz_dataflow_channels_per_worker
6499WHERE worker_id = 0::uint8",
6500    access: vec![PUBLIC_SELECT],
6501});
6502
6503pub static MZ_DATAFLOW_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6504    name: "mz_dataflow_operators",
6505    schema: MZ_INTROSPECTION_SCHEMA,
6506    oid: oid::VIEW_MZ_DATAFLOW_OPERATORS_OID,
6507    desc: RelationDesc::builder()
6508        .with_column("id", SqlScalarType::UInt64.nullable(false))
6509        .with_column("name", SqlScalarType::String.nullable(false))
6510        .with_key(vec![0])
6511        .finish(),
6512    column_comments: BTreeMap::from_iter([
6513        ("id", "The ID of the operator."),
6514        ("name", "The internal name of the operator."),
6515    ]),
6516    sql: "
6517SELECT id, name
6518FROM mz_introspection.mz_dataflow_operators_per_worker
6519WHERE worker_id = 0::uint8",
6520    access: vec![PUBLIC_SELECT],
6521});
6522
6523pub static MZ_DATAFLOW_GLOBAL_IDS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6524    name: "mz_dataflow_global_ids",
6525    schema: MZ_INTROSPECTION_SCHEMA,
6526    oid: oid::VIEW_MZ_DATAFLOW_GLOBAL_IDS_OID,
6527    desc: RelationDesc::builder()
6528        .with_column("id", SqlScalarType::UInt64.nullable(false))
6529        .with_column("global_id", SqlScalarType::String.nullable(false))
6530        .with_key(vec![0, 1])
6531        .finish(),
6532    column_comments: BTreeMap::from_iter([
6533        ("id", "The dataflow ID."),
6534        ("global_id", "A global ID associated with that dataflow."),
6535    ]),
6536    sql: "
6537SELECT id, global_id
6538FROM mz_introspection.mz_compute_dataflow_global_ids_per_worker
6539WHERE worker_id = 0::uint8",
6540    access: vec![PUBLIC_SELECT],
6541});
6542
6543pub static MZ_MAPPABLE_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6544    name: "mz_mappable_objects",
6545    schema: MZ_INTROSPECTION_SCHEMA,
6546    oid: oid::VIEW_MZ_MAPPABLE_OBJECTS_OID,
6547    desc: RelationDesc::builder()
6548        .with_column("name", SqlScalarType::String.nullable(false))
6549        .with_column("global_id", SqlScalarType::String.nullable(false))
6550        .finish(),
6551    column_comments: BTreeMap::from_iter([
6552        (
6553            "name",
6554            "The name of the object. This name is unquoted, and you might need to call `quote_ident` if you want to reference the name shown here.",
6555        ),
6556        ("global_id", "The global ID of the object."),
6557    ]),
6558    sql: "
6559SELECT COALESCE(md.name || '.', '') || ms.name || '.' || mo.name AS name, mgi.global_id AS global_id
6560FROM      mz_catalog.mz_objects mo
6561          JOIN mz_introspection.mz_compute_exports mce ON (mo.id = mce.export_id)
6562          JOIN mz_catalog.mz_schemas ms ON (mo.schema_id = ms.id)
6563          JOIN mz_introspection.mz_dataflow_global_ids mgi ON (mce.dataflow_id = mgi.id)
6564     LEFT JOIN mz_catalog.mz_databases md ON (ms.database_id = md.id);",
6565    access: vec![PUBLIC_SELECT],
6566});
6567
6568pub static MZ_LIR_MAPPING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6569    name: "mz_lir_mapping",
6570    schema: MZ_INTROSPECTION_SCHEMA,
6571    oid: oid::VIEW_MZ_LIR_MAPPING_OID,
6572    desc: RelationDesc::builder()
6573        .with_column("global_id", SqlScalarType::String.nullable(false))
6574        .with_column("lir_id", SqlScalarType::UInt64.nullable(false))
6575        .with_column("operator", SqlScalarType::String.nullable(false))
6576        .with_column("parent_lir_id", SqlScalarType::UInt64.nullable(true))
6577        .with_column("nesting", SqlScalarType::UInt16.nullable(false))
6578        .with_column("operator_id_start", SqlScalarType::UInt64.nullable(false))
6579        .with_column("operator_id_end", SqlScalarType::UInt64.nullable(false))
6580        .with_key(vec![0, 1])
6581        .finish(),
6582    column_comments: BTreeMap::from_iter([
6583        ("global_id", "The global ID."),
6584        ("lir_id", "The LIR node ID."),
6585        (
6586            "operator",
6587            "The LIR operator, in the format `OperatorName INPUTS [OPTIONS]`.",
6588        ),
6589        (
6590            "parent_lir_id",
6591            "The parent of this LIR node. May be `NULL`.",
6592        ),
6593        ("nesting", "The nesting level of this LIR node."),
6594        (
6595            "operator_id_start",
6596            "The first dataflow operator ID implementing this LIR operator (inclusive).",
6597        ),
6598        (
6599            "operator_id_end",
6600            "The first dataflow operator ID _after_ this LIR operator (exclusive).",
6601        ),
6602    ]),
6603    sql: "
6604SELECT global_id, lir_id, operator, parent_lir_id, nesting, operator_id_start, operator_id_end
6605FROM mz_introspection.mz_compute_lir_mapping_per_worker
6606WHERE worker_id = 0::uint8",
6607    access: vec![PUBLIC_SELECT],
6608});
6609
6610pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER: LazyLock<BuiltinView> =
6611    LazyLock::new(|| BuiltinView {
6612        name: "mz_dataflow_operator_dataflows_per_worker",
6613        schema: MZ_INTROSPECTION_SCHEMA,
6614        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER_OID,
6615        desc: RelationDesc::builder()
6616            .with_column("id", SqlScalarType::UInt64.nullable(false))
6617            .with_column("name", SqlScalarType::String.nullable(false))
6618            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6619            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6620            .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6621            .finish(),
6622        column_comments: BTreeMap::new(),
6623        sql: "SELECT
6624    ops.id,
6625    ops.name,
6626    ops.worker_id,
6627    dfs.id as dataflow_id,
6628    dfs.name as dataflow_name
6629FROM
6630    mz_introspection.mz_dataflow_operators_per_worker ops,
6631    mz_introspection.mz_dataflow_addresses_per_worker addrs,
6632    mz_introspection.mz_dataflows_per_worker dfs
6633WHERE
6634    ops.id = addrs.id AND
6635    ops.worker_id = addrs.worker_id AND
6636    dfs.id = addrs.address[1] AND
6637    dfs.worker_id = addrs.worker_id",
6638        access: vec![PUBLIC_SELECT],
6639    });
6640
6641pub static MZ_DATAFLOW_OPERATOR_DATAFLOWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6642    name: "mz_dataflow_operator_dataflows",
6643    schema: MZ_INTROSPECTION_SCHEMA,
6644    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_DATAFLOWS_OID,
6645    desc: RelationDesc::builder()
6646        .with_column("id", SqlScalarType::UInt64.nullable(false))
6647        .with_column("name", SqlScalarType::String.nullable(false))
6648        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6649        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
6650        .finish(),
6651    column_comments: BTreeMap::from_iter([
6652        (
6653            "id",
6654            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6655        ),
6656        ("name", "The internal name of the operator."),
6657        (
6658            "dataflow_id",
6659            "The ID of the dataflow hosting the operator. Corresponds to `mz_dataflows.id`.",
6660        ),
6661        (
6662            "dataflow_name",
6663            "The internal name of the dataflow hosting the operator.",
6664        ),
6665    ]),
6666    sql: "
6667SELECT id, name, dataflow_id, dataflow_name
6668FROM mz_introspection.mz_dataflow_operator_dataflows_per_worker
6669WHERE worker_id = 0::uint8",
6670    access: vec![PUBLIC_SELECT],
6671});
6672
6673pub static MZ_OBJECT_TRANSITIVE_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| {
6674    BuiltinView {
6675        name: "mz_object_transitive_dependencies",
6676        schema: MZ_INTERNAL_SCHEMA,
6677        oid: oid::VIEW_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_OID,
6678        desc: RelationDesc::builder()
6679            .with_column("object_id", SqlScalarType::String.nullable(false))
6680            .with_column(
6681                "referenced_object_id",
6682                SqlScalarType::String.nullable(false),
6683            )
6684            .with_key(vec![0, 1])
6685            .finish(),
6686        column_comments: BTreeMap::from_iter([
6687            (
6688                "object_id",
6689                "The ID of the dependent object. Corresponds to `mz_objects.id`.",
6690            ),
6691            (
6692                "referenced_object_id",
6693                "The ID of the (possibly transitively) referenced object. Corresponds to `mz_objects.id`.",
6694            ),
6695        ]),
6696        sql: "
6697WITH MUTUALLY RECURSIVE
6698  reach(object_id text, referenced_object_id text) AS (
6699    SELECT object_id, referenced_object_id FROM mz_internal.mz_object_dependencies
6700    UNION
6701    SELECT x, z FROM reach r1(x, y) JOIN reach r2(y, z) USING(y)
6702  )
6703SELECT object_id, referenced_object_id FROM reach;",
6704        access: vec![PUBLIC_SELECT],
6705    }
6706});
6707
6708pub static MZ_COMPUTE_EXPORTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6709    name: "mz_compute_exports",
6710    schema: MZ_INTROSPECTION_SCHEMA,
6711    oid: oid::VIEW_MZ_COMPUTE_EXPORTS_OID,
6712    desc: RelationDesc::builder()
6713        .with_column("export_id", SqlScalarType::String.nullable(false))
6714        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6715        .with_key(vec![0])
6716        .finish(),
6717    column_comments: BTreeMap::from_iter([
6718        (
6719            "export_id",
6720            "The ID of the index, materialized view, or subscription exported by the dataflow. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_internal.mz_subscriptions`.",
6721        ),
6722        (
6723            "dataflow_id",
6724            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6725        ),
6726    ]),
6727    sql: "
6728SELECT export_id, dataflow_id
6729FROM mz_introspection.mz_compute_exports_per_worker
6730WHERE worker_id = 0::uint8",
6731    access: vec![PUBLIC_SELECT],
6732});
6733
6734pub static MZ_COMPUTE_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6735    name: "mz_compute_frontiers",
6736    schema: MZ_INTROSPECTION_SCHEMA,
6737    oid: oid::VIEW_MZ_COMPUTE_FRONTIERS_OID,
6738    desc: RelationDesc::builder()
6739        .with_column("export_id", SqlScalarType::String.nullable(false))
6740        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6741        .with_key(vec![0])
6742        .finish(),
6743    column_comments: BTreeMap::from_iter([
6744        (
6745            "export_id",
6746            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6747        ),
6748        (
6749            "time",
6750            "The next timestamp at which the dataflow output may change.",
6751        ),
6752    ]),
6753    sql: "SELECT
6754    export_id, pg_catalog.min(time) AS time
6755FROM mz_introspection.mz_compute_frontiers_per_worker
6756GROUP BY export_id",
6757    access: vec![PUBLIC_SELECT],
6758});
6759
6760pub static MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER: LazyLock<BuiltinView> =
6761    LazyLock::new(|| BuiltinView {
6762        name: "mz_dataflow_channel_operators_per_worker",
6763        schema: MZ_INTROSPECTION_SCHEMA,
6764        oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER_OID,
6765        desc: RelationDesc::builder()
6766            .with_column("id", SqlScalarType::UInt64.nullable(false))
6767            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6768            .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6769            .with_column(
6770                "from_operator_address",
6771                SqlScalarType::List {
6772                    element_type: Box::new(SqlScalarType::UInt64),
6773                    custom_id: None,
6774                }
6775                .nullable(false),
6776            )
6777            .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6778            .with_column(
6779                "to_operator_address",
6780                SqlScalarType::List {
6781                    element_type: Box::new(SqlScalarType::UInt64),
6782                    custom_id: None,
6783                }
6784                .nullable(false),
6785            )
6786            .with_column("type", SqlScalarType::String.nullable(false))
6787            .finish(),
6788        column_comments: BTreeMap::new(),
6789        sql: "
6790WITH
6791channel_addresses(id, worker_id, address, from_index, to_index, type) AS (
6792     SELECT id, worker_id, address, from_index, to_index, type
6793     FROM mz_introspection.mz_dataflow_channels_per_worker mdc
6794     INNER JOIN mz_introspection.mz_dataflow_addresses_per_worker mda
6795     USING (id, worker_id)
6796),
6797channel_operator_addresses(id, worker_id, from_address, to_address, type) AS (
6798     SELECT id, worker_id,
6799            address || from_index AS from_address,
6800            address || to_index AS to_address,
6801            type
6802     FROM channel_addresses
6803),
6804operator_addresses(id, worker_id, address) AS (
6805     SELECT id, worker_id, address
6806     FROM mz_introspection.mz_dataflow_addresses_per_worker mda
6807     INNER JOIN mz_introspection.mz_dataflow_operators_per_worker mdo
6808     USING (id, worker_id)
6809)
6810SELECT coa.id,
6811       coa.worker_id,
6812       from_ops.id AS from_operator_id,
6813       coa.from_address AS from_operator_address,
6814       to_ops.id AS to_operator_id,
6815       coa.to_address AS to_operator_address,
6816       coa.type
6817FROM channel_operator_addresses coa
6818     LEFT OUTER JOIN operator_addresses from_ops
6819          ON coa.from_address = from_ops.address AND
6820             coa.worker_id = from_ops.worker_id
6821     LEFT OUTER JOIN operator_addresses to_ops
6822          ON coa.to_address = to_ops.address AND
6823             coa.worker_id = to_ops.worker_id
6824",
6825        access: vec![PUBLIC_SELECT],
6826    });
6827
6828pub static MZ_DATAFLOW_CHANNEL_OPERATORS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6829    name: "mz_dataflow_channel_operators",
6830    schema: MZ_INTROSPECTION_SCHEMA,
6831    oid: oid::VIEW_MZ_DATAFLOW_CHANNEL_OPERATORS_OID,
6832    desc: RelationDesc::builder()
6833        .with_column("id", SqlScalarType::UInt64.nullable(false))
6834        .with_column("from_operator_id", SqlScalarType::UInt64.nullable(true))
6835        .with_column(
6836            "from_operator_address",
6837            SqlScalarType::List {
6838                element_type: Box::new(SqlScalarType::UInt64),
6839                custom_id: None,
6840            }
6841            .nullable(false),
6842        )
6843        .with_column("to_operator_id", SqlScalarType::UInt64.nullable(true))
6844        .with_column(
6845            "to_operator_address",
6846            SqlScalarType::List {
6847                element_type: Box::new(SqlScalarType::UInt64),
6848                custom_id: None,
6849            }
6850            .nullable(false),
6851        )
6852        .with_column("type", SqlScalarType::String.nullable(false))
6853        .finish(),
6854    column_comments: BTreeMap::from_iter([
6855        (
6856            "id",
6857            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
6858        ),
6859        (
6860            "from_operator_id",
6861            "The ID of the source of the channel. Corresponds to `mz_dataflow_operators.id`.",
6862        ),
6863        (
6864            "from_operator_address",
6865            "The address of the source of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6866        ),
6867        (
6868            "to_operator_id",
6869            "The ID of the target of the channel. Corresponds to `mz_dataflow_operators.id`.",
6870        ),
6871        (
6872            "to_operator_address",
6873            "The address of the target of the channel. Corresponds to `mz_dataflow_addresses.address`.",
6874        ),
6875        ("type", "The container type of the channel."),
6876    ]),
6877    sql: "
6878SELECT id, from_operator_id, from_operator_address, to_operator_id, to_operator_address, type
6879FROM mz_introspection.mz_dataflow_channel_operators_per_worker
6880WHERE worker_id = 0::uint8",
6881    access: vec![PUBLIC_SELECT],
6882});
6883
6884pub static MZ_COMPUTE_IMPORT_FRONTIERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
6885    name: "mz_compute_import_frontiers",
6886    schema: MZ_INTROSPECTION_SCHEMA,
6887    oid: oid::VIEW_MZ_COMPUTE_IMPORT_FRONTIERS_OID,
6888    desc: RelationDesc::builder()
6889        .with_column("export_id", SqlScalarType::String.nullable(false))
6890        .with_column("import_id", SqlScalarType::String.nullable(false))
6891        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
6892        .with_key(vec![0, 1])
6893        .finish(),
6894    column_comments: BTreeMap::from_iter([
6895        (
6896            "export_id",
6897            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
6898        ),
6899        (
6900            "import_id",
6901            "The ID of the dataflow import. Corresponds to `mz_catalog.mz_sources.id` or `mz_catalog.mz_tables.id` or `mz_compute_exports.export_id`.",
6902        ),
6903        (
6904            "time",
6905            "The next timestamp at which the dataflow input may change.",
6906        ),
6907    ]),
6908    sql: "SELECT
6909    export_id, import_id, pg_catalog.min(time) AS time
6910FROM mz_introspection.mz_compute_import_frontiers_per_worker
6911GROUP BY export_id, import_id",
6912    access: vec![PUBLIC_SELECT],
6913});
6914
6915pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER: LazyLock<BuiltinView> =
6916    LazyLock::new(|| BuiltinView {
6917        name: "mz_records_per_dataflow_operator_per_worker",
6918        schema: MZ_INTROSPECTION_SCHEMA,
6919        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER_OID,
6920        desc: RelationDesc::builder()
6921            .with_column("id", SqlScalarType::UInt64.nullable(false))
6922            .with_column("name", SqlScalarType::String.nullable(false))
6923            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
6924            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6925            .with_column("records", SqlScalarType::Int64.nullable(true))
6926            .with_column("batches", SqlScalarType::Int64.nullable(true))
6927            .with_column("size", SqlScalarType::Int64.nullable(true))
6928            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6929            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6930            .finish(),
6931        column_comments: BTreeMap::new(),
6932        sql: "
6933SELECT
6934    dod.id,
6935    dod.name,
6936    dod.worker_id,
6937    dod.dataflow_id,
6938    ar_size.records AS records,
6939    ar_size.batches AS batches,
6940    ar_size.size AS size,
6941    ar_size.capacity AS capacity,
6942    ar_size.allocations AS allocations
6943FROM
6944    mz_introspection.mz_dataflow_operator_dataflows_per_worker dod
6945    LEFT OUTER JOIN mz_introspection.mz_arrangement_sizes_per_worker ar_size ON
6946        dod.id = ar_size.operator_id AND
6947        dod.worker_id = ar_size.worker_id",
6948        access: vec![PUBLIC_SELECT],
6949    });
6950
6951pub static MZ_RECORDS_PER_DATAFLOW_OPERATOR: LazyLock<BuiltinView> =
6952    LazyLock::new(|| BuiltinView {
6953        name: "mz_records_per_dataflow_operator",
6954        schema: MZ_INTROSPECTION_SCHEMA,
6955        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OPERATOR_OID,
6956        desc: RelationDesc::builder()
6957            .with_column("id", SqlScalarType::UInt64.nullable(false))
6958            .with_column("name", SqlScalarType::String.nullable(false))
6959            .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
6960            .with_column("records", SqlScalarType::Int64.nullable(true))
6961            .with_column("batches", SqlScalarType::Int64.nullable(true))
6962            .with_column("size", SqlScalarType::Int64.nullable(true))
6963            .with_column("capacity", SqlScalarType::Int64.nullable(true))
6964            .with_column("allocations", SqlScalarType::Int64.nullable(true))
6965            .with_key(vec![0, 1, 2])
6966            .finish(),
6967        column_comments: BTreeMap::from_iter([
6968            (
6969                "id",
6970                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
6971            ),
6972            ("name", "The internal name of the operator."),
6973            (
6974                "dataflow_id",
6975                "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
6976            ),
6977            ("records", "The number of records in the operator."),
6978            ("batches", "The number of batches in the dataflow."),
6979            ("size", "The utilized size in bytes of the arrangement."),
6980            (
6981                "capacity",
6982                "The capacity in bytes of the arrangement. Can be larger than the size.",
6983            ),
6984            (
6985                "allocations",
6986                "The number of separate memory allocations backing the arrangement.",
6987            ),
6988        ]),
6989        sql: "
6990SELECT
6991    id,
6992    name,
6993    dataflow_id,
6994    SUM(records)::int8 AS records,
6995    SUM(batches)::int8 AS batches,
6996    SUM(size)::int8 AS size,
6997    SUM(capacity)::int8 AS capacity,
6998    SUM(allocations)::int8 AS allocations
6999FROM mz_introspection.mz_records_per_dataflow_operator_per_worker
7000GROUP BY id, name, dataflow_id",
7001        access: vec![PUBLIC_SELECT],
7002    });
7003
7004pub static MZ_RECORDS_PER_DATAFLOW_PER_WORKER: LazyLock<BuiltinView> =
7005    LazyLock::new(|| BuiltinView {
7006        name: "mz_records_per_dataflow_per_worker",
7007        schema: MZ_INTROSPECTION_SCHEMA,
7008        oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_PER_WORKER_OID,
7009        desc: RelationDesc::builder()
7010            .with_column("id", SqlScalarType::UInt64.nullable(false))
7011            .with_column("name", SqlScalarType::String.nullable(false))
7012            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
7013            .with_column("records", SqlScalarType::Int64.nullable(true))
7014            .with_column("batches", SqlScalarType::Int64.nullable(true))
7015            .with_column("size", SqlScalarType::Int64.nullable(true))
7016            .with_column("capacity", SqlScalarType::Int64.nullable(true))
7017            .with_column("allocations", SqlScalarType::Int64.nullable(true))
7018            .with_key(vec![0, 1, 2])
7019            .finish(),
7020        column_comments: BTreeMap::new(),
7021        sql: "
7022SELECT
7023    rdo.dataflow_id as id,
7024    dfs.name,
7025    rdo.worker_id,
7026    SUM(rdo.records)::int8 as records,
7027    SUM(rdo.batches)::int8 as batches,
7028    SUM(rdo.size)::int8 as size,
7029    SUM(rdo.capacity)::int8 as capacity,
7030    SUM(rdo.allocations)::int8 as allocations
7031FROM
7032    mz_introspection.mz_records_per_dataflow_operator_per_worker rdo,
7033    mz_introspection.mz_dataflows_per_worker dfs
7034WHERE
7035    rdo.dataflow_id = dfs.id AND
7036    rdo.worker_id = dfs.worker_id
7037GROUP BY
7038    rdo.dataflow_id,
7039    dfs.name,
7040    rdo.worker_id",
7041        access: vec![PUBLIC_SELECT],
7042    });
7043
7044pub static MZ_RECORDS_PER_DATAFLOW: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7045    name: "mz_records_per_dataflow",
7046    schema: MZ_INTROSPECTION_SCHEMA,
7047    oid: oid::VIEW_MZ_RECORDS_PER_DATAFLOW_OID,
7048    desc: RelationDesc::builder()
7049        .with_column("id", SqlScalarType::UInt64.nullable(false))
7050        .with_column("name", SqlScalarType::String.nullable(false))
7051        .with_column("records", SqlScalarType::Int64.nullable(true))
7052        .with_column("batches", SqlScalarType::Int64.nullable(true))
7053        .with_column("size", SqlScalarType::Int64.nullable(true))
7054        .with_column("capacity", SqlScalarType::Int64.nullable(true))
7055        .with_column("allocations", SqlScalarType::Int64.nullable(true))
7056        .with_key(vec![0, 1])
7057        .finish(),
7058    column_comments: BTreeMap::from_iter([
7059        (
7060            "id",
7061            "The ID of the dataflow. Corresponds to `mz_dataflows.id`.",
7062        ),
7063        ("name", "The internal name of the dataflow."),
7064        ("records", "The number of records in the dataflow."),
7065        ("batches", "The number of batches in the dataflow."),
7066        ("size", "The utilized size in bytes of the arrangements."),
7067        (
7068            "capacity",
7069            "The capacity in bytes of the arrangements. Can be larger than the size.",
7070        ),
7071        (
7072            "allocations",
7073            "The number of separate memory allocations backing the arrangements.",
7074        ),
7075    ]),
7076    sql: "
7077SELECT
7078    id,
7079    name,
7080    SUM(records)::int8 as records,
7081    SUM(batches)::int8 as batches,
7082    SUM(size)::int8 as size,
7083    SUM(capacity)::int8 as capacity,
7084    SUM(allocations)::int8 as allocations
7085FROM
7086    mz_introspection.mz_records_per_dataflow_per_worker
7087GROUP BY
7088    id,
7089    name",
7090    access: vec![PUBLIC_SELECT],
7091});
7092
7093/// Peeled version of `PG_NAMESPACE`:
7094/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7095///   in order to make this view indexable.
7096/// - This has the database name as an extra column, so that downstream views can check it against
7097///  `current_database()`.
7098pub static PG_NAMESPACE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7099    name: "pg_namespace_all_databases",
7100    schema: MZ_INTERNAL_SCHEMA,
7101    oid: oid::VIEW_PG_NAMESPACE_ALL_DATABASES_OID,
7102    desc: RelationDesc::builder()
7103        .with_column("oid", SqlScalarType::Oid.nullable(false))
7104        .with_column("nspname", SqlScalarType::String.nullable(false))
7105        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
7106        .with_column(
7107            "nspacl",
7108            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7109        )
7110        .with_column("database_name", SqlScalarType::String.nullable(true))
7111        .finish(),
7112    column_comments: BTreeMap::new(),
7113    sql: "
7114SELECT
7115    s.oid AS oid,
7116    s.name AS nspname,
7117    role_owner.oid AS nspowner,
7118    NULL::pg_catalog.text[] AS nspacl,
7119    d.name as database_name
7120FROM mz_catalog.mz_schemas s
7121LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7122JOIN mz_catalog.mz_roles role_owner ON role_owner.id = s.owner_id",
7123    access: vec![PUBLIC_SELECT],
7124});
7125
7126pub const PG_NAMESPACE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7127    name: "pg_namespace_all_databases_ind",
7128    schema: MZ_INTERNAL_SCHEMA,
7129    oid: oid::INDEX_PG_NAMESPACE_ALL_DATABASES_IND_OID,
7130    sql: "IN CLUSTER mz_catalog_server
7131ON mz_internal.pg_namespace_all_databases (nspname)",
7132    is_retained_metrics_object: false,
7133};
7134
7135pub static PG_NAMESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7136    name: "pg_namespace",
7137    schema: PG_CATALOG_SCHEMA,
7138    oid: oid::VIEW_PG_NAMESPACE_OID,
7139    desc: RelationDesc::builder()
7140        .with_column("oid", SqlScalarType::Oid.nullable(false))
7141        .with_column("nspname", SqlScalarType::String.nullable(false))
7142        .with_column("nspowner", SqlScalarType::Oid.nullable(false))
7143        .with_column(
7144            "nspacl",
7145            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7146        )
7147        .finish(),
7148    column_comments: BTreeMap::new(),
7149    sql: "
7150SELECT
7151    oid, nspname, nspowner, nspacl
7152FROM mz_internal.pg_namespace_all_databases
7153WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7154    access: vec![PUBLIC_SELECT],
7155});
7156
7157/// Peeled version of `PG_CLASS`:
7158/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7159///   in order to make this view indexable.
7160/// - This has the database name as an extra column, so that downstream views can check it against
7161///  `current_database()`.
7162pub static PG_CLASS_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7163    BuiltinView {
7164        name: "pg_class_all_databases",
7165        schema: MZ_INTERNAL_SCHEMA,
7166        oid: oid::VIEW_PG_CLASS_ALL_DATABASES_OID,
7167        desc: RelationDesc::builder()
7168            .with_column("oid", SqlScalarType::Oid.nullable(false))
7169            .with_column("relname", SqlScalarType::String.nullable(false))
7170            .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
7171            .with_column("reloftype", SqlScalarType::Oid.nullable(false))
7172            .with_column("relowner", SqlScalarType::Oid.nullable(false))
7173            .with_column("relam", SqlScalarType::Oid.nullable(false))
7174            .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
7175            .with_column("reltuples", SqlScalarType::Float32.nullable(false))
7176            .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
7177            .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
7178            .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
7179            .with_column("relkind", SqlScalarType::String.nullable(true))
7180            .with_column("relnatts", SqlScalarType::Int16.nullable(false))
7181            .with_column("relchecks", SqlScalarType::Int16.nullable(false))
7182            .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
7183            .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
7184            .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
7185            .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
7186            .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
7187            .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
7188            .with_column("relispartition", SqlScalarType::Bool.nullable(false))
7189            .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
7190            .with_column("reloptions", SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true))
7191            .with_column("database_name", SqlScalarType::String.nullable(true))
7192            .finish(),
7193        column_comments: BTreeMap::new(),
7194        sql: "
7195SELECT
7196    class_objects.oid,
7197    class_objects.name AS relname,
7198    mz_schemas.oid AS relnamespace,
7199    -- MZ doesn't support typed tables so reloftype is filled with 0
7200    0::pg_catalog.oid AS reloftype,
7201    role_owner.oid AS relowner,
7202    0::pg_catalog.oid AS relam,
7203    -- MZ doesn't have tablespaces so reltablespace is filled in with 0 implying the default tablespace
7204    0::pg_catalog.oid AS reltablespace,
7205    -- MZ doesn't support (estimated) row counts currently.
7206    -- Postgres defines a value of -1 as unknown.
7207    -1::float4 as reltuples,
7208    -- MZ doesn't use TOAST tables so reltoastrelid is filled with 0
7209    0::pg_catalog.oid AS reltoastrelid,
7210    EXISTS (SELECT id, oid, name, on_id, cluster_id FROM mz_catalog.mz_indexes where mz_indexes.on_id = class_objects.id) AS relhasindex,
7211    -- MZ doesn't have unlogged tables and because of (https://github.com/MaterializeInc/database-issues/issues/2689)
7212    -- temporary objects don't show up here, so relpersistence is filled with 'p' for permanent.
7213    -- TODO(jkosh44): update this column when issue is resolved.
7214    'p'::pg_catalog.\"char\" AS relpersistence,
7215    CASE
7216        WHEN class_objects.type = 'table' THEN 'r'
7217        WHEN class_objects.type = 'source' THEN 'r'
7218        WHEN class_objects.type = 'index' THEN 'i'
7219        WHEN class_objects.type = 'view' THEN 'v'
7220        WHEN class_objects.type = 'materialized-view' THEN 'm'
7221    END relkind,
7222    COALESCE(
7223        (
7224            SELECT count(*)::pg_catalog.int2
7225            FROM mz_catalog.mz_columns
7226            WHERE mz_columns.id = class_objects.id
7227        ),
7228        0::pg_catalog.int2
7229    ) AS relnatts,
7230    -- MZ doesn't support CHECK constraints so relchecks is filled with 0
7231    0::pg_catalog.int2 AS relchecks,
7232    -- MZ doesn't support creating rules so relhasrules is filled with false
7233    false AS relhasrules,
7234    -- MZ doesn't support creating triggers so relhastriggers is filled with false
7235    false AS relhastriggers,
7236    -- MZ doesn't support table inheritance or partitions so relhassubclass is filled with false
7237    false AS relhassubclass,
7238    -- MZ doesn't have row level security so relrowsecurity and relforcerowsecurity is filled with false
7239    false AS relrowsecurity,
7240    false AS relforcerowsecurity,
7241    -- MZ doesn't support replication so relreplident is filled with 'd' for default
7242    'd'::pg_catalog.\"char\" AS relreplident,
7243    -- MZ doesn't support table partitioning so relispartition is filled with false
7244    false AS relispartition,
7245    -- PG removed relhasoids in v12 so it's filled with false
7246    false AS relhasoids,
7247    -- MZ doesn't support options for relations
7248    NULL::pg_catalog.text[] as reloptions,
7249    d.name as database_name
7250FROM (
7251    -- pg_class catalogs relations and indexes
7252    SELECT id, oid, schema_id, name, type, owner_id FROM mz_catalog.mz_relations
7253    UNION ALL
7254        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type, mz_indexes.owner_id
7255        FROM mz_catalog.mz_indexes
7256        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7257) AS class_objects
7258JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7259LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7260JOIN mz_catalog.mz_roles role_owner ON role_owner.id = class_objects.owner_id",
7261        access: vec![PUBLIC_SELECT],
7262    }
7263});
7264
7265pub const PG_CLASS_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7266    name: "pg_class_all_databases_ind",
7267    schema: MZ_INTERNAL_SCHEMA,
7268    oid: oid::INDEX_PG_CLASS_ALL_DATABASES_IND_OID,
7269    sql: "IN CLUSTER mz_catalog_server
7270ON mz_internal.pg_class_all_databases (relname)",
7271    is_retained_metrics_object: false,
7272};
7273
7274pub static PG_CLASS: LazyLock<BuiltinView> = LazyLock::new(|| {
7275    BuiltinView {
7276    name: "pg_class",
7277    schema: PG_CATALOG_SCHEMA,
7278    oid: oid::VIEW_PG_CLASS_OID,
7279    desc: RelationDesc::builder()
7280        .with_column("oid", SqlScalarType::Oid.nullable(false))
7281        .with_column("relname", SqlScalarType::String.nullable(false))
7282        .with_column("relnamespace", SqlScalarType::Oid.nullable(false))
7283        .with_column("reloftype", SqlScalarType::Oid.nullable(false))
7284        .with_column("relowner", SqlScalarType::Oid.nullable(false))
7285        .with_column("relam", SqlScalarType::Oid.nullable(false))
7286        .with_column("reltablespace", SqlScalarType::Oid.nullable(false))
7287        .with_column("reltuples", SqlScalarType::Float32.nullable(false))
7288        .with_column("reltoastrelid", SqlScalarType::Oid.nullable(false))
7289        .with_column("relhasindex", SqlScalarType::Bool.nullable(false))
7290        .with_column("relpersistence", SqlScalarType::PgLegacyChar.nullable(false))
7291        .with_column("relkind", SqlScalarType::String.nullable(true))
7292        .with_column("relnatts", SqlScalarType::Int16.nullable(false))
7293        .with_column("relchecks", SqlScalarType::Int16.nullable(false))
7294        .with_column("relhasrules", SqlScalarType::Bool.nullable(false))
7295        .with_column("relhastriggers", SqlScalarType::Bool.nullable(false))
7296        .with_column("relhassubclass", SqlScalarType::Bool.nullable(false))
7297        .with_column("relrowsecurity", SqlScalarType::Bool.nullable(false))
7298        .with_column("relforcerowsecurity", SqlScalarType::Bool.nullable(false))
7299        .with_column("relreplident", SqlScalarType::PgLegacyChar.nullable(false))
7300        .with_column("relispartition", SqlScalarType::Bool.nullable(false))
7301        .with_column("relhasoids", SqlScalarType::Bool.nullable(false))
7302        .with_column(
7303            "reloptions",
7304            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7305        )
7306        .finish(),
7307    column_comments: BTreeMap::new(),
7308    sql: "
7309SELECT
7310    oid, relname, relnamespace, reloftype, relowner, relam, reltablespace, reltuples, reltoastrelid,
7311    relhasindex, relpersistence, relkind, relnatts, relchecks, relhasrules, relhastriggers, relhassubclass,
7312    relrowsecurity, relforcerowsecurity, relreplident, relispartition, relhasoids, reloptions
7313FROM mz_internal.pg_class_all_databases
7314WHERE database_name IS NULL OR database_name = pg_catalog.current_database();
7315",
7316    access: vec![PUBLIC_SELECT],
7317}
7318});
7319
7320pub static PG_DEPEND: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7321    name: "pg_depend",
7322    schema: PG_CATALOG_SCHEMA,
7323    oid: oid::VIEW_PG_DEPEND_OID,
7324    desc: RelationDesc::builder()
7325        .with_column("classid", SqlScalarType::Oid.nullable(true))
7326        .with_column("objid", SqlScalarType::Oid.nullable(false))
7327        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7328        .with_column("refclassid", SqlScalarType::Oid.nullable(true))
7329        .with_column("refobjid", SqlScalarType::Oid.nullable(false))
7330        .with_column("refobjsubid", SqlScalarType::Int32.nullable(false))
7331        .with_column("deptype", SqlScalarType::PgLegacyChar.nullable(false))
7332        .finish(),
7333    column_comments: BTreeMap::new(),
7334    sql: "
7335WITH class_objects AS (
7336    SELECT
7337        CASE
7338            WHEN type = 'table' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
7339            WHEN type = 'source' THEN 'pg_tables'::pg_catalog.regclass::pg_catalog.oid
7340            WHEN type = 'view' THEN 'pg_views'::pg_catalog.regclass::pg_catalog.oid
7341            WHEN type = 'materialized-view' THEN 'pg_matviews'::pg_catalog.regclass::pg_catalog.oid
7342        END classid,
7343        id,
7344        oid,
7345        schema_id
7346    FROM mz_catalog.mz_relations
7347    UNION ALL
7348    SELECT
7349        'pg_index'::pg_catalog.regclass::pg_catalog.oid AS classid,
7350        i.id,
7351        i.oid,
7352        r.schema_id
7353    FROM mz_catalog.mz_indexes i
7354    JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7355),
7356
7357current_objects AS (
7358    SELECT class_objects.*
7359    FROM class_objects
7360    JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7361    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7362    -- This filter is tricky, as it filters out not just objects outside the
7363    -- database, but *dependencies* on objects outside this database. It's not
7364    -- clear that this is the right choice, but because PostgreSQL doesn't
7365    -- support cross-database references, it's not clear that the other choice
7366    -- is better.
7367    WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7368)
7369
7370SELECT
7371    objects.classid::pg_catalog.oid,
7372    objects.oid::pg_catalog.oid AS objid,
7373    0::pg_catalog.int4 AS objsubid,
7374    dependents.classid::pg_catalog.oid AS refclassid,
7375    dependents.oid::pg_catalog.oid AS refobjid,
7376    0::pg_catalog.int4 AS refobjsubid,
7377    'n'::pg_catalog.char AS deptype
7378FROM mz_internal.mz_object_dependencies
7379JOIN current_objects objects ON object_id = objects.id
7380JOIN current_objects dependents ON referenced_object_id = dependents.id",
7381    access: vec![PUBLIC_SELECT],
7382});
7383
7384pub static PG_DATABASE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7385    name: "pg_database",
7386    schema: PG_CATALOG_SCHEMA,
7387    oid: oid::VIEW_PG_DATABASE_OID,
7388    desc: RelationDesc::builder()
7389        .with_column("oid", SqlScalarType::Oid.nullable(false))
7390        .with_column("datname", SqlScalarType::String.nullable(false))
7391        .with_column("datdba", SqlScalarType::Oid.nullable(false))
7392        .with_column("encoding", SqlScalarType::Int32.nullable(false))
7393        .with_column("datistemplate", SqlScalarType::Bool.nullable(false))
7394        .with_column("datallowconn", SqlScalarType::Bool.nullable(false))
7395        .with_column("datcollate", SqlScalarType::String.nullable(false))
7396        .with_column("datctype", SqlScalarType::String.nullable(false))
7397        .with_column(
7398            "datacl",
7399            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
7400        )
7401        .with_key(vec![0])
7402        .finish(),
7403    column_comments: BTreeMap::new(),
7404    sql: "SELECT
7405    d.oid as oid,
7406    d.name as datname,
7407    role_owner.oid as datdba,
7408    6 as encoding,
7409    -- Materialize doesn't support database cloning.
7410    FALSE AS datistemplate,
7411    TRUE AS datallowconn,
7412    'C' as datcollate,
7413    'C' as datctype,
7414    NULL::pg_catalog.text[] as datacl
7415FROM mz_catalog.mz_databases d
7416JOIN mz_catalog.mz_roles role_owner ON role_owner.id = d.owner_id",
7417    access: vec![PUBLIC_SELECT],
7418});
7419
7420pub static PG_INDEX: LazyLock<BuiltinView> = LazyLock::new(|| {
7421    BuiltinView {
7422        name: "pg_index",
7423        schema: PG_CATALOG_SCHEMA,
7424        oid: oid::VIEW_PG_INDEX_OID,
7425        desc: RelationDesc::builder()
7426            .with_column("indexrelid", SqlScalarType::Oid.nullable(false))
7427            .with_column("indrelid", SqlScalarType::Oid.nullable(false))
7428            .with_column("indnatts", SqlScalarType::Int16.nullable(false))
7429            .with_column("indisunique", SqlScalarType::Bool.nullable(false))
7430            .with_column("indisprimary", SqlScalarType::Bool.nullable(false))
7431            .with_column("indimmediate", SqlScalarType::Bool.nullable(false))
7432            .with_column("indisclustered", SqlScalarType::Bool.nullable(false))
7433            .with_column("indisvalid", SqlScalarType::Bool.nullable(false))
7434            .with_column("indisreplident", SqlScalarType::Bool.nullable(false))
7435            .with_column("indkey", SqlScalarType::Int2Vector.nullable(false))
7436            .with_column("indoption", SqlScalarType::Int2Vector.nullable(false))
7437            .with_column("indexprs", SqlScalarType::String.nullable(true))
7438            .with_column("indpred", SqlScalarType::String.nullable(true))
7439            .with_key(vec![0, 1])
7440            .finish(),
7441        column_comments: BTreeMap::new(),
7442        sql: "SELECT
7443    mz_indexes.oid AS indexrelid,
7444    mz_relations.oid AS indrelid,
7445    COALESCE(
7446        (
7447            SELECT count(*)::pg_catalog.int2
7448            FROM mz_catalog.mz_columns
7449            JOIN mz_catalog.mz_relations mri ON mz_columns.id = mri.id
7450            WHERE mri.oid = mz_catalog.mz_relations.oid
7451        ),
7452        0::pg_catalog.int2
7453    ) AS indnatts,
7454    -- MZ doesn't support creating unique indexes so indisunique is filled with false
7455    false::pg_catalog.bool AS indisunique,
7456    false::pg_catalog.bool AS indisprimary,
7457    -- MZ doesn't support unique indexes so indimmediate is filled with false
7458    false::pg_catalog.bool AS indimmediate,
7459    -- MZ doesn't support CLUSTER so indisclustered is filled with false
7460    false::pg_catalog.bool AS indisclustered,
7461    -- MZ never creates invalid indexes so indisvalid is filled with true
7462    true::pg_catalog.bool AS indisvalid,
7463    -- MZ doesn't support replication so indisreplident is filled with false
7464    false::pg_catalog.bool AS indisreplident,
7465    -- Return zero if the index attribute is not a simple column reference, column position otherwise
7466    pg_catalog.string_agg(coalesce(mz_index_columns.on_position::int8, 0)::pg_catalog.text, ' ' ORDER BY mz_index_columns.index_position::int8)::pg_catalog.int2vector AS indkey,
7467    -- MZ doesn't have per-column flags, so returning a 0 for each column in the index
7468    pg_catalog.string_agg('0', ' ')::pg_catalog.int2vector AS indoption,
7469    -- Index expressions are returned in MZ format
7470    CASE pg_catalog.string_agg(mz_index_columns.on_expression, ' ' ORDER BY mz_index_columns.index_position::int8)
7471    WHEN NULL THEN NULL
7472    ELSE '{' || pg_catalog.string_agg(mz_index_columns.on_expression, '}, {' ORDER BY mz_index_columns.index_position::int8) || '}'
7473    END AS indexprs,
7474    -- MZ doesn't support indexes with predicates
7475    NULL::pg_catalog.text AS indpred
7476FROM mz_catalog.mz_indexes
7477JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7478JOIN mz_catalog.mz_index_columns ON mz_index_columns.index_id = mz_indexes.id
7479JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_relations.schema_id
7480LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7481WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()
7482GROUP BY mz_indexes.oid, mz_relations.oid",
7483        access: vec![PUBLIC_SELECT],
7484    }
7485});
7486
7487pub static PG_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7488    name: "pg_indexes",
7489    schema: PG_CATALOG_SCHEMA,
7490    oid: oid::VIEW_PG_INDEXES_OID,
7491    desc: RelationDesc::builder()
7492        .with_column("table_catalog", SqlScalarType::String.nullable(false))
7493        .with_column("schemaname", SqlScalarType::String.nullable(false))
7494        .with_column("tablename", SqlScalarType::String.nullable(false))
7495        .with_column("indexname", SqlScalarType::String.nullable(false))
7496        .with_column("tablespace", SqlScalarType::String.nullable(true))
7497        .with_column("indexdef", SqlScalarType::String.nullable(true))
7498        .finish(),
7499    column_comments: BTreeMap::new(),
7500    sql: "SELECT
7501    current_database() as table_catalog,
7502    s.name AS schemaname,
7503    r.name AS tablename,
7504    i.name AS indexname,
7505    NULL::text AS tablespace,
7506    -- TODO(jkosh44) Fill in with actual index definition.
7507    NULL::text AS indexdef
7508FROM mz_catalog.mz_indexes i
7509JOIN mz_catalog.mz_relations r ON i.on_id = r.id
7510JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
7511LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
7512WHERE s.database_id IS NULL OR d.name = current_database()",
7513    access: vec![PUBLIC_SELECT],
7514});
7515
7516/// Peeled version of `PG_DESCRIPTION`:
7517/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7518///   in order to make this view indexable.
7519/// - This has 2 extra columns for the database names, so that downstream views can check them
7520///   against `current_database()`.
7521pub static PG_DESCRIPTION_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7522    BuiltinView {
7523        name: "pg_description_all_databases",
7524        schema: MZ_INTERNAL_SCHEMA,
7525        oid: oid::VIEW_PG_DESCRIPTION_ALL_DATABASES_OID,
7526        desc: RelationDesc::builder()
7527            .with_column("objoid", SqlScalarType::Oid.nullable(false))
7528            .with_column("classoid", SqlScalarType::Oid.nullable(true))
7529            .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7530            .with_column("description", SqlScalarType::String.nullable(false))
7531            .with_column("oid_database_name", SqlScalarType::String.nullable(true))
7532            .with_column("class_database_name", SqlScalarType::String.nullable(true))
7533            .finish(),
7534        column_comments: BTreeMap::new(),
7535        sql: "
7536(
7537    -- Gather all of the class oid's for objects that can have comments.
7538    WITH pg_classoids AS (
7539        SELECT oid, database_name as oid_database_name,
7540          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS classoid,
7541          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_class') AS class_database_name
7542        FROM mz_internal.pg_class_all_databases
7543        UNION ALL
7544        SELECT oid, database_name as oid_database_name,
7545          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS classoid,
7546          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_type') AS class_database_name
7547        FROM mz_internal.pg_type_all_databases
7548        UNION ALL
7549        SELECT oid, database_name as oid_database_name,
7550          (SELECT oid FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS classoid,
7551          (SELECT database_name FROM mz_internal.pg_class_all_databases WHERE relname = 'pg_namespace') AS class_database_name
7552        FROM mz_internal.pg_namespace_all_databases
7553    ),
7554
7555    -- Gather all of the MZ ids for objects that can have comments.
7556    mz_objects AS (
7557        SELECT id, oid, type FROM mz_catalog.mz_objects
7558        UNION ALL
7559        SELECT id, oid, 'schema' AS type FROM mz_catalog.mz_schemas
7560    )
7561    SELECT
7562        pg_classoids.oid AS objoid,
7563        pg_classoids.classoid as classoid,
7564        COALESCE(cmt.object_sub_id, 0) AS objsubid,
7565        cmt.comment AS description,
7566        -- Columns added because of the peeling. (Note that there are 2 of these here.)
7567        oid_database_name,
7568        class_database_name
7569    FROM
7570        pg_classoids
7571    JOIN
7572        mz_objects ON pg_classoids.oid = mz_objects.oid
7573    JOIN
7574        mz_internal.mz_comments AS cmt ON mz_objects.id = cmt.id AND lower(mz_objects.type) = lower(cmt.object_type)
7575)",
7576        access: vec![PUBLIC_SELECT],
7577    }
7578});
7579
7580pub const PG_DESCRIPTION_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7581    name: "pg_description_all_databases_ind",
7582    schema: MZ_INTERNAL_SCHEMA,
7583    oid: oid::INDEX_PG_DESCRIPTION_ALL_DATABASES_IND_OID,
7584    sql: "IN CLUSTER mz_catalog_server
7585ON mz_internal.pg_description_all_databases (objoid, classoid, objsubid, description, oid_database_name, class_database_name)",
7586    is_retained_metrics_object: false,
7587};
7588
7589/// Note: Databases, Roles, Clusters, Cluster Replicas, Secrets, and Connections are excluded from
7590/// this view for Postgres compatibility. Specifically, there is no classoid for these objects,
7591/// which is required for this view.
7592pub static PG_DESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7593    name: "pg_description",
7594    schema: PG_CATALOG_SCHEMA,
7595    oid: oid::VIEW_PG_DESCRIPTION_OID,
7596    desc: RelationDesc::builder()
7597        .with_column("objoid", SqlScalarType::Oid.nullable(false))
7598        .with_column("classoid", SqlScalarType::Oid.nullable(true))
7599        .with_column("objsubid", SqlScalarType::Int32.nullable(false))
7600        .with_column("description", SqlScalarType::String.nullable(false))
7601        .finish(),
7602    column_comments: BTreeMap::new(),
7603    sql: "
7604SELECT
7605    objoid,
7606    classoid,
7607    objsubid,
7608    description
7609FROM
7610    mz_internal.pg_description_all_databases
7611WHERE
7612    (oid_database_name IS NULL OR oid_database_name = pg_catalog.current_database()) AND
7613    (class_database_name IS NULL OR class_database_name = pg_catalog.current_database());",
7614    access: vec![PUBLIC_SELECT],
7615});
7616
7617/// Peeled version of `PG_TYPE`:
7618/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7619///   in order to make this view indexable.
7620/// - This has the database name as an extra column, so that downstream views can check it against
7621///  `current_database()`.
7622pub static PG_TYPE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7623    BuiltinView {
7624        name: "pg_type_all_databases",
7625        schema: MZ_INTERNAL_SCHEMA,
7626        oid: oid::VIEW_PG_TYPE_ALL_DATABASES_OID,
7627        desc: RelationDesc::builder()
7628            .with_column("oid", SqlScalarType::Oid.nullable(false))
7629            .with_column("typname", SqlScalarType::String.nullable(false))
7630            .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7631            .with_column("typowner", SqlScalarType::Oid.nullable(false))
7632            .with_column("typlen", SqlScalarType::Int16.nullable(true))
7633            .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7634            .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7635            .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7636            .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7637            .with_column("typelem", SqlScalarType::Oid.nullable(false))
7638            .with_column("typarray", SqlScalarType::Oid.nullable(false))
7639            .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7640            .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7641            .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7642            .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7643            .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7644            .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7645            .with_column("typdefault", SqlScalarType::String.nullable(true))
7646            .with_column("database_name", SqlScalarType::String.nullable(true))
7647            .finish(),
7648        column_comments: BTreeMap::new(),
7649        sql: "
7650SELECT
7651    mz_types.oid,
7652    mz_types.name AS typname,
7653    mz_schemas.oid AS typnamespace,
7654    role_owner.oid AS typowner,
7655    NULL::pg_catalog.int2 AS typlen,
7656    -- 'a' is used internally to denote an array type, but in postgres they show up
7657    -- as 'b'.
7658    (CASE mztype WHEN 'a' THEN 'b' ELSE mztype END)::pg_catalog.char AS typtype,
7659    (CASE category
7660        WHEN 'array' THEN 'A'
7661        WHEN 'bit-string' THEN 'V'
7662        WHEN 'boolean' THEN 'B'
7663        WHEN 'composite' THEN 'C'
7664        WHEN 'date-time' THEN 'D'
7665        WHEN 'enum' THEN 'E'
7666        WHEN 'geometric' THEN 'G'
7667        WHEN 'list' THEN 'U' -- List types are user-defined from PostgreSQL's perspective.
7668        WHEN 'network-address' THEN 'I'
7669        WHEN 'numeric' THEN 'N'
7670        WHEN 'pseudo' THEN 'P'
7671        WHEN 'string' THEN 'S'
7672        WHEN 'timespan' THEN 'T'
7673        WHEN 'user-defined' THEN 'U'
7674        WHEN 'unknown' THEN 'X'
7675    END)::pg_catalog.char AS typcategory,
7676    -- In pg only the 'box' type is not ','.
7677    ','::pg_catalog.char AS typdelim,
7678    0::pg_catalog.oid AS typrelid,
7679    coalesce(
7680        (
7681            SELECT t.oid
7682            FROM mz_catalog.mz_array_types a
7683            JOIN mz_catalog.mz_types t ON a.element_id = t.id
7684            WHERE a.id = mz_types.id
7685        ),
7686        (
7687            SELECT t.oid
7688            FROM mz_catalog.mz_list_types l
7689            JOIN mz_catalog.mz_types t ON l.element_id = t.id
7690            WHERE l.id = mz_types.id
7691        ),
7692        0
7693    ) AS typelem,
7694    coalesce(
7695        (
7696            SELECT
7697                t.oid
7698            FROM
7699                mz_catalog.mz_array_types AS a
7700                JOIN mz_catalog.mz_types AS t ON a.id = t.id
7701            WHERE
7702                a.element_id = mz_types.id
7703        ),
7704        0
7705    )
7706        AS typarray,
7707    mz_internal.mz_type_pg_metadata.typinput::pg_catalog.regproc AS typinput,
7708    COALESCE(mz_internal.mz_type_pg_metadata.typreceive, 0) AS typreceive,
7709    false::pg_catalog.bool AS typnotnull,
7710    0::pg_catalog.oid AS typbasetype,
7711    -1::pg_catalog.int4 AS typtypmod,
7712    -- MZ doesn't support COLLATE so typcollation is filled with 0
7713    0::pg_catalog.oid AS typcollation,
7714    NULL::pg_catalog.text AS typdefault,
7715    d.name as database_name
7716FROM
7717    mz_catalog.mz_types
7718    LEFT JOIN mz_internal.mz_type_pg_metadata ON mz_catalog.mz_types.id = mz_internal.mz_type_pg_metadata.id
7719    JOIN mz_catalog.mz_schemas ON mz_schemas.id = mz_types.schema_id
7720    JOIN (
7721            -- 'a' is not a supported typtype, but we use it to denote an array. It is
7722            -- converted to the correct value above.
7723            SELECT id, 'a' AS mztype FROM mz_catalog.mz_array_types
7724            UNION ALL SELECT id, 'b' FROM mz_catalog.mz_base_types
7725            UNION ALL SELECT id, 'l' FROM mz_catalog.mz_list_types
7726            UNION ALL SELECT id, 'm' FROM mz_catalog.mz_map_types
7727            UNION ALL SELECT id, 'p' FROM mz_catalog.mz_pseudo_types
7728        )
7729            AS t ON mz_types.id = t.id
7730    LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7731    JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_types.owner_id",
7732        access: vec![PUBLIC_SELECT],
7733    }
7734});
7735
7736pub const PG_TYPE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7737    name: "pg_type_all_databases_ind",
7738    schema: MZ_INTERNAL_SCHEMA,
7739    oid: oid::INDEX_PG_TYPE_ALL_DATABASES_IND_OID,
7740    sql: "IN CLUSTER mz_catalog_server
7741ON mz_internal.pg_type_all_databases (oid)",
7742    is_retained_metrics_object: false,
7743};
7744
7745pub static PG_TYPE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7746    name: "pg_type",
7747    schema: PG_CATALOG_SCHEMA,
7748    oid: oid::VIEW_PG_TYPE_OID,
7749    desc: RelationDesc::builder()
7750        .with_column("oid", SqlScalarType::Oid.nullable(false))
7751        .with_column("typname", SqlScalarType::String.nullable(false))
7752        .with_column("typnamespace", SqlScalarType::Oid.nullable(false))
7753        .with_column("typowner", SqlScalarType::Oid.nullable(false))
7754        .with_column("typlen", SqlScalarType::Int16.nullable(true))
7755        .with_column("typtype", SqlScalarType::PgLegacyChar.nullable(false))
7756        .with_column("typcategory", SqlScalarType::PgLegacyChar.nullable(true))
7757        .with_column("typdelim", SqlScalarType::PgLegacyChar.nullable(false))
7758        .with_column("typrelid", SqlScalarType::Oid.nullable(false))
7759        .with_column("typelem", SqlScalarType::Oid.nullable(false))
7760        .with_column("typarray", SqlScalarType::Oid.nullable(false))
7761        .with_column("typinput", SqlScalarType::RegProc.nullable(true))
7762        .with_column("typreceive", SqlScalarType::Oid.nullable(false))
7763        .with_column("typnotnull", SqlScalarType::Bool.nullable(false))
7764        .with_column("typbasetype", SqlScalarType::Oid.nullable(false))
7765        .with_column("typtypmod", SqlScalarType::Int32.nullable(false))
7766        .with_column("typcollation", SqlScalarType::Oid.nullable(false))
7767        .with_column("typdefault", SqlScalarType::String.nullable(true))
7768        .finish(),
7769    column_comments: BTreeMap::new(),
7770    sql: "SELECT
7771    oid, typname, typnamespace, typowner, typlen, typtype, typcategory, typdelim, typrelid, typelem,
7772    typarray, typinput, typreceive, typnotnull, typbasetype, typtypmod, typcollation, typdefault
7773FROM mz_internal.pg_type_all_databases
7774WHERE database_name IS NULL OR database_name = pg_catalog.current_database();",
7775    access: vec![PUBLIC_SELECT],
7776});
7777
7778/// Peeled version of `PG_ATTRIBUTE`:
7779/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
7780///   in order to make this view indexable.
7781/// - This has 2 extra columns for the database names, so that downstream views can check them
7782///   against `current_database()`.
7783pub static PG_ATTRIBUTE_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| {
7784    BuiltinView {
7785        name: "pg_attribute_all_databases",
7786        schema: MZ_INTERNAL_SCHEMA,
7787        oid: oid::VIEW_PG_ATTRIBUTE_ALL_DATABASES_OID,
7788        desc: RelationDesc::builder()
7789            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7790            .with_column("attname", SqlScalarType::String.nullable(false))
7791            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7792            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7793            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7794            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7795            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7796            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7797            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7798            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7799            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7800            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7801            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7802            .with_column("database_name", SqlScalarType::String.nullable(true))
7803            .with_column("pg_type_database_name", SqlScalarType::String.nullable(true))
7804            .finish(),
7805        column_comments: BTreeMap::new(),
7806        sql: "
7807SELECT
7808    class_objects.oid as attrelid,
7809    mz_columns.name as attname,
7810    mz_columns.type_oid AS atttypid,
7811    pg_type_all_databases.typlen AS attlen,
7812    position::int8::int2 as attnum,
7813    mz_columns.type_mod as atttypmod,
7814    -- dummy value, just to make go-jet's workaround work for now. Discussion:
7815    -- https://github.com/MaterializeInc/materialize/pull/34649#issuecomment-3714291409
7816    0::int2 as attndims,
7817    NOT nullable as attnotnull,
7818    mz_columns.default IS NOT NULL as atthasdef,
7819    ''::pg_catalog.\"char\" as attidentity,
7820    -- MZ doesn't support generated columns so attgenerated is filled with ''
7821    ''::pg_catalog.\"char\" as attgenerated,
7822    FALSE as attisdropped,
7823    -- MZ doesn't support COLLATE so attcollation is filled with 0
7824    0::pg_catalog.oid as attcollation,
7825    -- Columns added because of the peeling. (Note that there are 2 of these here.)
7826    d.name as database_name,
7827    pg_type_all_databases.database_name as pg_type_database_name
7828FROM (
7829    -- pg_attribute catalogs columns on relations and indexes
7830    SELECT id, oid, schema_id, name, type FROM mz_catalog.mz_relations
7831    UNION ALL
7832        SELECT mz_indexes.id, mz_indexes.oid, mz_relations.schema_id, mz_indexes.name, 'index' AS type
7833        FROM mz_catalog.mz_indexes
7834        JOIN mz_catalog.mz_relations ON mz_indexes.on_id = mz_relations.id
7835) AS class_objects
7836JOIN mz_catalog.mz_columns ON class_objects.id = mz_columns.id
7837JOIN mz_internal.pg_type_all_databases ON pg_type_all_databases.oid = mz_columns.type_oid
7838JOIN mz_catalog.mz_schemas ON mz_schemas.id = class_objects.schema_id
7839LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id",
7840        // Since this depends on pg_type, its id must be higher due to initialization
7841        // ordering.
7842        access: vec![PUBLIC_SELECT],
7843    }
7844});
7845
7846pub const PG_ATTRIBUTE_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
7847    name: "pg_attribute_all_databases_ind",
7848    schema: MZ_INTERNAL_SCHEMA,
7849    oid: oid::INDEX_PG_ATTRIBUTE_ALL_DATABASES_IND_OID,
7850    sql: "IN CLUSTER mz_catalog_server
7851ON mz_internal.pg_attribute_all_databases (
7852    attrelid, attname, atttypid, attlen, attnum, atttypmod, attnotnull, atthasdef, attidentity,
7853    attgenerated, attisdropped, attcollation, database_name, pg_type_database_name
7854)",
7855    is_retained_metrics_object: false,
7856};
7857
7858/// <https://www.postgresql.org/docs/current/catalog-pg-attribute.html>
7859pub static PG_ATTRIBUTE: LazyLock<BuiltinView> = LazyLock::new(|| {
7860    BuiltinView {
7861        name: "pg_attribute",
7862        schema: PG_CATALOG_SCHEMA,
7863        oid: oid::VIEW_PG_ATTRIBUTE_OID,
7864        desc: RelationDesc::builder()
7865            .with_column("attrelid", SqlScalarType::Oid.nullable(false))
7866            .with_column("attname", SqlScalarType::String.nullable(false))
7867            .with_column("atttypid", SqlScalarType::Oid.nullable(false))
7868            .with_column("attlen", SqlScalarType::Int16.nullable(true))
7869            .with_column("attnum", SqlScalarType::Int16.nullable(false))
7870            .with_column("atttypmod", SqlScalarType::Int32.nullable(false))
7871            .with_column("attndims", SqlScalarType::Int16.nullable(false))
7872            .with_column("attnotnull", SqlScalarType::Bool.nullable(false))
7873            .with_column("atthasdef", SqlScalarType::Bool.nullable(false))
7874            .with_column("attidentity", SqlScalarType::PgLegacyChar.nullable(false))
7875            .with_column("attgenerated", SqlScalarType::PgLegacyChar.nullable(false))
7876            .with_column("attisdropped", SqlScalarType::Bool.nullable(false))
7877            .with_column("attcollation", SqlScalarType::Oid.nullable(false))
7878            .finish(),
7879        column_comments: BTreeMap::new(),
7880        sql: "
7881SELECT
7882    attrelid, attname, atttypid, attlen, attnum, atttypmod, attndims, attnotnull, atthasdef,
7883    attidentity, attgenerated, attisdropped, attcollation
7884FROM mz_internal.pg_attribute_all_databases
7885WHERE
7886  (database_name IS NULL OR database_name = pg_catalog.current_database()) AND
7887  (pg_type_database_name IS NULL OR pg_type_database_name = pg_catalog.current_database());",
7888        // Since this depends on pg_type, its id must be higher due to initialization
7889        // ordering.
7890        access: vec![PUBLIC_SELECT],
7891    }
7892});
7893
7894pub static PG_PROC: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7895    name: "pg_proc",
7896    schema: PG_CATALOG_SCHEMA,
7897    oid: oid::VIEW_PG_PROC_OID,
7898    desc: RelationDesc::builder()
7899        .with_column("oid", SqlScalarType::Oid.nullable(false))
7900        .with_column("proname", SqlScalarType::String.nullable(false))
7901        .with_column("pronamespace", SqlScalarType::Oid.nullable(false))
7902        .with_column("proowner", SqlScalarType::Oid.nullable(false))
7903        .with_column("proargdefaults", SqlScalarType::String.nullable(true))
7904        .with_column("prorettype", SqlScalarType::Oid.nullable(false))
7905        .finish(),
7906    column_comments: BTreeMap::new(),
7907    sql: "SELECT
7908    mz_functions.oid,
7909    mz_functions.name AS proname,
7910    mz_schemas.oid AS pronamespace,
7911    role_owner.oid AS proowner,
7912    NULL::pg_catalog.text AS proargdefaults,
7913    ret_type.oid AS prorettype
7914FROM mz_catalog.mz_functions
7915JOIN mz_catalog.mz_schemas ON mz_functions.schema_id = mz_schemas.id
7916LEFT JOIN mz_catalog.mz_databases d ON d.id = mz_schemas.database_id
7917JOIN mz_catalog.mz_types AS ret_type ON mz_functions.return_type_id = ret_type.id
7918JOIN mz_catalog.mz_roles role_owner ON role_owner.id = mz_functions.owner_id
7919WHERE mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()",
7920    access: vec![PUBLIC_SELECT],
7921});
7922
7923pub static PG_OPERATOR: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7924    name: "pg_operator",
7925    schema: PG_CATALOG_SCHEMA,
7926    oid: oid::VIEW_PG_OPERATOR_OID,
7927    desc: RelationDesc::builder()
7928        .with_column("oid", SqlScalarType::Oid.nullable(false))
7929        .with_column("oprname", SqlScalarType::String.nullable(false))
7930        .with_column("oprresult", SqlScalarType::Oid.nullable(false))
7931        .with_column("oprleft", SqlScalarType::Oid.nullable(false))
7932        .with_column("oprright", SqlScalarType::Oid.nullable(false))
7933        .with_key(vec![0, 1, 2, 3, 4])
7934        .finish(),
7935    column_comments: BTreeMap::new(),
7936    sql: "SELECT
7937    mz_operators.oid,
7938    mz_operators.name AS oprname,
7939    ret_type.oid AS oprresult,
7940    left_type.oid as oprleft,
7941    right_type.oid as oprright
7942FROM mz_catalog.mz_operators
7943JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7944JOIN mz_catalog.mz_types AS left_type ON mz_operators.argument_type_ids[1] = left_type.id
7945JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[2] = right_type.id
7946WHERE array_length(mz_operators.argument_type_ids, 1) = 2
7947UNION SELECT
7948    mz_operators.oid,
7949    mz_operators.name AS oprname,
7950    ret_type.oid AS oprresult,
7951    0 as oprleft,
7952    right_type.oid as oprright
7953FROM mz_catalog.mz_operators
7954JOIN mz_catalog.mz_types AS ret_type ON mz_operators.return_type_id = ret_type.id
7955JOIN mz_catalog.mz_types AS right_type ON mz_operators.argument_type_ids[1] = right_type.id
7956WHERE array_length(mz_operators.argument_type_ids, 1) = 1",
7957    access: vec![PUBLIC_SELECT],
7958});
7959
7960pub static PG_RANGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7961    name: "pg_range",
7962    schema: PG_CATALOG_SCHEMA,
7963    oid: oid::VIEW_PG_RANGE_OID,
7964    desc: RelationDesc::builder()
7965        .with_column("rngtypid", SqlScalarType::Oid.nullable(false))
7966        .with_column("rngsubtype", SqlScalarType::Oid.nullable(false))
7967        .with_key(vec![])
7968        .finish(),
7969    column_comments: BTreeMap::new(),
7970    sql: "SELECT
7971    NULL::pg_catalog.oid AS rngtypid,
7972    NULL::pg_catalog.oid AS rngsubtype
7973WHERE false",
7974    access: vec![PUBLIC_SELECT],
7975});
7976
7977pub static PG_ENUM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
7978    name: "pg_enum",
7979    schema: PG_CATALOG_SCHEMA,
7980    oid: oid::VIEW_PG_ENUM_OID,
7981    desc: RelationDesc::builder()
7982        .with_column("oid", SqlScalarType::Oid.nullable(false))
7983        .with_column("enumtypid", SqlScalarType::Oid.nullable(false))
7984        .with_column("enumsortorder", SqlScalarType::Float32.nullable(false))
7985        .with_column("enumlabel", SqlScalarType::String.nullable(false))
7986        .with_key(vec![])
7987        .finish(),
7988    column_comments: BTreeMap::new(),
7989    sql: "SELECT
7990    NULL::pg_catalog.oid AS oid,
7991    NULL::pg_catalog.oid AS enumtypid,
7992    NULL::pg_catalog.float4 AS enumsortorder,
7993    NULL::pg_catalog.text AS enumlabel
7994WHERE false",
7995    access: vec![PUBLIC_SELECT],
7996});
7997
7998/// Peeled version of `PG_ATTRDEF`:
7999/// - This doesn't check `mz_schemas.database_id IS NULL OR d.name = pg_catalog.current_database()`,
8000///   in order to make this view indexable.
8001pub static PG_ATTRDEF_ALL_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8002    name: "pg_attrdef_all_databases",
8003    schema: MZ_INTERNAL_SCHEMA,
8004    oid: oid::VIEW_PG_ATTRDEF_ALL_DATABASES_OID,
8005    desc: RelationDesc::builder()
8006        .with_column("oid", SqlScalarType::Oid.nullable(true))
8007        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
8008        .with_column("adnum", SqlScalarType::Int64.nullable(false))
8009        .with_column("adbin", SqlScalarType::String.nullable(false))
8010        .with_column("adsrc", SqlScalarType::String.nullable(false))
8011        .finish(),
8012    column_comments: BTreeMap::new(),
8013    sql: "
8014SELECT
8015    NULL::pg_catalog.oid AS oid,
8016    mz_objects.oid AS adrelid,
8017    mz_columns.position::int8 AS adnum,
8018    mz_columns.default AS adbin,
8019    mz_columns.default AS adsrc
8020FROM mz_catalog.mz_columns
8021    JOIN mz_catalog.mz_objects ON mz_columns.id = mz_objects.id
8022WHERE default IS NOT NULL",
8023    access: vec![PUBLIC_SELECT],
8024});
8025
8026pub const PG_ATTRDEF_ALL_DATABASES_IND: BuiltinIndex = BuiltinIndex {
8027    name: "pg_attrdef_all_databases_ind",
8028    schema: MZ_INTERNAL_SCHEMA,
8029    oid: oid::INDEX_PG_ATTRDEF_ALL_DATABASES_IND_OID,
8030    sql: "IN CLUSTER mz_catalog_server
8031ON mz_internal.pg_attrdef_all_databases (oid, adrelid, adnum, adbin, adsrc)",
8032    is_retained_metrics_object: false,
8033};
8034
8035pub static PG_ATTRDEF: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8036    name: "pg_attrdef",
8037    schema: PG_CATALOG_SCHEMA,
8038    oid: oid::VIEW_PG_ATTRDEF_OID,
8039    desc: RelationDesc::builder()
8040        .with_column("oid", SqlScalarType::Oid.nullable(true))
8041        .with_column("adrelid", SqlScalarType::Oid.nullable(false))
8042        .with_column("adnum", SqlScalarType::Int64.nullable(false))
8043        .with_column("adbin", SqlScalarType::String.nullable(false))
8044        .with_column("adsrc", SqlScalarType::String.nullable(false))
8045        .finish(),
8046    column_comments: BTreeMap::new(),
8047    sql: "
8048SELECT
8049    pg_attrdef_all_databases.oid as oid,
8050    adrelid,
8051    adnum,
8052    adbin,
8053    adsrc
8054FROM mz_internal.pg_attrdef_all_databases
8055    JOIN mz_catalog.mz_databases d ON (d.id IS NULL OR d.name = pg_catalog.current_database());",
8056    access: vec![PUBLIC_SELECT],
8057});
8058
8059pub static PG_SETTINGS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8060    name: "pg_settings",
8061    schema: PG_CATALOG_SCHEMA,
8062    oid: oid::VIEW_PG_SETTINGS_OID,
8063    desc: RelationDesc::builder()
8064        .with_column("name", SqlScalarType::String.nullable(false))
8065        .with_column("setting", SqlScalarType::String.nullable(false))
8066        .with_key(vec![])
8067        .finish(),
8068    column_comments: BTreeMap::new(),
8069    sql: "SELECT
8070    name, setting
8071FROM (VALUES
8072    ('max_index_keys'::pg_catalog.text, '1000'::pg_catalog.text)
8073) AS _ (name, setting)",
8074    access: vec![PUBLIC_SELECT],
8075});
8076
8077pub static PG_AUTH_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8078    name: "pg_auth_members",
8079    schema: PG_CATALOG_SCHEMA,
8080    oid: oid::VIEW_PG_AUTH_MEMBERS_OID,
8081    desc: RelationDesc::builder()
8082        .with_column("roleid", SqlScalarType::Oid.nullable(false))
8083        .with_column("member", SqlScalarType::Oid.nullable(false))
8084        .with_column("grantor", SqlScalarType::Oid.nullable(false))
8085        .with_column("admin_option", SqlScalarType::Bool.nullable(false))
8086        .finish(),
8087    column_comments: BTreeMap::new(),
8088    sql: "SELECT
8089    role.oid AS roleid,
8090    member.oid AS member,
8091    grantor.oid AS grantor,
8092    -- Materialize hasn't implemented admin_option.
8093    false as admin_option
8094FROM mz_catalog.mz_role_members membership
8095JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
8096JOIN mz_catalog.mz_roles member ON membership.member = member.id
8097JOIN mz_catalog.mz_roles grantor ON membership.grantor = grantor.id",
8098    access: vec![PUBLIC_SELECT],
8099});
8100
8101pub static PG_EVENT_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8102    name: "pg_event_trigger",
8103    schema: PG_CATALOG_SCHEMA,
8104    oid: oid::VIEW_PG_EVENT_TRIGGER_OID,
8105    desc: RelationDesc::builder()
8106        .with_column("oid", SqlScalarType::Oid.nullable(false))
8107        .with_column("evtname", SqlScalarType::String.nullable(false))
8108        .with_column("evtevent", SqlScalarType::String.nullable(false))
8109        .with_column("evtowner", SqlScalarType::Oid.nullable(false))
8110        .with_column("evtfoid", SqlScalarType::Oid.nullable(false))
8111        .with_column("evtenabled", SqlScalarType::PgLegacyChar.nullable(false))
8112        .with_column(
8113            "evttags",
8114            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
8115        )
8116        .with_key(vec![])
8117        .finish(),
8118    column_comments: BTreeMap::new(),
8119    sql: "SELECT
8120        NULL::pg_catalog.oid AS oid,
8121        NULL::pg_catalog.text AS evtname,
8122        NULL::pg_catalog.text AS evtevent,
8123        NULL::pg_catalog.oid AS evtowner,
8124        NULL::pg_catalog.oid AS evtfoid,
8125        NULL::pg_catalog.char AS evtenabled,
8126        NULL::pg_catalog.text[] AS evttags
8127    WHERE false",
8128    access: vec![PUBLIC_SELECT],
8129});
8130
8131pub static PG_LANGUAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8132    name: "pg_language",
8133    schema: PG_CATALOG_SCHEMA,
8134    oid: oid::VIEW_PG_LANGUAGE_OID,
8135    desc: RelationDesc::builder()
8136        .with_column("oid", SqlScalarType::Oid.nullable(false))
8137        .with_column("lanname", SqlScalarType::String.nullable(false))
8138        .with_column("lanowner", SqlScalarType::Oid.nullable(false))
8139        .with_column("lanispl", SqlScalarType::Bool.nullable(false))
8140        .with_column("lanpltrusted", SqlScalarType::Bool.nullable(false))
8141        .with_column("lanplcallfoid", SqlScalarType::Oid.nullable(false))
8142        .with_column("laninline", SqlScalarType::Oid.nullable(false))
8143        .with_column("lanvalidator", SqlScalarType::Oid.nullable(false))
8144        .with_column(
8145            "lanacl",
8146            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
8147        )
8148        .with_key(vec![])
8149        .finish(),
8150    column_comments: BTreeMap::new(),
8151    sql: "SELECT
8152        NULL::pg_catalog.oid  AS oid,
8153        NULL::pg_catalog.text AS lanname,
8154        NULL::pg_catalog.oid  AS lanowner,
8155        NULL::pg_catalog.bool AS lanispl,
8156        NULL::pg_catalog.bool AS lanpltrusted,
8157        NULL::pg_catalog.oid  AS lanplcallfoid,
8158        NULL::pg_catalog.oid  AS laninline,
8159        NULL::pg_catalog.oid  AS lanvalidator,
8160        NULL::pg_catalog.text[] AS lanacl
8161    WHERE false",
8162    access: vec![PUBLIC_SELECT],
8163});
8164
8165pub static PG_SHDESCRIPTION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8166    name: "pg_shdescription",
8167    schema: PG_CATALOG_SCHEMA,
8168    oid: oid::VIEW_PG_SHDESCRIPTION_OID,
8169    desc: RelationDesc::builder()
8170        .with_column("objoid", SqlScalarType::Oid.nullable(false))
8171        .with_column("classoid", SqlScalarType::Oid.nullable(false))
8172        .with_column("description", SqlScalarType::String.nullable(false))
8173        .with_key(vec![])
8174        .finish(),
8175    column_comments: BTreeMap::new(),
8176    sql: "SELECT
8177        NULL::pg_catalog.oid AS objoid,
8178        NULL::pg_catalog.oid AS classoid,
8179        NULL::pg_catalog.text AS description
8180    WHERE false",
8181    access: vec![PUBLIC_SELECT],
8182});
8183
8184pub static PG_TIMEZONE_ABBREVS: LazyLock<BuiltinView> = LazyLock::new(|| {
8185    BuiltinView {
8186        name: "pg_timezone_abbrevs",
8187        schema: PG_CATALOG_SCHEMA,
8188        oid: oid::VIEW_PG_TIMEZONE_ABBREVS_OID,
8189        desc: RelationDesc::builder()
8190            .with_column("abbrev", SqlScalarType::String.nullable(false))
8191            .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8192            .with_column("is_dst", SqlScalarType::Bool.nullable(true))
8193            .with_key(vec![0])
8194            .finish(),
8195        column_comments: BTreeMap::new(),
8196        sql: "SELECT
8197    abbreviation AS abbrev,
8198    COALESCE(utc_offset, timezone_offset(timezone_name, now()).base_utc_offset + timezone_offset(timezone_name, now()).dst_offset)
8199        AS utc_offset,
8200    COALESCE(dst, timezone_offset(timezone_name, now()).dst_offset <> INTERVAL '0')
8201        AS is_dst
8202FROM mz_catalog.mz_timezone_abbreviations",
8203        access: vec![PUBLIC_SELECT],
8204    }
8205});
8206
8207pub static PG_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8208    name: "pg_timezone_names",
8209    schema: PG_CATALOG_SCHEMA,
8210    oid: oid::VIEW_PG_TIMEZONE_NAMES_OID,
8211    desc: RelationDesc::builder()
8212        .with_column("name", SqlScalarType::String.nullable(false))
8213        .with_column("abbrev", SqlScalarType::String.nullable(true))
8214        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8215        .with_column("is_dst", SqlScalarType::Bool.nullable(true))
8216        .with_key(vec![0])
8217        .finish(),
8218    column_comments: BTreeMap::new(),
8219    sql: "SELECT
8220    name,
8221    timezone_offset(name, now()).abbrev AS abbrev,
8222    timezone_offset(name, now()).base_utc_offset + timezone_offset(name, now()).dst_offset
8223        AS utc_offset,
8224    timezone_offset(name, now()).dst_offset <> INTERVAL '0'
8225        AS is_dst
8226FROM mz_catalog.mz_timezone_names",
8227    access: vec![PUBLIC_SELECT],
8228});
8229
8230pub static MZ_TIMEZONE_ABBREVIATIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8231    name: "mz_timezone_abbreviations",
8232    schema: MZ_CATALOG_SCHEMA,
8233    oid: oid::VIEW_MZ_TIMEZONE_ABBREVIATIONS_OID,
8234    desc: RelationDesc::builder()
8235        .with_column("abbreviation", SqlScalarType::String.nullable(false))
8236        .with_column("utc_offset", SqlScalarType::Interval.nullable(true))
8237        .with_column("dst", SqlScalarType::Bool.nullable(true))
8238        .with_column("timezone_name", SqlScalarType::String.nullable(true))
8239        .with_key(vec![0])
8240        .finish(),
8241    column_comments: BTreeMap::from_iter([
8242        ("abbreviation", "The timezone abbreviation."),
8243        (
8244            "utc_offset",
8245            "The UTC offset of the timezone or `NULL` if fixed.",
8246        ),
8247        (
8248            "dst",
8249            "Whether the timezone is in daylight savings or `NULL` if fixed.",
8250        ),
8251        (
8252            "timezone_name",
8253            "The full name of the non-fixed timezone or `NULL` if not fixed.",
8254        ),
8255    ]),
8256    sql: format!(
8257        "SELECT * FROM ({}) _ (abbreviation, utc_offset, dst, timezone_name)",
8258        mz_pgtz::abbrev::MZ_CATALOG_TIMEZONE_ABBREVIATIONS_SQL,
8259    )
8260    .leak(),
8261    access: vec![PUBLIC_SELECT],
8262});
8263
8264pub static MZ_TIMEZONE_NAMES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8265    name: "mz_timezone_names",
8266    schema: MZ_CATALOG_SCHEMA,
8267    oid: oid::VIEW_MZ_TIMEZONE_NAMES_OID,
8268    desc: RelationDesc::builder()
8269        .with_column("name", SqlScalarType::String.nullable(false))
8270        .with_key(vec![0])
8271        .finish(),
8272    column_comments: BTreeMap::from_iter([("name", "The timezone name.")]),
8273    sql: format!(
8274        "SELECT * FROM ({}) _ (name)",
8275        mz_pgtz::timezone::MZ_CATALOG_TIMEZONE_NAMES_SQL,
8276    )
8277    .leak(),
8278    access: vec![PUBLIC_SELECT],
8279});
8280
8281pub static MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8282    LazyLock::new(|| BuiltinView {
8283        name: "mz_peek_durations_histogram_per_worker",
8284        schema: MZ_INTROSPECTION_SCHEMA,
8285        oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8286        desc: RelationDesc::builder()
8287            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8288            .with_column("type", SqlScalarType::String.nullable(false))
8289            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8290            .with_column("count", SqlScalarType::Int64.nullable(false))
8291            .with_key(vec![0, 1, 2])
8292            .finish(),
8293        column_comments: BTreeMap::new(),
8294        sql: "SELECT
8295    worker_id, type, duration_ns, pg_catalog.count(*) AS count
8296FROM
8297    mz_introspection.mz_peek_durations_histogram_raw
8298GROUP BY
8299    worker_id, type, duration_ns",
8300        access: vec![PUBLIC_SELECT],
8301    });
8302
8303pub static MZ_PEEK_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8304    name: "mz_peek_durations_histogram",
8305    schema: MZ_INTROSPECTION_SCHEMA,
8306    oid: oid::VIEW_MZ_PEEK_DURATIONS_HISTOGRAM_OID,
8307    desc: RelationDesc::builder()
8308        .with_column("type", SqlScalarType::String.nullable(false))
8309        .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8310        .with_column(
8311            "count",
8312            SqlScalarType::Numeric {
8313                max_scale: Some(NumericMaxScale::ZERO),
8314            }
8315            .nullable(false),
8316        )
8317        .with_key(vec![0, 1])
8318        .finish(),
8319    column_comments: BTreeMap::from_iter([
8320        ("type", "The peek variant: `index` or `persist`."),
8321        (
8322            "duration_ns",
8323            "The upper bound of the bucket in nanoseconds.",
8324        ),
8325        (
8326            "count",
8327            "The (noncumulative) count of peeks in this bucket.",
8328        ),
8329    ]),
8330    sql: "
8331SELECT
8332    type, duration_ns,
8333    pg_catalog.sum(count) AS count
8334FROM mz_introspection.mz_peek_durations_histogram_per_worker
8335GROUP BY type, duration_ns",
8336    access: vec![PUBLIC_SELECT],
8337});
8338
8339pub static MZ_SCHEDULING_ELAPSED_PER_WORKER: LazyLock<BuiltinView> =
8340    LazyLock::new(|| BuiltinView {
8341        name: "mz_scheduling_elapsed_per_worker",
8342        schema: MZ_INTROSPECTION_SCHEMA,
8343        oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_PER_WORKER_OID,
8344        desc: RelationDesc::builder()
8345            .with_column("id", SqlScalarType::UInt64.nullable(false))
8346            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8347            .with_column("elapsed_ns", SqlScalarType::Int64.nullable(false))
8348            .with_key(vec![0, 1])
8349            .finish(),
8350        column_comments: BTreeMap::new(),
8351        sql: "SELECT
8352    id, worker_id, pg_catalog.count(*) AS elapsed_ns
8353FROM
8354    mz_introspection.mz_scheduling_elapsed_raw
8355GROUP BY
8356    id, worker_id",
8357        access: vec![PUBLIC_SELECT],
8358    });
8359
8360pub static MZ_SCHEDULING_ELAPSED: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8361    name: "mz_scheduling_elapsed",
8362    schema: MZ_INTROSPECTION_SCHEMA,
8363    oid: oid::VIEW_MZ_SCHEDULING_ELAPSED_OID,
8364    desc: RelationDesc::builder()
8365        .with_column("id", SqlScalarType::UInt64.nullable(false))
8366        .with_column(
8367            "elapsed_ns",
8368            SqlScalarType::Numeric {
8369                max_scale: Some(NumericMaxScale::ZERO),
8370            }
8371            .nullable(false),
8372        )
8373        .with_key(vec![0])
8374        .finish(),
8375    column_comments: BTreeMap::from_iter([
8376        (
8377            "id",
8378            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8379        ),
8380        (
8381            "elapsed_ns",
8382            "The total elapsed time spent in the operator in nanoseconds.",
8383        ),
8384    ]),
8385    sql: "
8386SELECT
8387    id,
8388    pg_catalog.sum(elapsed_ns) AS elapsed_ns
8389FROM mz_introspection.mz_scheduling_elapsed_per_worker
8390GROUP BY id",
8391    access: vec![PUBLIC_SELECT],
8392});
8393
8394pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8395    LazyLock::new(|| BuiltinView {
8396        name: "mz_compute_operator_durations_histogram_per_worker",
8397        schema: MZ_INTROSPECTION_SCHEMA,
8398        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER_OID,
8399        desc: RelationDesc::builder()
8400            .with_column("id", SqlScalarType::UInt64.nullable(false))
8401            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8402            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8403            .with_column("count", SqlScalarType::Int64.nullable(false))
8404            .with_key(vec![0, 1, 2])
8405            .finish(),
8406        column_comments: BTreeMap::new(),
8407        sql: "SELECT
8408    id, worker_id, duration_ns, pg_catalog.count(*) AS count
8409FROM
8410    mz_introspection.mz_compute_operator_durations_histogram_raw
8411GROUP BY
8412    id, worker_id, duration_ns",
8413        access: vec![PUBLIC_SELECT],
8414    });
8415
8416pub static MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM: LazyLock<BuiltinView> =
8417    LazyLock::new(|| BuiltinView {
8418        name: "mz_compute_operator_durations_histogram",
8419        schema: MZ_INTROSPECTION_SCHEMA,
8420        oid: oid::VIEW_MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_OID,
8421        desc: RelationDesc::builder()
8422            .with_column("id", SqlScalarType::UInt64.nullable(false))
8423            .with_column("duration_ns", SqlScalarType::UInt64.nullable(false))
8424            .with_column(
8425                "count",
8426                SqlScalarType::Numeric {
8427                    max_scale: Some(NumericMaxScale::ZERO),
8428                }
8429                .nullable(false),
8430            )
8431            .with_key(vec![0, 1])
8432            .finish(),
8433        column_comments: BTreeMap::from_iter([
8434            (
8435                "id",
8436                "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
8437            ),
8438            (
8439                "duration_ns",
8440                "The upper bound of the duration bucket in nanoseconds.",
8441            ),
8442            (
8443                "count",
8444                "The (noncumulative) count of invocations in the bucket.",
8445            ),
8446        ]),
8447        sql: "
8448SELECT
8449    id,
8450    duration_ns,
8451    pg_catalog.sum(count) AS count
8452FROM mz_introspection.mz_compute_operator_durations_histogram_per_worker
8453GROUP BY id, duration_ns",
8454        access: vec![PUBLIC_SELECT],
8455    });
8456
8457pub static MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER: LazyLock<BuiltinView> =
8458    LazyLock::new(|| BuiltinView {
8459        name: "mz_scheduling_parks_histogram_per_worker",
8460        schema: MZ_INTROSPECTION_SCHEMA,
8461        oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER_OID,
8462        desc: RelationDesc::builder()
8463            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8464            .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8465            .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8466            .with_column("count", SqlScalarType::Int64.nullable(false))
8467            .with_key(vec![0, 1, 2])
8468            .finish(),
8469        column_comments: BTreeMap::new(),
8470        sql: "SELECT
8471    worker_id, slept_for_ns, requested_ns, pg_catalog.count(*) AS count
8472FROM
8473    mz_introspection.mz_scheduling_parks_histogram_raw
8474GROUP BY
8475    worker_id, slept_for_ns, requested_ns",
8476        access: vec![PUBLIC_SELECT],
8477    });
8478
8479pub static MZ_SCHEDULING_PARKS_HISTOGRAM: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8480    name: "mz_scheduling_parks_histogram",
8481    schema: MZ_INTROSPECTION_SCHEMA,
8482    oid: oid::VIEW_MZ_SCHEDULING_PARKS_HISTOGRAM_OID,
8483    desc: RelationDesc::builder()
8484        .with_column("slept_for_ns", SqlScalarType::UInt64.nullable(false))
8485        .with_column("requested_ns", SqlScalarType::UInt64.nullable(false))
8486        .with_column(
8487            "count",
8488            SqlScalarType::Numeric {
8489                max_scale: Some(NumericMaxScale::ZERO),
8490            }
8491            .nullable(false),
8492        )
8493        .with_key(vec![0, 1])
8494        .finish(),
8495    column_comments: BTreeMap::from_iter([
8496        (
8497            "slept_for_ns",
8498            "The actual length of the park event in nanoseconds.",
8499        ),
8500        (
8501            "requested_ns",
8502            "The requested length of the park event in nanoseconds.",
8503        ),
8504        (
8505            "count",
8506            "The (noncumulative) count of park events in this bucket.",
8507        ),
8508    ]),
8509    sql: "
8510SELECT
8511    slept_for_ns,
8512    requested_ns,
8513    pg_catalog.sum(count) AS count
8514FROM mz_introspection.mz_scheduling_parks_histogram_per_worker
8515GROUP BY slept_for_ns, requested_ns",
8516    access: vec![PUBLIC_SELECT],
8517});
8518
8519pub static MZ_COMPUTE_ERROR_COUNTS_PER_WORKER: LazyLock<BuiltinView> =
8520    LazyLock::new(|| BuiltinView {
8521        name: "mz_compute_error_counts_per_worker",
8522        schema: MZ_INTROSPECTION_SCHEMA,
8523        oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_PER_WORKER_OID,
8524        desc: RelationDesc::builder()
8525            .with_column("export_id", SqlScalarType::String.nullable(false))
8526            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8527            .with_column("count", SqlScalarType::Int64.nullable(false))
8528            .with_key(vec![0, 1, 2])
8529            .finish(),
8530        column_comments: BTreeMap::new(),
8531        sql: "
8532WITH MUTUALLY RECURSIVE
8533    -- Indexes that reuse existing indexes rather than maintaining separate dataflows.
8534    -- For these we don't log error counts separately, so we need to forward the error counts from
8535    -- their dependencies instead.
8536    index_reuses(reuse_id text, index_id text) AS (
8537        SELECT d.object_id, d.dependency_id
8538        FROM mz_internal.mz_compute_dependencies d
8539        JOIN mz_introspection.mz_compute_exports e ON (e.export_id = d.object_id)
8540        WHERE NOT EXISTS (
8541            SELECT 1 FROM mz_introspection.mz_dataflows
8542            WHERE id = e.dataflow_id
8543        )
8544    ),
8545    -- Error counts that were directly logged on compute exports.
8546    direct_errors(export_id text, worker_id uint8, count int8) AS (
8547        SELECT export_id, worker_id, count
8548        FROM mz_introspection.mz_compute_error_counts_raw
8549    ),
8550    -- Error counts propagated to index reused.
8551    all_errors(export_id text, worker_id uint8, count int8) AS (
8552        SELECT * FROM direct_errors
8553        UNION
8554        SELECT r.reuse_id, e.worker_id, e.count
8555        FROM all_errors e
8556        JOIN index_reuses r ON (r.index_id = e.export_id)
8557    )
8558SELECT * FROM all_errors",
8559        access: vec![PUBLIC_SELECT],
8560    });
8561
8562pub static MZ_COMPUTE_ERROR_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8563    name: "mz_compute_error_counts",
8564    schema: MZ_INTROSPECTION_SCHEMA,
8565    oid: oid::VIEW_MZ_COMPUTE_ERROR_COUNTS_OID,
8566    desc: RelationDesc::builder()
8567        .with_column("export_id", SqlScalarType::String.nullable(false))
8568        .with_column(
8569            "count",
8570            SqlScalarType::Numeric {
8571                max_scale: Some(NumericMaxScale::ZERO),
8572            }
8573            .nullable(false),
8574        )
8575        .with_key(vec![0])
8576        .finish(),
8577    column_comments: BTreeMap::from_iter([
8578        (
8579            "export_id",
8580            "The ID of the dataflow export. Corresponds to `mz_compute_exports.export_id`.",
8581        ),
8582        (
8583            "count",
8584            "The count of errors present in this dataflow export.",
8585        ),
8586    ]),
8587    sql: "
8588SELECT
8589    export_id,
8590    pg_catalog.sum(count) AS count
8591FROM mz_introspection.mz_compute_error_counts_per_worker
8592GROUP BY export_id
8593HAVING pg_catalog.sum(count) != 0",
8594    access: vec![PUBLIC_SELECT],
8595});
8596
8597pub static MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED: LazyLock<BuiltinSource> =
8598    LazyLock::new(|| BuiltinSource {
8599        // TODO(database-issues#8173): Rename this source to `mz_compute_error_counts_raw`. Currently this causes a
8600        // naming conflict because the resolver stumbles over the source with the same name in
8601        // `mz_introspection` due to the automatic schema translation.
8602        name: "mz_compute_error_counts_raw_unified",
8603        schema: MZ_INTERNAL_SCHEMA,
8604        oid: oid::SOURCE_MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED_OID,
8605        desc: RelationDesc::builder()
8606            .with_column("replica_id", SqlScalarType::String.nullable(false))
8607            .with_column("object_id", SqlScalarType::String.nullable(false))
8608            .with_column(
8609                "count",
8610                SqlScalarType::Numeric { max_scale: None }.nullable(false),
8611            )
8612            .finish(),
8613        data_source: IntrospectionType::ComputeErrorCounts.into(),
8614        column_comments: BTreeMap::new(),
8615        is_retained_metrics_object: false,
8616        access: vec![PUBLIC_SELECT],
8617    });
8618
8619pub static MZ_COMPUTE_HYDRATION_TIMES: LazyLock<BuiltinSource> = LazyLock::new(|| BuiltinSource {
8620    name: "mz_compute_hydration_times",
8621    schema: MZ_INTERNAL_SCHEMA,
8622    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_TIMES_OID,
8623    desc: RelationDesc::builder()
8624        .with_column("replica_id", SqlScalarType::String.nullable(false))
8625        .with_column("object_id", SqlScalarType::String.nullable(false))
8626        .with_column("time_ns", SqlScalarType::UInt64.nullable(true))
8627        .finish(),
8628    data_source: IntrospectionType::ComputeHydrationTimes.into(),
8629    column_comments: BTreeMap::new(),
8630    is_retained_metrics_object: true,
8631    access: vec![PUBLIC_SELECT],
8632});
8633
8634pub static MZ_COMPUTE_HYDRATION_TIMES_IND: LazyLock<BuiltinIndex> =
8635    LazyLock::new(|| BuiltinIndex {
8636        name: "mz_compute_hydration_times_ind",
8637        schema: MZ_INTERNAL_SCHEMA,
8638        oid: oid::INDEX_MZ_COMPUTE_HYDRATION_TIMES_IND_OID,
8639        sql: "IN CLUSTER mz_catalog_server
8640    ON mz_internal.mz_compute_hydration_times (replica_id)",
8641        is_retained_metrics_object: true,
8642    });
8643
8644pub static MZ_COMPUTE_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8645    name: "mz_compute_hydration_statuses",
8646    schema: MZ_INTERNAL_SCHEMA,
8647    oid: oid::SOURCE_MZ_COMPUTE_HYDRATION_STATUSES_OID,
8648    desc: RelationDesc::builder()
8649        .with_column("object_id", SqlScalarType::String.nullable(false))
8650        .with_column("replica_id", SqlScalarType::String.nullable(false))
8651        .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8652        .with_column("hydration_time", SqlScalarType::Interval.nullable(true))
8653        .finish(),
8654    column_comments: BTreeMap::from_iter([
8655        (
8656            "object_id",
8657            "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`",
8658        ),
8659        ("replica_id", "The ID of a cluster replica."),
8660        (
8661            "hydrated",
8662            "Whether the compute object is hydrated on the replica.",
8663        ),
8664        (
8665            "hydration_time",
8666            "The amount of time it took for the replica to hydrate the compute object.",
8667        ),
8668    ]),
8669    sql: "
8670WITH
8671    dataflows AS (
8672        SELECT
8673            object_id,
8674            replica_id,
8675            time_ns IS NOT NULL AS hydrated,
8676            ((time_ns / 1000) || 'microseconds')::interval AS hydration_time
8677        FROM mz_internal.mz_compute_hydration_times
8678    ),
8679    -- MVs that have advanced to the empty frontier don't have a dataflow installed anymore and
8680    -- therefore don't show up in `mz_compute_hydration_times`. We still want to show them here to
8681    -- avoid surprises for people joining `mz_materialized_views` against this relation (like the
8682    -- blue-green readiness query does), so we include them as 'hydrated'.
8683    complete_mvs AS (
8684        SELECT
8685            mv.id,
8686            f.replica_id,
8687            true AS hydrated,
8688            NULL::interval AS hydration_time
8689        FROM mz_materialized_views mv
8690        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = mv.id
8691        WHERE f.write_frontier IS NULL
8692    ),
8693    -- Ditto CTs
8694    complete_cts AS (
8695        SELECT
8696            ct.id,
8697            f.replica_id,
8698            true AS hydrated,
8699            NULL::interval AS hydration_time
8700        FROM mz_internal.mz_continual_tasks ct
8701        JOIN mz_catalog.mz_cluster_replica_frontiers f ON f.object_id = ct.id
8702        WHERE f.write_frontier IS NULL
8703    )
8704SELECT * FROM dataflows
8705UNION ALL
8706SELECT * FROM complete_mvs
8707UNION ALL
8708SELECT * FROM complete_cts",
8709    access: vec![PUBLIC_SELECT],
8710});
8711
8712pub static MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES: LazyLock<BuiltinSource> = LazyLock::new(|| {
8713    BuiltinSource {
8714        name: "mz_compute_operator_hydration_statuses",
8715        schema: MZ_INTERNAL_SCHEMA,
8716        oid: oid::SOURCE_MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_OID,
8717        desc: RelationDesc::builder()
8718            .with_column("replica_id", SqlScalarType::String.nullable(false))
8719            .with_column("object_id", SqlScalarType::String.nullable(false))
8720            .with_column(
8721                "physical_plan_node_id",
8722                SqlScalarType::UInt64.nullable(false),
8723            )
8724            .with_column("hydrated", SqlScalarType::Bool.nullable(false))
8725            .with_key(vec![0, 1, 2])
8726            .finish(),
8727        data_source: IntrospectionType::ComputeOperatorHydrationStatus.into(),
8728        column_comments: BTreeMap::from_iter([
8729            ("replica_id", "The ID of a cluster replica."),
8730            (
8731                "object_id",
8732                "The ID of a compute object. Corresponds to `mz_catalog.mz_indexes.id` or `mz_catalog.mz_materialized_views.id`.",
8733            ),
8734            (
8735                "physical_plan_node_id",
8736                "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)`.",
8737            ),
8738            ("hydrated", "Whether the node is hydrated on the replica."),
8739        ]),
8740        is_retained_metrics_object: false,
8741        access: vec![PUBLIC_SELECT],
8742    }
8743});
8744
8745pub static MZ_MESSAGE_COUNTS_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8746    name: "mz_message_counts_per_worker",
8747    schema: MZ_INTROSPECTION_SCHEMA,
8748    oid: oid::VIEW_MZ_MESSAGE_COUNTS_PER_WORKER_OID,
8749    desc: RelationDesc::builder()
8750        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8751        .with_column("from_worker_id", SqlScalarType::UInt64.nullable(false))
8752        .with_column("to_worker_id", SqlScalarType::UInt64.nullable(false))
8753        .with_column("sent", SqlScalarType::Int64.nullable(false))
8754        .with_column("received", SqlScalarType::Int64.nullable(false))
8755        .with_column("batch_sent", SqlScalarType::Int64.nullable(false))
8756        .with_column("batch_received", SqlScalarType::Int64.nullable(false))
8757        .with_key(vec![0, 1, 2])
8758        .finish(),
8759    column_comments: BTreeMap::new(),
8760    sql: "
8761WITH batch_sent_cte AS (
8762    SELECT
8763        channel_id,
8764        from_worker_id,
8765        to_worker_id,
8766        pg_catalog.count(*) AS sent
8767    FROM
8768        mz_introspection.mz_message_batch_counts_sent_raw
8769    GROUP BY
8770        channel_id, from_worker_id, to_worker_id
8771),
8772batch_received_cte AS (
8773    SELECT
8774        channel_id,
8775        from_worker_id,
8776        to_worker_id,
8777        pg_catalog.count(*) AS received
8778    FROM
8779        mz_introspection.mz_message_batch_counts_received_raw
8780    GROUP BY
8781        channel_id, from_worker_id, to_worker_id
8782),
8783sent_cte AS (
8784    SELECT
8785        channel_id,
8786        from_worker_id,
8787        to_worker_id,
8788        pg_catalog.count(*) AS sent
8789    FROM
8790        mz_introspection.mz_message_counts_sent_raw
8791    GROUP BY
8792        channel_id, from_worker_id, to_worker_id
8793),
8794received_cte AS (
8795    SELECT
8796        channel_id,
8797        from_worker_id,
8798        to_worker_id,
8799        pg_catalog.count(*) AS received
8800    FROM
8801        mz_introspection.mz_message_counts_received_raw
8802    GROUP BY
8803        channel_id, from_worker_id, to_worker_id
8804)
8805SELECT
8806    sent_cte.channel_id,
8807    sent_cte.from_worker_id,
8808    sent_cte.to_worker_id,
8809    sent_cte.sent,
8810    received_cte.received,
8811    batch_sent_cte.sent AS batch_sent,
8812    batch_received_cte.received AS batch_received
8813FROM sent_cte
8814JOIN received_cte USING (channel_id, from_worker_id, to_worker_id)
8815JOIN batch_sent_cte USING (channel_id, from_worker_id, to_worker_id)
8816JOIN batch_received_cte USING (channel_id, from_worker_id, to_worker_id)",
8817    access: vec![PUBLIC_SELECT],
8818});
8819
8820pub static MZ_MESSAGE_COUNTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8821    name: "mz_message_counts",
8822    schema: MZ_INTROSPECTION_SCHEMA,
8823    oid: oid::VIEW_MZ_MESSAGE_COUNTS_OID,
8824    desc: RelationDesc::builder()
8825        .with_column("channel_id", SqlScalarType::UInt64.nullable(false))
8826        .with_column(
8827            "sent",
8828            SqlScalarType::Numeric {
8829                max_scale: Some(NumericMaxScale::ZERO),
8830            }
8831            .nullable(false),
8832        )
8833        .with_column(
8834            "received",
8835            SqlScalarType::Numeric {
8836                max_scale: Some(NumericMaxScale::ZERO),
8837            }
8838            .nullable(false),
8839        )
8840        .with_column(
8841            "batch_sent",
8842            SqlScalarType::Numeric {
8843                max_scale: Some(NumericMaxScale::ZERO),
8844            }
8845            .nullable(false),
8846        )
8847        .with_column(
8848            "batch_received",
8849            SqlScalarType::Numeric {
8850                max_scale: Some(NumericMaxScale::ZERO),
8851            }
8852            .nullable(false),
8853        )
8854        .with_key(vec![0])
8855        .finish(),
8856    column_comments: BTreeMap::from_iter([
8857        (
8858            "channel_id",
8859            "The ID of the channel. Corresponds to `mz_dataflow_channels.id`.",
8860        ),
8861        ("sent", "The number of messages sent."),
8862        ("received", "The number of messages received."),
8863        ("batch_sent", "The number of batches sent."),
8864        ("batch_received", "The number of batches received."),
8865    ]),
8866    sql: "
8867SELECT
8868    channel_id,
8869    pg_catalog.sum(sent) AS sent,
8870    pg_catalog.sum(received) AS received,
8871    pg_catalog.sum(batch_sent) AS batch_sent,
8872    pg_catalog.sum(batch_received) AS batch_received
8873FROM mz_introspection.mz_message_counts_per_worker
8874GROUP BY channel_id",
8875    access: vec![PUBLIC_SELECT],
8876});
8877
8878pub static MZ_ACTIVE_PEEKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
8879    name: "mz_active_peeks",
8880    schema: MZ_INTROSPECTION_SCHEMA,
8881    oid: oid::VIEW_MZ_ACTIVE_PEEKS_OID,
8882    desc: RelationDesc::builder()
8883        .with_column("id", SqlScalarType::Uuid.nullable(false))
8884        .with_column("object_id", SqlScalarType::String.nullable(false))
8885        .with_column("type", SqlScalarType::String.nullable(false))
8886        .with_column("time", SqlScalarType::MzTimestamp.nullable(false))
8887        .with_key(vec![0])
8888        .finish(),
8889    column_comments: BTreeMap::from_iter([
8890        ("id", "The ID of the peek request."),
8891        (
8892            "object_id",
8893            "The ID of the collection the peek is targeting. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, `mz_catalog.mz_sources.id`, or `mz_catalog.mz_tables.id`.",
8894        ),
8895        (
8896            "type",
8897            "The type of the corresponding peek: `index` if targeting an index or temporary dataflow; `persist` for a source, materialized view, or table.",
8898        ),
8899        ("time", "The timestamp the peek has requested."),
8900    ]),
8901    sql: "
8902SELECT id, object_id, type, time
8903FROM mz_introspection.mz_active_peeks_per_worker
8904WHERE worker_id = 0::uint8",
8905    access: vec![PUBLIC_SELECT],
8906});
8907
8908pub static MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER: LazyLock<BuiltinView> =
8909    LazyLock::new(|| BuiltinView {
8910        name: "mz_dataflow_operator_reachability_per_worker",
8911        schema: MZ_INTROSPECTION_SCHEMA,
8912        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER_OID,
8913        desc: RelationDesc::builder()
8914            .with_column("id", SqlScalarType::UInt64.nullable(false))
8915            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8916            .with_column("port", SqlScalarType::UInt64.nullable(false))
8917            .with_column("update_type", SqlScalarType::String.nullable(false))
8918            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8919            .with_column("count", SqlScalarType::Int64.nullable(false))
8920            .with_key(vec![0, 1, 2, 3, 4])
8921            .finish(),
8922        column_comments: BTreeMap::new(),
8923        sql: "SELECT
8924    addr2.id,
8925    reachability.worker_id,
8926    port,
8927    update_type,
8928    time,
8929    pg_catalog.count(*) as count
8930FROM
8931    mz_introspection.mz_dataflow_operator_reachability_raw reachability,
8932    mz_introspection.mz_dataflow_addresses_per_worker addr1,
8933    mz_introspection.mz_dataflow_addresses_per_worker addr2
8934WHERE
8935    addr2.address =
8936    CASE
8937        WHEN source = 0 THEN addr1.address
8938        ELSE addr1.address || reachability.source
8939    END
8940    AND addr1.id = reachability.id
8941    AND addr1.worker_id = reachability.worker_id
8942    AND addr2.worker_id = reachability.worker_id
8943GROUP BY addr2.id, reachability.worker_id, port, update_type, time",
8944        access: vec![PUBLIC_SELECT],
8945    });
8946
8947pub static MZ_DATAFLOW_OPERATOR_REACHABILITY: LazyLock<BuiltinView> =
8948    LazyLock::new(|| BuiltinView {
8949        name: "mz_dataflow_operator_reachability",
8950        schema: MZ_INTROSPECTION_SCHEMA,
8951        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_REACHABILITY_OID,
8952        desc: RelationDesc::builder()
8953            .with_column("id", SqlScalarType::UInt64.nullable(false))
8954            .with_column("port", SqlScalarType::UInt64.nullable(false))
8955            .with_column("update_type", SqlScalarType::String.nullable(false))
8956            .with_column("time", SqlScalarType::MzTimestamp.nullable(true))
8957            .with_column(
8958                "count",
8959                SqlScalarType::Numeric {
8960                    max_scale: Some(NumericMaxScale::ZERO),
8961                }
8962                .nullable(false),
8963            )
8964            .with_key(vec![0, 1, 2, 3])
8965            .finish(),
8966        column_comments: BTreeMap::new(),
8967        sql: "
8968SELECT
8969    id,
8970    port,
8971    update_type,
8972    time,
8973    pg_catalog.sum(count) as count
8974FROM mz_introspection.mz_dataflow_operator_reachability_per_worker
8975GROUP BY id, port, update_type, time",
8976        access: vec![PUBLIC_SELECT],
8977    });
8978
8979pub static MZ_ARRANGEMENT_SIZES_PER_WORKER: LazyLock<BuiltinView> = LazyLock::new(|| {
8980    BuiltinView {
8981        name: "mz_arrangement_sizes_per_worker",
8982        schema: MZ_INTROSPECTION_SCHEMA,
8983        oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_PER_WORKER_OID,
8984        desc: RelationDesc::builder()
8985            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
8986            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
8987            .with_column("records", SqlScalarType::Int64.nullable(true))
8988            .with_column("batches", SqlScalarType::Int64.nullable(true))
8989            .with_column("size", SqlScalarType::Int64.nullable(true))
8990            .with_column("capacity", SqlScalarType::Int64.nullable(true))
8991            .with_column("allocations", SqlScalarType::Int64.nullable(true))
8992            .finish(),
8993        column_comments: BTreeMap::new(),
8994        sql: "
8995WITH operators_per_worker_cte AS (
8996    SELECT
8997        id AS operator_id,
8998        worker_id
8999    FROM
9000        mz_introspection.mz_dataflow_operators_per_worker
9001),
9002batches_cte AS (
9003    SELECT
9004        operator_id,
9005        worker_id,
9006        COUNT(*) AS batches
9007    FROM
9008        mz_introspection.mz_arrangement_batches_raw
9009    GROUP BY
9010        operator_id, worker_id
9011),
9012records_cte AS (
9013    SELECT
9014        operator_id,
9015        worker_id,
9016        COUNT(*) AS records
9017    FROM
9018        mz_introspection.mz_arrangement_records_raw
9019    GROUP BY
9020        operator_id, worker_id
9021),
9022heap_size_cte AS (
9023    SELECT
9024        operator_id,
9025        worker_id,
9026        COUNT(*) AS size
9027    FROM
9028        mz_introspection.mz_arrangement_heap_size_raw
9029    GROUP BY
9030        operator_id, worker_id
9031),
9032heap_capacity_cte AS (
9033    SELECT
9034        operator_id,
9035        worker_id,
9036        COUNT(*) AS capacity
9037    FROM
9038        mz_introspection.mz_arrangement_heap_capacity_raw
9039    GROUP BY
9040        operator_id, worker_id
9041),
9042heap_allocations_cte AS (
9043    SELECT
9044        operator_id,
9045        worker_id,
9046        COUNT(*) AS allocations
9047    FROM
9048        mz_introspection.mz_arrangement_heap_allocations_raw
9049    GROUP BY
9050        operator_id, worker_id
9051),
9052batcher_records_cte AS (
9053    SELECT
9054        operator_id,
9055        worker_id,
9056        COUNT(*) AS records
9057    FROM
9058        mz_introspection.mz_arrangement_batcher_records_raw
9059    GROUP BY
9060        operator_id, worker_id
9061),
9062batcher_size_cte AS (
9063    SELECT
9064        operator_id,
9065        worker_id,
9066        COUNT(*) AS size
9067    FROM
9068        mz_introspection.mz_arrangement_batcher_size_raw
9069    GROUP BY
9070        operator_id, worker_id
9071),
9072batcher_capacity_cte AS (
9073    SELECT
9074        operator_id,
9075        worker_id,
9076        COUNT(*) AS capacity
9077    FROM
9078        mz_introspection.mz_arrangement_batcher_capacity_raw
9079    GROUP BY
9080        operator_id, worker_id
9081),
9082batcher_allocations_cte AS (
9083    SELECT
9084        operator_id,
9085        worker_id,
9086        COUNT(*) AS allocations
9087    FROM
9088        mz_introspection.mz_arrangement_batcher_allocations_raw
9089    GROUP BY
9090        operator_id, worker_id
9091),
9092combined AS (
9093    SELECT
9094        opw.operator_id,
9095        opw.worker_id,
9096        CASE
9097            WHEN records_cte.records IS NULL AND batcher_records_cte.records IS NULL THEN NULL
9098            ELSE COALESCE(records_cte.records, 0) + COALESCE(batcher_records_cte.records, 0)
9099        END AS records,
9100        batches_cte.batches AS batches,
9101        CASE
9102            WHEN heap_size_cte.size IS NULL AND batcher_size_cte.size IS NULL THEN NULL
9103            ELSE COALESCE(heap_size_cte.size, 0) + COALESCE(batcher_size_cte.size, 0)
9104        END AS size,
9105        CASE
9106            WHEN heap_capacity_cte.capacity IS NULL AND batcher_capacity_cte.capacity IS NULL THEN NULL
9107            ELSE COALESCE(heap_capacity_cte.capacity, 0) + COALESCE(batcher_capacity_cte.capacity, 0)
9108        END AS capacity,
9109        CASE
9110            WHEN heap_allocations_cte.allocations IS NULL AND batcher_allocations_cte.allocations IS NULL THEN NULL
9111            ELSE COALESCE(heap_allocations_cte.allocations, 0) + COALESCE(batcher_allocations_cte.allocations, 0)
9112        END AS allocations
9113    FROM
9114                    operators_per_worker_cte opw
9115    LEFT OUTER JOIN batches_cte USING (operator_id, worker_id)
9116    LEFT OUTER JOIN records_cte USING (operator_id, worker_id)
9117    LEFT OUTER JOIN heap_size_cte USING (operator_id, worker_id)
9118    LEFT OUTER JOIN heap_capacity_cte USING (operator_id, worker_id)
9119    LEFT OUTER JOIN heap_allocations_cte USING (operator_id, worker_id)
9120    LEFT OUTER JOIN batcher_records_cte USING (operator_id, worker_id)
9121    LEFT OUTER JOIN batcher_size_cte USING (operator_id, worker_id)
9122    LEFT OUTER JOIN batcher_capacity_cte USING (operator_id, worker_id)
9123    LEFT OUTER JOIN batcher_allocations_cte USING (operator_id, worker_id)
9124)
9125SELECT
9126    operator_id, worker_id, records, batches, size, capacity, allocations
9127FROM combined
9128WHERE
9129       records     IS NOT NULL
9130    OR batches     IS NOT NULL
9131    OR size        IS NOT NULL
9132    OR capacity    IS NOT NULL
9133    OR allocations IS NOT NULL
9134",
9135        access: vec![PUBLIC_SELECT],
9136    }
9137});
9138
9139pub static MZ_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9140    name: "mz_arrangement_sizes",
9141    schema: MZ_INTROSPECTION_SCHEMA,
9142    oid: oid::VIEW_MZ_ARRANGEMENT_SIZES_OID,
9143    desc: RelationDesc::builder()
9144        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9145        .with_column("records", SqlScalarType::Int64.nullable(true))
9146        .with_column("batches", SqlScalarType::Int64.nullable(true))
9147        .with_column("size", SqlScalarType::Int64.nullable(true))
9148        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9149        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9150        .with_key(vec![0])
9151        .finish(),
9152    column_comments: BTreeMap::from_iter([
9153        (
9154            "operator_id",
9155            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
9156        ),
9157        ("records", "The number of records in the arrangement."),
9158        ("batches", "The number of batches in the arrangement."),
9159        ("size", "The utilized size in bytes of the arrangement."),
9160        (
9161            "capacity",
9162            "The capacity in bytes of the arrangement. Can be larger than the size.",
9163        ),
9164        (
9165            "allocations",
9166            "The number of separate memory allocations backing the arrangement.",
9167        ),
9168    ]),
9169    sql: "
9170SELECT
9171    operator_id,
9172    SUM(records)::int8 AS records,
9173    SUM(batches)::int8 AS batches,
9174    SUM(size)::int8 AS size,
9175    SUM(capacity)::int8 AS capacity,
9176    SUM(allocations)::int8 AS allocations
9177FROM mz_introspection.mz_arrangement_sizes_per_worker
9178GROUP BY operator_id",
9179    access: vec![PUBLIC_SELECT],
9180});
9181
9182pub static MZ_ARRANGEMENT_SHARING_PER_WORKER: LazyLock<BuiltinView> =
9183    LazyLock::new(|| BuiltinView {
9184        name: "mz_arrangement_sharing_per_worker",
9185        schema: MZ_INTROSPECTION_SCHEMA,
9186        oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_PER_WORKER_OID,
9187        desc: RelationDesc::builder()
9188            .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9189            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
9190            .with_column("count", SqlScalarType::Int64.nullable(false))
9191            .with_key(vec![0, 1])
9192            .finish(),
9193        column_comments: BTreeMap::new(),
9194        sql: "
9195SELECT
9196    operator_id,
9197    worker_id,
9198    pg_catalog.count(*) AS count
9199FROM mz_introspection.mz_arrangement_sharing_raw
9200GROUP BY operator_id, worker_id",
9201        access: vec![PUBLIC_SELECT],
9202    });
9203
9204pub static MZ_ARRANGEMENT_SHARING: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9205    name: "mz_arrangement_sharing",
9206    schema: MZ_INTROSPECTION_SCHEMA,
9207    oid: oid::VIEW_MZ_ARRANGEMENT_SHARING_OID,
9208    desc: RelationDesc::builder()
9209        .with_column("operator_id", SqlScalarType::UInt64.nullable(false))
9210        .with_column("count", SqlScalarType::Int64.nullable(false))
9211        .with_key(vec![0])
9212        .finish(),
9213    column_comments: BTreeMap::from_iter([
9214        (
9215            "operator_id",
9216            "The ID of the operator that created the arrangement. Corresponds to `mz_dataflow_operators.id`.",
9217        ),
9218        (
9219            "count",
9220            "The number of operators that share the arrangement.",
9221        ),
9222    ]),
9223    sql: "
9224SELECT operator_id, count
9225FROM mz_introspection.mz_arrangement_sharing_per_worker
9226WHERE worker_id = 0::uint8",
9227    access: vec![PUBLIC_SELECT],
9228});
9229
9230pub static MZ_CLUSTER_REPLICA_UTILIZATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9231    name: "mz_cluster_replica_utilization",
9232    schema: MZ_INTERNAL_SCHEMA,
9233    oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_OID,
9234    desc: RelationDesc::builder()
9235        .with_column("replica_id", SqlScalarType::String.nullable(false))
9236        .with_column("process_id", SqlScalarType::UInt64.nullable(false))
9237        .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
9238        .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
9239        .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
9240        .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
9241        .finish(),
9242    column_comments: BTreeMap::from_iter([
9243        ("replica_id", "The ID of a cluster replica."),
9244        ("process_id", "The ID of a process within the replica."),
9245        (
9246            "cpu_percent",
9247            "Approximate CPU usage, in percent of the total allocation.",
9248        ),
9249        (
9250            "memory_percent",
9251            "Approximate RAM usage, in percent of the total allocation.",
9252        ),
9253        (
9254            "disk_percent",
9255            "Approximate disk usage, in percent of the total allocation.",
9256        ),
9257        (
9258            "heap_percent",
9259            "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
9260        ),
9261    ]),
9262    sql: "
9263SELECT
9264    r.id AS replica_id,
9265    m.process_id,
9266    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
9267    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
9268    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
9269    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent
9270FROM
9271    mz_catalog.mz_cluster_replicas AS r
9272        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
9273        JOIN mz_internal.mz_cluster_replica_metrics AS m ON m.replica_id = r.id",
9274    access: vec![PUBLIC_SELECT],
9275});
9276
9277pub static MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY: LazyLock<BuiltinView> =
9278    LazyLock::new(|| BuiltinView {
9279        name: "mz_cluster_replica_utilization_history",
9280        schema: MZ_INTERNAL_SCHEMA,
9281        oid: oid::VIEW_MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY_OID,
9282        desc: RelationDesc::builder()
9283            .with_column("replica_id", SqlScalarType::String.nullable(false))
9284            .with_column("process_id", SqlScalarType::UInt64.nullable(false))
9285            .with_column("cpu_percent", SqlScalarType::Float64.nullable(true))
9286            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
9287            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
9288            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
9289            .with_column(
9290                "occurred_at",
9291                SqlScalarType::TimestampTz { precision: None }.nullable(false),
9292            )
9293            .finish(),
9294        column_comments: BTreeMap::from_iter([
9295            ("replica_id", "The ID of a cluster replica."),
9296            ("process_id", "The ID of a process within the replica."),
9297            (
9298                "cpu_percent",
9299                "Approximate CPU usage, in percent of the total allocation.",
9300            ),
9301            (
9302                "memory_percent",
9303                "Approximate RAM usage, in percent of the total allocation.",
9304            ),
9305            (
9306                "disk_percent",
9307                "Approximate disk usage, in percent of the total allocation.",
9308            ),
9309            (
9310                "heap_percent",
9311                "Approximate heap (RAM + swap) usage, in percent of the total allocation.",
9312            ),
9313            (
9314                "occurred_at",
9315                "Wall-clock timestamp at which the event occurred.",
9316            ),
9317        ]),
9318        sql: "
9319SELECT
9320    r.id AS replica_id,
9321    m.process_id,
9322    m.cpu_nano_cores::float8 / NULLIF(s.cpu_nano_cores, 0) * 100 AS cpu_percent,
9323    m.memory_bytes::float8 / NULLIF(s.memory_bytes, 0) * 100 AS memory_percent,
9324    m.disk_bytes::float8 / NULLIF(s.disk_bytes, 0) * 100 AS disk_percent,
9325    m.heap_bytes::float8 / NULLIF(m.heap_limit, 0) * 100 AS heap_percent,
9326    m.occurred_at
9327FROM
9328    mz_catalog.mz_cluster_replicas AS r
9329        JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
9330        JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.id",
9331        access: vec![PUBLIC_SELECT],
9332    });
9333
9334pub static MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER: LazyLock<BuiltinView> =
9335    LazyLock::new(|| BuiltinView {
9336        name: "mz_dataflow_operator_parents_per_worker",
9337        schema: MZ_INTROSPECTION_SCHEMA,
9338        oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER_OID,
9339        desc: RelationDesc::builder()
9340            .with_column("id", SqlScalarType::UInt64.nullable(false))
9341            .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9342            .with_column("worker_id", SqlScalarType::UInt64.nullable(false))
9343            .finish(),
9344        column_comments: BTreeMap::new(),
9345        sql: "
9346WITH operator_addrs AS(
9347    SELECT
9348        id, address, worker_id
9349    FROM mz_introspection.mz_dataflow_addresses_per_worker
9350        INNER JOIN mz_introspection.mz_dataflow_operators_per_worker
9351            USING (id, worker_id)
9352),
9353parent_addrs AS (
9354    SELECT
9355        id,
9356        address[1:list_length(address) - 1] AS parent_address,
9357        worker_id
9358    FROM operator_addrs
9359)
9360SELECT pa.id, oa.id AS parent_id, pa.worker_id
9361FROM parent_addrs AS pa
9362    INNER JOIN operator_addrs AS oa
9363        ON pa.parent_address = oa.address
9364        AND pa.worker_id = oa.worker_id",
9365        access: vec![PUBLIC_SELECT],
9366    });
9367
9368pub static MZ_DATAFLOW_OPERATOR_PARENTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9369    name: "mz_dataflow_operator_parents",
9370    schema: MZ_INTROSPECTION_SCHEMA,
9371    oid: oid::VIEW_MZ_DATAFLOW_OPERATOR_PARENTS_OID,
9372    desc: RelationDesc::builder()
9373        .with_column("id", SqlScalarType::UInt64.nullable(false))
9374        .with_column("parent_id", SqlScalarType::UInt64.nullable(false))
9375        .finish(),
9376    column_comments: BTreeMap::from_iter([
9377        (
9378            "id",
9379            "The ID of the operator. Corresponds to `mz_dataflow_operators.id`.",
9380        ),
9381        (
9382            "parent_id",
9383            "The ID of the operator's parent operator. Corresponds to `mz_dataflow_operators.id`.",
9384        ),
9385    ]),
9386    sql: "
9387SELECT id, parent_id
9388FROM mz_introspection.mz_dataflow_operator_parents_per_worker
9389WHERE worker_id = 0::uint8",
9390    access: vec![PUBLIC_SELECT],
9391});
9392
9393pub static MZ_DATAFLOW_ARRANGEMENT_SIZES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9394    name: "mz_dataflow_arrangement_sizes",
9395    schema: MZ_INTROSPECTION_SCHEMA,
9396    oid: oid::VIEW_MZ_DATAFLOW_ARRANGEMENT_SIZES_OID,
9397    desc: RelationDesc::builder()
9398        .with_column("id", SqlScalarType::UInt64.nullable(false))
9399        .with_column("name", SqlScalarType::String.nullable(false))
9400        .with_column("records", SqlScalarType::Int64.nullable(true))
9401        .with_column("batches", SqlScalarType::Int64.nullable(true))
9402        .with_column("size", SqlScalarType::Int64.nullable(true))
9403        .with_column("capacity", SqlScalarType::Int64.nullable(true))
9404        .with_column("allocations", SqlScalarType::Int64.nullable(true))
9405        .with_key(vec![0, 1])
9406        .finish(),
9407    column_comments: BTreeMap::from_iter([
9408        (
9409            "id",
9410            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9411        ),
9412        ("name", "The name of the [dataflow]."),
9413        (
9414            "records",
9415            "The number of records in all arrangements in the dataflow.",
9416        ),
9417        (
9418            "batches",
9419            "The number of batches in all arrangements in the dataflow.",
9420        ),
9421        ("size", "The utilized size in bytes of the arrangements."),
9422        (
9423            "capacity",
9424            "The capacity in bytes of the arrangements. Can be larger than the size.",
9425        ),
9426        (
9427            "allocations",
9428            "The number of separate memory allocations backing the arrangements.",
9429        ),
9430    ]),
9431    sql: "
9432SELECT
9433    mdod.dataflow_id AS id,
9434    mdod.dataflow_name AS name,
9435    SUM(mas.records)::int8 AS records,
9436    SUM(mas.batches)::int8 AS batches,
9437    SUM(mas.size)::int8 AS size,
9438    SUM(mas.capacity)::int8 AS capacity,
9439    SUM(mas.allocations)::int8 AS allocations
9440FROM mz_introspection.mz_dataflow_operator_dataflows AS mdod
9441LEFT JOIN mz_introspection.mz_arrangement_sizes AS mas
9442    ON mdod.id = mas.operator_id
9443GROUP BY mdod.dataflow_id, mdod.dataflow_name",
9444    access: vec![PUBLIC_SELECT],
9445});
9446
9447pub static MZ_EXPECTED_GROUP_SIZE_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9448    name: "mz_expected_group_size_advice",
9449    schema: MZ_INTROSPECTION_SCHEMA,
9450    oid: oid::VIEW_MZ_EXPECTED_GROUP_SIZE_ADVICE_OID,
9451    desc: RelationDesc::builder()
9452        .with_column("dataflow_id", SqlScalarType::UInt64.nullable(false))
9453        .with_column("dataflow_name", SqlScalarType::String.nullable(false))
9454        .with_column("region_id", SqlScalarType::UInt64.nullable(false))
9455        .with_column("region_name", SqlScalarType::String.nullable(false))
9456        .with_column("levels", SqlScalarType::Int64.nullable(false))
9457        .with_column("to_cut", SqlScalarType::Int64.nullable(false))
9458        .with_column(
9459            "savings",
9460            SqlScalarType::Numeric {
9461                max_scale: Some(NumericMaxScale::ZERO),
9462            }
9463            .nullable(true),
9464        )
9465        .with_column("hint", SqlScalarType::Float64.nullable(false))
9466        .finish(),
9467    column_comments: BTreeMap::from_iter([
9468        (
9469            "dataflow_id",
9470            "The ID of the [dataflow]. Corresponds to `mz_dataflows.id`.",
9471        ),
9472        (
9473            "dataflow_name",
9474            "The internal name of the dataflow hosting the min/max aggregation or Top K.",
9475        ),
9476        (
9477            "region_id",
9478            "The ID of the root operator scope. Corresponds to `mz_dataflow_operators.id`.",
9479        ),
9480        (
9481            "region_name",
9482            "The internal name of the root operator scope for the min/max aggregation or Top K.",
9483        ),
9484        (
9485            "levels",
9486            "The number of levels in the hierarchical scheme implemented by the region.",
9487        ),
9488        (
9489            "to_cut",
9490            "The number of levels that can be eliminated (cut) from the region's hierarchy.",
9491        ),
9492        (
9493            "savings",
9494            "A conservative estimate of the amount of memory in bytes to be saved by applying the hint.",
9495        ),
9496        (
9497            "hint",
9498            "The hint value that will eliminate `to_cut` levels from the region's hierarchy.",
9499        ),
9500    ]),
9501    sql: "
9502        -- The mz_expected_group_size_advice view provides tuning suggestions for the GROUP SIZE
9503        -- query hints. This tuning hint is effective for min/max/top-k patterns, where a stack
9504        -- of arrangements must be built. For each dataflow and region corresponding to one
9505        -- such pattern, we look for how many levels can be eliminated without hitting a level
9506        -- that actually substantially filters the input. The advice is constructed so that
9507        -- setting the hint for the affected region will eliminate these redundant levels of
9508        -- the hierarchical rendering.
9509        --
9510        -- A number of helper CTEs are used for the view definition. The first one, operators,
9511        -- looks for operator names that comprise arrangements of inputs to each level of a
9512        -- min/max/top-k hierarchy.
9513        WITH operators AS (
9514            SELECT
9515                dod.dataflow_id,
9516                dor.id AS region_id,
9517                dod.id,
9518                ars.records,
9519                ars.size
9520            FROM
9521                mz_introspection.mz_dataflow_operator_dataflows dod
9522                JOIN mz_introspection.mz_dataflow_addresses doa
9523                    ON dod.id = doa.id
9524                JOIN mz_introspection.mz_dataflow_addresses dra
9525                    ON dra.address = doa.address[:list_length(doa.address) - 1]
9526                JOIN mz_introspection.mz_dataflow_operators dor
9527                    ON dor.id = dra.id
9528                JOIN mz_introspection.mz_arrangement_sizes ars
9529                    ON ars.operator_id = dod.id
9530            WHERE
9531                dod.name = 'Arranged TopK input'
9532                OR dod.name = 'Arranged MinsMaxesHierarchical input'
9533                OR dod.name = 'Arrange ReduceMinsMaxes'
9534            ),
9535        -- The second CTE, levels, simply computes the heights of the min/max/top-k hierarchies
9536        -- identified in operators above.
9537        levels AS (
9538            SELECT o.dataflow_id, o.region_id, COUNT(*) AS levels
9539            FROM operators o
9540            GROUP BY o.dataflow_id, o.region_id
9541        ),
9542        -- The third CTE, pivot, determines for each min/max/top-k hierarchy, the first input
9543        -- operator. This operator is crucially important, as it records the number of records
9544        -- that was given as input to the gadget as a whole.
9545        pivot AS (
9546            SELECT
9547                o1.dataflow_id,
9548                o1.region_id,
9549                o1.id,
9550                o1.records
9551            FROM operators o1
9552            WHERE
9553                o1.id = (
9554                    SELECT MIN(o2.id)
9555                    FROM operators o2
9556                    WHERE
9557                        o2.dataflow_id = o1.dataflow_id
9558                        AND o2.region_id = o1.region_id
9559                    OPTIONS (AGGREGATE INPUT GROUP SIZE = 8)
9560                )
9561        ),
9562        -- The fourth CTE, candidates, will look for operators where the number of records
9563        -- maintained is not significantly different from the number at the pivot (excluding
9564        -- the pivot itself). These are the candidates for being cut from the dataflow region
9565        -- by adjusting the hint. The query includes a constant, heuristically tuned on TPC-H
9566        -- load generator data, to give some room for small deviations in number of records.
9567        -- The intuition for allowing for this deviation is that we are looking for a strongly
9568        -- reducing point in the hierarchy. To see why one such operator ought to exist in an
9569        -- untuned hierarchy, consider that at each level, we use hashing to distribute rows
9570        -- among groups where the min/max/top-k computation is (partially) applied. If the
9571        -- hierarchy has too many levels, the first-level (pivot) groups will be such that many
9572        -- groups might be empty or contain only one row. Each subsequent level will have a number
9573        -- of groups that is reduced exponentially. So at some point, we will find the level where
9574        -- we actually start having a few rows per group. That's where we will see the row counts
9575        -- significantly drop off.
9576        candidates AS (
9577            SELECT
9578                o.dataflow_id,
9579                o.region_id,
9580                o.id,
9581                o.records,
9582                o.size
9583            FROM
9584                operators o
9585                JOIN pivot p
9586                    ON o.dataflow_id = p.dataflow_id
9587                        AND o.region_id = p.region_id
9588                        AND o.id <> p.id
9589            WHERE o.records >= p.records * (1 - 0.15)
9590        ),
9591        -- The fifth CTE, cuts, computes for each relevant dataflow region, the number of
9592        -- candidate levels that should be cut. We only return here dataflow regions where at
9593        -- least one level must be cut. Note that once we hit a point where the hierarchy starts
9594        -- to have a filtering effect, i.e., after the last candidate, it is dangerous to suggest
9595        -- cutting the height of the hierarchy further. This is because we will have way less
9596        -- groups in the next level, so there should be even further reduction happening or there
9597        -- is some substantial skew in the data. But if the latter is the case, then we should not
9598        -- tune the GROUP SIZE hints down anyway to avoid hurting latency upon updates directed
9599        -- at these unusually large groups. In addition to selecting the levels to cut, we also
9600        -- compute a conservative estimate of the memory savings in bytes that will result from
9601        -- cutting these levels from the hierarchy. The estimate is based on the sizes of the
9602        -- input arrangements for each level to be cut. These arrangements should dominate the
9603        -- size of each level that can be cut, since the reduction gadget internal to the level
9604        -- does not remove much data at these levels.
9605        cuts AS (
9606            SELECT c.dataflow_id, c.region_id, COUNT(*) AS to_cut, SUM(c.size) AS savings
9607            FROM candidates c
9608            GROUP BY c.dataflow_id, c.region_id
9609            HAVING COUNT(*) > 0
9610        )
9611        -- Finally, we compute the hint suggestion for each dataflow region based on the number of
9612        -- levels and the number of candidates to be cut. The hint is computed taking into account
9613        -- the fan-in used in rendering for the hash partitioning and reduction of the groups,
9614        -- currently equal to 16.
9615        SELECT
9616            dod.dataflow_id,
9617            dod.dataflow_name,
9618            dod.id AS region_id,
9619            dod.name AS region_name,
9620            l.levels,
9621            c.to_cut,
9622            c.savings,
9623            pow(16, l.levels - c.to_cut) - 1 AS hint
9624        FROM cuts c
9625            JOIN levels l
9626                ON c.dataflow_id = l.dataflow_id AND c.region_id = l.region_id
9627            JOIN mz_introspection.mz_dataflow_operator_dataflows dod
9628                ON dod.dataflow_id = c.dataflow_id AND dod.id = c.region_id",
9629    access: vec![PUBLIC_SELECT],
9630});
9631
9632pub static MZ_INDEX_ADVICE: LazyLock<BuiltinView> = LazyLock::new(|| {
9633    BuiltinView {
9634        name: "mz_index_advice",
9635        schema: MZ_INTERNAL_SCHEMA,
9636        oid: oid::VIEW_MZ_INDEX_ADVICE_OID,
9637        desc: RelationDesc::builder()
9638            .with_column("object_id", SqlScalarType::String.nullable(true))
9639            .with_column("hint", SqlScalarType::String.nullable(false))
9640            .with_column("details", SqlScalarType::String.nullable(false))
9641            .with_column("referenced_object_ids", SqlScalarType::List { element_type: Box::new(SqlScalarType::String), custom_id: None }.nullable(true))
9642            .finish(),
9643        column_comments: BTreeMap::from_iter([
9644            ("object_id", "The ID of the object. Corresponds to mz_objects.id."),
9645            ("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."),
9646            ("details", "Additional details on why the `hint` was proposed based on the dependencies of the object."),
9647            ("referenced_object_ids", "The IDs of objects referenced by `details`. Corresponds to mz_objects.id."),
9648        ]),
9649        sql: "
9650-- To avoid confusion with sources and sinks in the materialize sense,
9651-- the following uses the terms leafs (instead of sinks) and roots (instead of sources)
9652-- when referring to the object dependency graph.
9653--
9654-- The basic idea is to walk up the dependency graph to propagate the transitive dependencies
9655-- of maintained objected upwards. The leaves of the dependency graph are maintained objects
9656-- that are not depended on by other maintained objects and have a justification why they must
9657-- be maintained (e.g. a materialized view that is depended on by a sink).
9658-- Starting from these leaves, the dependencies are propagated upwards towards the roots according
9659-- to the object dependencies. Whenever there is a node that is being depended on by multiple
9660-- downstream objects, that node is marked to be converted into a maintained object and this
9661-- node is then propagated further up. Once completed, the list of objects that are marked as
9662-- maintained is checked against all objects to generate appropriate recommendations.
9663--
9664-- Note that the recommendations only incorporate dependencies between objects.
9665-- This can lead to bad recommendations, e.g. filters can no longer be pushed into (or close to)
9666-- a sink if an index is added in between the sink and the filter. For very selective filters,
9667-- this can lead to redundant work: the index is computing stuff only to discarded by the selective
9668-- filter later on. But these kind of aspects cannot be understood by merely looking at the
9669-- dependencies.
9670WITH MUTUALLY RECURSIVE
9671    -- for all objects, understand if they have an index on them and on which cluster they are running
9672    -- this avoids having different cases for views with an index and materialized views later on
9673    objects(id text, type text, cluster_id text, indexes text list) AS (
9674        -- views and materialized views without an index
9675        SELECT
9676            o.id,
9677            o.type,
9678            o.cluster_id,
9679            '{}'::text list AS indexes
9680        FROM mz_catalog.mz_objects o
9681        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view') AND NOT EXISTS (
9682            SELECT FROM mz_internal.mz_object_dependencies d
9683            JOIN mz_catalog.mz_objects AS i
9684                ON (i.id = d.object_id AND i.type = 'index')
9685            WHERE (o.id = d.referenced_object_id)
9686        )
9687
9688        UNION ALL
9689
9690        -- views and materialized views with an index
9691        SELECT
9692            o.id,
9693            o.type,
9694            -- o.cluster_id is always NULL for views, so use the cluster of the index instead
9695            COALESCE(o.cluster_id, i.cluster_id) AS cluster_id,
9696            list_agg(i.id) AS indexes
9697        FROM mz_catalog.mz_objects o
9698        JOIN mz_internal.mz_object_dependencies AS d
9699            ON (o.id = d.referenced_object_id)
9700        JOIN mz_catalog.mz_objects AS i
9701            ON (i.id = d.object_id AND i.type = 'index')
9702        WHERE o.id LIKE 'u%' AND o.type IN ('materialized-view', 'view', 'source')
9703        GROUP BY o.id, o.type, o.cluster_id, i.cluster_id
9704    ),
9705
9706    -- maintained objects that are at the leafs of the dependency graph with respect to a specific cluster
9707    maintained_leafs(id text, justification text) AS (
9708        -- materialized views that are connected to a sink
9709        SELECT
9710            m.id,
9711            s.id AS justification
9712        FROM objects AS m
9713        JOIN mz_internal.mz_object_dependencies AS d
9714            ON (m.id = d.referenced_object_id)
9715        JOIN mz_catalog.mz_objects AS s
9716            ON (s.id = d.object_id AND s.type = 'sink')
9717        WHERE m.type = 'materialized-view'
9718
9719        UNION ALL
9720
9721        -- (materialized) views with an index that are not transitively depend on by maintained objects on the same cluster
9722        SELECT
9723            v.id,
9724            unnest(v.indexes) AS justification
9725        FROM objects AS v
9726        WHERE v.type IN ('view', 'materialized-view', 'source') AND NOT EXISTS (
9727            SELECT FROM mz_internal.mz_object_transitive_dependencies AS d
9728            INNER JOIN mz_catalog.mz_objects AS child
9729                ON (d.object_id = child.id)
9730            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]
9731        )
9732    ),
9733
9734    -- this is just a helper cte to union multiple lists as part of an aggregation, which is not directly possible in SQL
9735    agg_maintained_children(id text, maintained_children text list) AS (
9736        SELECT
9737            parent_id AS id,
9738            list_agg(maintained_child) AS maintained_leafs
9739        FROM (
9740            SELECT DISTINCT
9741                d.referenced_object_id AS parent_id,
9742                -- it's not possible to union lists in an aggregation, so we have to unnest the list first
9743                unnest(child.maintained_children) AS maintained_child
9744            FROM propagate_dependencies AS child
9745            INNER JOIN mz_internal.mz_object_dependencies AS d
9746                ON (child.id = d.object_id)
9747        )
9748        GROUP BY parent_id
9749    ),
9750
9751    -- propagate dependencies of maintained objects from the leafs to the roots of the dependency graph and
9752    -- record a justification when an object should be maintained, e.g. when it is depended on by more than one maintained object
9753    -- 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
9754    propagate_dependencies(id text, maintained_children text list, justification text list) AS (
9755        -- base case: start with the leafs
9756        SELECT DISTINCT
9757            id,
9758            LIST[id] AS maintained_children,
9759            list_agg(justification) AS justification
9760        FROM maintained_leafs
9761        GROUP BY id
9762
9763        UNION
9764
9765        -- recursive case: if there is a child with the same dependencies as the parent,
9766        -- the parent is only reused by a single child
9767        SELECT
9768            parent.id,
9769            child.maintained_children,
9770            NULL::text list AS justification
9771        FROM agg_maintained_children AS parent
9772        INNER JOIN mz_internal.mz_object_dependencies AS d
9773            ON (parent.id = d.referenced_object_id)
9774        INNER JOIN propagate_dependencies AS child
9775            ON (d.object_id = child.id)
9776        WHERE parent.maintained_children = child.maintained_children
9777
9778        UNION
9779
9780        -- recursive case: if there is NO child with the same dependencies as the parent,
9781        -- different children are reusing the parent so maintaining the object is justified by itself
9782        SELECT DISTINCT
9783            parent.id,
9784            LIST[parent.id] AS maintained_children,
9785            parent.maintained_children AS justification
9786        FROM agg_maintained_children AS parent
9787        WHERE NOT EXISTS (
9788            SELECT FROM mz_internal.mz_object_dependencies AS d
9789            INNER JOIN propagate_dependencies AS child
9790                ON (d.object_id = child.id AND d.referenced_object_id = parent.id)
9791            WHERE parent.maintained_children = child.maintained_children
9792        )
9793    ),
9794
9795    objects_with_justification(id text, type text, cluster_id text, maintained_children text list, justification text list, indexes text list) AS (
9796        SELECT
9797            p.id,
9798            o.type,
9799            o.cluster_id,
9800            p.maintained_children,
9801            p.justification,
9802            o.indexes
9803        FROM propagate_dependencies p
9804        JOIN objects AS o
9805            ON (p.id = o.id)
9806    ),
9807
9808    hints(id text, hint text, details text, justification text list) AS (
9809        -- materialized views that are not required
9810        SELECT
9811            id,
9812            'convert to a view' AS hint,
9813            'no dependencies from sinks nor from objects on different clusters' AS details,
9814            justification
9815        FROM objects_with_justification
9816        WHERE type = 'materialized-view' AND justification IS NULL
9817
9818        UNION ALL
9819
9820        -- materialized views that are required because a sink or a maintained object from a different cluster depends on them
9821        SELECT
9822            id,
9823            'keep' AS hint,
9824            'dependencies from sinks or objects on different clusters: ' AS details,
9825            justification
9826        FROM objects_with_justification AS m
9827        WHERE type = 'materialized-view' AND justification IS NOT NULL AND EXISTS (
9828            SELECT FROM unnest(justification) AS dependency
9829            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9830
9831            UNION ALL
9832
9833            SELECT FROM unnest(justification) AS dependency
9834            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9835            WHERE d.cluster_id != m.cluster_id
9836        )
9837
9838        UNION ALL
9839
9840        -- 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
9841        SELECT
9842            id,
9843            'convert to a view with an index' AS hint,
9844            'no dependencies from sinks nor from objects on different clusters, but maintained dependencies on the same cluster: ' AS details,
9845            justification
9846        FROM objects_with_justification AS m
9847        WHERE type = 'materialized-view' AND justification IS NOT NULL AND NOT EXISTS (
9848            SELECT FROM unnest(justification) AS dependency
9849            JOIN mz_catalog.mz_objects s ON (s.type = 'sink' AND s.id = dependency)
9850
9851            UNION ALL
9852
9853            SELECT FROM unnest(justification) AS dependency
9854            JOIN mz_catalog.mz_objects AS d ON (d.id = dependency)
9855            WHERE d.cluster_id != m.cluster_id
9856        )
9857
9858        UNION ALL
9859
9860        -- views that have indexes on different clusters should be a materialized view
9861        SELECT
9862            o.id,
9863            'convert to materialized view' AS hint,
9864            'dependencies on multiple clusters: ' AS details,
9865            o.justification
9866        FROM objects_with_justification o,
9867            LATERAL unnest(o.justification) j
9868        LEFT JOIN mz_catalog.mz_objects AS m
9869            ON (m.id = j AND m.type IN ('index', 'materialized-view'))
9870        WHERE o.type = 'view' AND o.justification IS NOT NULL
9871        GROUP BY o.id, o.justification
9872        HAVING count(DISTINCT m.cluster_id) >= 2
9873
9874        UNION ALL
9875
9876        -- views without an index that should be maintained
9877        SELECT
9878            id,
9879            'add index' AS hint,
9880            'multiple downstream dependencies: ' AS details,
9881            justification
9882        FROM objects_with_justification
9883        WHERE type = 'view' AND justification IS NOT NULL AND indexes = '{}'::text list
9884
9885        UNION ALL
9886
9887        -- index inside the dependency graph (not a leaf)
9888        SELECT
9889            unnest(indexes) AS id,
9890            'drop unless queried directly' AS hint,
9891            'fewer than two downstream dependencies: ' AS details,
9892            maintained_children AS justification
9893        FROM objects_with_justification
9894        WHERE type = 'view' AND NOT indexes = '{}'::text list AND justification IS NULL
9895
9896        UNION ALL
9897
9898        -- index on a leaf of the dependency graph
9899        SELECT
9900            unnest(indexes) AS id,
9901            'drop unless queried directly' AS hint,
9902            'associated object does not have any dependencies (maintained or not maintained)' AS details,
9903            NULL::text list AS justification
9904        FROM objects_with_justification
9905        -- indexes can only be part of justification for leaf nodes
9906        WHERE type IN ('view', 'materialized-view') AND NOT indexes = '{}'::text list AND justification @> indexes
9907
9908        UNION ALL
9909
9910        -- index on a source
9911        SELECT
9912            unnest(indexes) AS id,
9913            'drop unless queried directly' AS hint,
9914            'sources do not transform data and can expose data directly' AS details,
9915            NULL::text list AS justification
9916        FROM objects_with_justification
9917        -- indexes can only be part of justification for leaf nodes
9918        WHERE type = 'source' AND NOT indexes = '{}'::text list
9919
9920        UNION ALL
9921
9922        -- indexes on views inside the dependency graph
9923        SELECT
9924            unnest(indexes) AS id,
9925            'keep' AS hint,
9926            'multiple downstream dependencies: ' AS details,
9927            justification
9928        FROM objects_with_justification
9929        -- indexes can only be part of justification for leaf nodes
9930        WHERE type = 'view' AND justification IS NOT NULL AND NOT indexes = '{}'::text list AND NOT justification @> indexes
9931    ),
9932
9933    hints_resolved_ids(id text, hint text, details text, justification text list) AS (
9934        SELECT
9935            h.id,
9936            h.hint,
9937            h.details || list_agg(o.name)::text AS details,
9938            h.justification
9939        FROM hints AS h,
9940            LATERAL unnest(h.justification) j
9941        JOIN mz_catalog.mz_objects AS o
9942            ON (o.id = j)
9943        GROUP BY h.id, h.hint, h.details, h.justification
9944
9945        UNION ALL
9946
9947        SELECT
9948            id,
9949            hint,
9950            details,
9951            justification
9952        FROM hints
9953        WHERE justification IS NULL
9954    )
9955
9956SELECT
9957    h.id AS object_id,
9958    h.hint AS hint,
9959    h.details,
9960    h.justification AS referenced_object_ids
9961FROM hints_resolved_ids AS h",
9962        access: vec![PUBLIC_SELECT],
9963    }
9964});
9965
9966// NOTE: If you add real data to this implementation, then please update
9967// the related `pg_` function implementations (like `pg_get_constraintdef`)
9968pub static PG_CONSTRAINT: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
9969    name: "pg_constraint",
9970    schema: PG_CATALOG_SCHEMA,
9971    oid: oid::VIEW_PG_CONSTRAINT_OID,
9972    desc: RelationDesc::builder()
9973        .with_column("oid", SqlScalarType::Oid.nullable(false))
9974        .with_column("conname", SqlScalarType::String.nullable(false))
9975        .with_column("connamespace", SqlScalarType::Oid.nullable(false))
9976        .with_column("contype", SqlScalarType::PgLegacyChar.nullable(false))
9977        .with_column("condeferrable", SqlScalarType::Bool.nullable(false))
9978        .with_column("condeferred", SqlScalarType::Bool.nullable(false))
9979        .with_column("convalidated", SqlScalarType::Bool.nullable(false))
9980        .with_column("conrelid", SqlScalarType::Oid.nullable(false))
9981        .with_column("contypid", SqlScalarType::Oid.nullable(false))
9982        .with_column("conindid", SqlScalarType::Oid.nullable(false))
9983        .with_column("conparentid", SqlScalarType::Oid.nullable(false))
9984        .with_column("confrelid", SqlScalarType::Oid.nullable(false))
9985        .with_column("confupdtype", SqlScalarType::PgLegacyChar.nullable(false))
9986        .with_column("confdeltype", SqlScalarType::PgLegacyChar.nullable(false))
9987        .with_column("confmatchtype", SqlScalarType::PgLegacyChar.nullable(false))
9988        .with_column("conislocal", SqlScalarType::Bool.nullable(false))
9989        .with_column("coninhcount", SqlScalarType::Int32.nullable(false))
9990        .with_column("connoinherit", SqlScalarType::Bool.nullable(false))
9991        .with_column(
9992            "conkey",
9993            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9994        )
9995        .with_column(
9996            "confkey",
9997            SqlScalarType::Array(Box::new(SqlScalarType::Int16)).nullable(false),
9998        )
9999        .with_column(
10000            "conpfeqop",
10001            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10002        )
10003        .with_column(
10004            "conppeqop",
10005            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10006        )
10007        .with_column(
10008            "conffeqop",
10009            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10010        )
10011        .with_column(
10012            "conexclop",
10013            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10014        )
10015        .with_column("conbin", SqlScalarType::String.nullable(false))
10016        .with_key(vec![])
10017        .finish(),
10018    column_comments: BTreeMap::new(),
10019    sql: "SELECT
10020    NULL::pg_catalog.oid as oid,
10021    NULL::pg_catalog.text as conname,
10022    NULL::pg_catalog.oid as connamespace,
10023    NULL::pg_catalog.\"char\" as contype,
10024    NULL::pg_catalog.bool as condeferrable,
10025    NULL::pg_catalog.bool as condeferred,
10026    NULL::pg_catalog.bool as convalidated,
10027    NULL::pg_catalog.oid as conrelid,
10028    NULL::pg_catalog.oid as contypid,
10029    NULL::pg_catalog.oid as conindid,
10030    NULL::pg_catalog.oid as conparentid,
10031    NULL::pg_catalog.oid as confrelid,
10032    NULL::pg_catalog.\"char\" as confupdtype,
10033    NULL::pg_catalog.\"char\" as confdeltype,
10034    NULL::pg_catalog.\"char\" as confmatchtype,
10035    NULL::pg_catalog.bool as conislocal,
10036    NULL::pg_catalog.int4 as coninhcount,
10037    NULL::pg_catalog.bool as connoinherit,
10038    NULL::pg_catalog.int2[] as conkey,
10039    NULL::pg_catalog.int2[] as confkey,
10040    NULL::pg_catalog.oid[] as conpfeqop,
10041    NULL::pg_catalog.oid[] as conppeqop,
10042    NULL::pg_catalog.oid[] as conffeqop,
10043    NULL::pg_catalog.oid[] as conexclop,
10044    NULL::pg_catalog.text as conbin
10045WHERE false",
10046    access: vec![PUBLIC_SELECT],
10047});
10048
10049pub static PG_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10050    name: "pg_tables",
10051    schema: PG_CATALOG_SCHEMA,
10052    oid: oid::VIEW_PG_TABLES_OID,
10053    desc: RelationDesc::builder()
10054        .with_column("schemaname", SqlScalarType::String.nullable(true))
10055        .with_column("tablename", SqlScalarType::String.nullable(false))
10056        .with_column("tableowner", SqlScalarType::String.nullable(false))
10057        .finish(),
10058    column_comments: BTreeMap::new(),
10059    sql: "
10060SELECT n.nspname AS schemaname,
10061    c.relname AS tablename,
10062    pg_catalog.pg_get_userbyid(c.relowner) AS tableowner
10063FROM pg_catalog.pg_class c
10064LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
10065WHERE c.relkind IN ('r', 'p')",
10066    access: vec![PUBLIC_SELECT],
10067});
10068
10069pub static PG_TABLESPACE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10070    name: "pg_tablespace",
10071    schema: PG_CATALOG_SCHEMA,
10072    oid: oid::VIEW_PG_TABLESPACE_OID,
10073    desc: RelationDesc::builder()
10074        .with_column("oid", SqlScalarType::Oid.nullable(false))
10075        .with_column("spcname", SqlScalarType::String.nullable(false))
10076        .with_column("spcowner", SqlScalarType::Oid.nullable(true))
10077        .with_column(
10078            "spcacl",
10079            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
10080        )
10081        .with_column(
10082            "spcoptions",
10083            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
10084        )
10085        .with_key(vec![])
10086        .finish(),
10087    column_comments: BTreeMap::new(),
10088    sql: "
10089    SELECT oid, spcname, spcowner, spcacl, spcoptions
10090    FROM (
10091        VALUES (
10092            --These are the same defaults CockroachDB uses.
10093            0::pg_catalog.oid,
10094            'pg_default'::pg_catalog.text,
10095            NULL::pg_catalog.oid,
10096            NULL::pg_catalog.text[],
10097            NULL::pg_catalog.text[]
10098        )
10099    ) AS _ (oid, spcname, spcowner, spcacl, spcoptions)
10100",
10101    access: vec![PUBLIC_SELECT],
10102});
10103
10104pub static PG_ACCESS_METHODS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10105    name: "pg_am",
10106    schema: PG_CATALOG_SCHEMA,
10107    oid: oid::VIEW_PG_AM_OID,
10108    desc: RelationDesc::builder()
10109        .with_column("oid", SqlScalarType::Oid.nullable(false))
10110        .with_column("amname", SqlScalarType::String.nullable(false))
10111        .with_column("amhandler", SqlScalarType::RegProc.nullable(false))
10112        .with_column("amtype", SqlScalarType::PgLegacyChar.nullable(false))
10113        .with_key(vec![])
10114        .finish(),
10115    column_comments: BTreeMap::new(),
10116    sql: "
10117SELECT NULL::pg_catalog.oid AS oid,
10118    NULL::pg_catalog.text AS amname,
10119    NULL::pg_catalog.regproc AS amhandler,
10120    NULL::pg_catalog.\"char\" AS amtype
10121WHERE false",
10122    access: vec![PUBLIC_SELECT],
10123});
10124
10125pub static PG_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10126    name: "pg_roles",
10127    schema: PG_CATALOG_SCHEMA,
10128    oid: oid::VIEW_PG_ROLES_OID,
10129    desc: RelationDesc::builder()
10130        .with_column("rolname", SqlScalarType::String.nullable(false))
10131        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10132        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10133        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
10134        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
10135        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10136        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10137        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10138        .with_column("rolpassword", SqlScalarType::String.nullable(false))
10139        .with_column(
10140            "rolvaliduntil",
10141            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10142        )
10143        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10144        .with_column(
10145            "rolconfig",
10146            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
10147        )
10148        .with_column("oid", SqlScalarType::Oid.nullable(false))
10149        .finish(),
10150    column_comments: BTreeMap::new(),
10151    sql: "SELECT
10152    rolname,
10153    rolsuper,
10154    rolinherit,
10155    rolcreaterole,
10156    rolcreatedb,
10157    COALESCE(rolcanlogin, false) AS rolcanlogin,
10158    rolreplication,
10159    rolconnlimit,
10160    '********' as rolpassword,
10161    rolvaliduntil,
10162    rolbypassrls,
10163    (
10164        SELECT array_agg(parameter_name || '=' || parameter_value)
10165        FROM mz_catalog.mz_role_parameters rp
10166        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
10167        WHERE ai.oid = r.oid
10168    ) AS rolconfig,
10169    oid
10170FROM pg_catalog.pg_authid ai",
10171    access: vec![PUBLIC_SELECT],
10172});
10173
10174pub static PG_USER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10175    name: "pg_user",
10176    schema: PG_CATALOG_SCHEMA,
10177    oid: oid::VIEW_PG_USER_OID,
10178    desc: RelationDesc::builder()
10179        .with_column("usename", SqlScalarType::String.nullable(false))
10180        .with_column("usesysid", SqlScalarType::Oid.nullable(false))
10181        .with_column("usecreatedb", SqlScalarType::Bool.nullable(true))
10182        .with_column("usesuper", SqlScalarType::Bool.nullable(true))
10183        .with_column("userepl", SqlScalarType::Bool.nullable(false))
10184        .with_column("usebypassrls", SqlScalarType::Bool.nullable(false))
10185        .with_column("passwd", SqlScalarType::String.nullable(true))
10186        .with_column(
10187            "valuntil",
10188            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10189        )
10190        .with_column(
10191            "useconfig",
10192            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(true),
10193        )
10194        .finish(),
10195    column_comments: BTreeMap::new(),
10196    sql: "
10197SELECT
10198    rolname as usename,
10199    ai.oid as usesysid,
10200    rolcreatedb AS usecreatedb,
10201    rolsuper AS usesuper,
10202    rolreplication AS userepl,
10203    rolbypassrls AS usebypassrls,
10204    rolpassword as passwd,
10205    rolvaliduntil as valuntil,
10206    (
10207        SELECT array_agg(parameter_name || '=' || parameter_value)
10208        FROM mz_catalog.mz_role_parameters rp
10209        JOIN mz_catalog.mz_roles r ON r.id = rp.role_id
10210        WHERE ai.oid = r.oid
10211    ) AS useconfig
10212FROM pg_catalog.pg_authid ai
10213WHERE rolcanlogin",
10214    access: vec![PUBLIC_SELECT],
10215});
10216
10217pub static PG_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10218    name: "pg_views",
10219    schema: PG_CATALOG_SCHEMA,
10220    oid: oid::VIEW_PG_VIEWS_OID,
10221    desc: RelationDesc::builder()
10222        .with_column("schemaname", SqlScalarType::String.nullable(true))
10223        .with_column("viewname", SqlScalarType::String.nullable(false))
10224        .with_column("viewowner", SqlScalarType::Oid.nullable(false))
10225        .with_column("definition", SqlScalarType::String.nullable(false))
10226        .finish(),
10227    column_comments: BTreeMap::new(),
10228    sql: "SELECT
10229    s.name AS schemaname,
10230    v.name AS viewname,
10231    role_owner.oid AS viewowner,
10232    v.definition AS definition
10233FROM mz_catalog.mz_views v
10234LEFT JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10235LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10236JOIN mz_catalog.mz_roles role_owner ON role_owner.id = v.owner_id
10237WHERE s.database_id IS NULL OR d.name = current_database()",
10238    access: vec![PUBLIC_SELECT],
10239});
10240
10241pub static PG_MATVIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10242    name: "pg_matviews",
10243    schema: PG_CATALOG_SCHEMA,
10244    oid: oid::VIEW_PG_MATVIEWS_OID,
10245    desc: RelationDesc::builder()
10246        .with_column("schemaname", SqlScalarType::String.nullable(true))
10247        .with_column("matviewname", SqlScalarType::String.nullable(false))
10248        .with_column("matviewowner", SqlScalarType::Oid.nullable(false))
10249        .with_column("definition", SqlScalarType::String.nullable(false))
10250        .finish(),
10251    column_comments: BTreeMap::new(),
10252    sql: "SELECT
10253    s.name AS schemaname,
10254    m.name AS matviewname,
10255    role_owner.oid AS matviewowner,
10256    m.definition AS definition
10257FROM mz_catalog.mz_materialized_views m
10258LEFT JOIN mz_catalog.mz_schemas s ON s.id = m.schema_id
10259LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10260JOIN mz_catalog.mz_roles role_owner ON role_owner.id = m.owner_id
10261WHERE s.database_id IS NULL OR d.name = current_database()",
10262    access: vec![PUBLIC_SELECT],
10263});
10264
10265pub static INFORMATION_SCHEMA_APPLICABLE_ROLES: LazyLock<BuiltinView> =
10266    LazyLock::new(|| BuiltinView {
10267        name: "applicable_roles",
10268        schema: INFORMATION_SCHEMA,
10269        oid: oid::VIEW_APPLICABLE_ROLES_OID,
10270        desc: RelationDesc::builder()
10271            .with_column("grantee", SqlScalarType::String.nullable(false))
10272            .with_column("role_name", SqlScalarType::String.nullable(false))
10273            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10274            .finish(),
10275        column_comments: BTreeMap::new(),
10276        sql: "
10277SELECT
10278    member.name AS grantee,
10279    role.name AS role_name,
10280    -- ADMIN OPTION isn't implemented.
10281    'NO' AS is_grantable
10282FROM mz_catalog.mz_role_members membership
10283JOIN mz_catalog.mz_roles role ON membership.role_id = role.id
10284JOIN mz_catalog.mz_roles member ON membership.member = member.id
10285WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, member.oid, 'USAGE')",
10286        access: vec![PUBLIC_SELECT],
10287    });
10288
10289pub static INFORMATION_SCHEMA_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10290    name: "columns",
10291    schema: INFORMATION_SCHEMA,
10292    oid: oid::VIEW_COLUMNS_OID,
10293    desc: RelationDesc::builder()
10294        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10295        .with_column("table_schema", SqlScalarType::String.nullable(false))
10296        .with_column("table_name", SqlScalarType::String.nullable(false))
10297        .with_column("column_name", SqlScalarType::String.nullable(false))
10298        .with_column("ordinal_position", SqlScalarType::Int64.nullable(false))
10299        .with_column("column_default", SqlScalarType::String.nullable(true))
10300        .with_column("is_nullable", SqlScalarType::String.nullable(false))
10301        .with_column("data_type", SqlScalarType::String.nullable(false))
10302        .with_column(
10303            "character_maximum_length",
10304            SqlScalarType::Int32.nullable(true),
10305        )
10306        .with_column("numeric_precision", SqlScalarType::Int32.nullable(true))
10307        .with_column("numeric_scale", SqlScalarType::Int32.nullable(true))
10308        .finish(),
10309    column_comments: BTreeMap::new(),
10310    sql: "
10311SELECT
10312    current_database() as table_catalog,
10313    s.name AS table_schema,
10314    o.name AS table_name,
10315    c.name AS column_name,
10316    c.position::int8 AS ordinal_position,
10317    c.default AS column_default,
10318    CASE WHEN c.nullable THEN 'YES' ELSE 'NO' END AS is_nullable,
10319    c.type AS data_type,
10320    NULL::pg_catalog.int4 AS character_maximum_length,
10321    NULL::pg_catalog.int4 AS numeric_precision,
10322    NULL::pg_catalog.int4 AS numeric_scale
10323FROM mz_catalog.mz_columns c
10324JOIN mz_catalog.mz_objects o ON o.id = c.id
10325JOIN mz_catalog.mz_schemas s ON s.id = o.schema_id
10326LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10327WHERE s.database_id IS NULL OR d.name = current_database()",
10328    access: vec![PUBLIC_SELECT],
10329});
10330
10331pub static INFORMATION_SCHEMA_ENABLED_ROLES: LazyLock<BuiltinView> =
10332    LazyLock::new(|| BuiltinView {
10333        name: "enabled_roles",
10334        schema: INFORMATION_SCHEMA,
10335        oid: oid::VIEW_ENABLED_ROLES_OID,
10336        desc: RelationDesc::builder()
10337            .with_column("role_name", SqlScalarType::String.nullable(false))
10338            .finish(),
10339        column_comments: BTreeMap::new(),
10340        sql: "
10341SELECT name AS role_name
10342FROM mz_catalog.mz_roles
10343WHERE mz_catalog.mz_is_superuser() OR pg_has_role(current_role, oid, 'USAGE')",
10344        access: vec![PUBLIC_SELECT],
10345    });
10346
10347pub static INFORMATION_SCHEMA_ROLE_TABLE_GRANTS: LazyLock<BuiltinView> = LazyLock::new(|| {
10348    BuiltinView {
10349        name: "role_table_grants",
10350        schema: INFORMATION_SCHEMA,
10351        oid: oid::VIEW_ROLE_TABLE_GRANTS_OID,
10352        desc: RelationDesc::builder()
10353            .with_column("grantor", SqlScalarType::String.nullable(false))
10354            .with_column("grantee", SqlScalarType::String.nullable(true))
10355            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10356            .with_column("table_schema", SqlScalarType::String.nullable(false))
10357            .with_column("table_name", SqlScalarType::String.nullable(false))
10358            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10359            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10360            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10361            .finish(),
10362        column_comments: BTreeMap::new(),
10363        sql: "
10364SELECT grantor, grantee, table_catalog, table_schema, table_name, privilege_type, is_grantable, with_hierarchy
10365FROM information_schema.table_privileges
10366WHERE
10367    grantor IN (SELECT role_name FROM information_schema.enabled_roles)
10368    OR grantee IN (SELECT role_name FROM information_schema.enabled_roles)",
10369        access: vec![PUBLIC_SELECT],
10370    }
10371});
10372
10373pub static INFORMATION_SCHEMA_KEY_COLUMN_USAGE: LazyLock<BuiltinView> =
10374    LazyLock::new(|| BuiltinView {
10375        name: "key_column_usage",
10376        schema: INFORMATION_SCHEMA,
10377        oid: oid::VIEW_KEY_COLUMN_USAGE_OID,
10378        desc: RelationDesc::builder()
10379            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10380            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10381            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10382            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10383            .with_column("table_schema", SqlScalarType::String.nullable(false))
10384            .with_column("table_name", SqlScalarType::String.nullable(false))
10385            .with_column("column_name", SqlScalarType::String.nullable(false))
10386            .with_column("ordinal_position", SqlScalarType::Int32.nullable(false))
10387            .with_column(
10388                "position_in_unique_constraint",
10389                SqlScalarType::Int32.nullable(false),
10390            )
10391            .with_key(vec![])
10392            .finish(),
10393        column_comments: BTreeMap::new(),
10394        sql: "SELECT
10395    NULL::text AS constraint_catalog,
10396    NULL::text AS constraint_schema,
10397    NULL::text AS constraint_name,
10398    NULL::text AS table_catalog,
10399    NULL::text AS table_schema,
10400    NULL::text AS table_name,
10401    NULL::text AS column_name,
10402    NULL::integer AS ordinal_position,
10403    NULL::integer AS position_in_unique_constraint
10404WHERE false",
10405        access: vec![PUBLIC_SELECT],
10406    });
10407
10408pub static INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS: LazyLock<BuiltinView> =
10409    LazyLock::new(|| BuiltinView {
10410        name: "referential_constraints",
10411        schema: INFORMATION_SCHEMA,
10412        oid: oid::VIEW_REFERENTIAL_CONSTRAINTS_OID,
10413        desc: RelationDesc::builder()
10414            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10415            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10416            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10417            .with_column(
10418                "unique_constraint_catalog",
10419                SqlScalarType::String.nullable(false),
10420            )
10421            .with_column(
10422                "unique_constraint_schema",
10423                SqlScalarType::String.nullable(false),
10424            )
10425            .with_column(
10426                "unique_constraint_name",
10427                SqlScalarType::String.nullable(false),
10428            )
10429            .with_column("match_option", SqlScalarType::String.nullable(false))
10430            .with_column("update_rule", SqlScalarType::String.nullable(false))
10431            .with_column("delete_rule", SqlScalarType::String.nullable(false))
10432            .with_key(vec![])
10433            .finish(),
10434        column_comments: BTreeMap::new(),
10435        sql: "SELECT
10436    NULL::text AS constraint_catalog,
10437    NULL::text AS constraint_schema,
10438    NULL::text AS constraint_name,
10439    NULL::text AS unique_constraint_catalog,
10440    NULL::text AS unique_constraint_schema,
10441    NULL::text AS unique_constraint_name,
10442    NULL::text AS match_option,
10443    NULL::text AS update_rule,
10444    NULL::text AS delete_rule
10445WHERE false",
10446        access: vec![PUBLIC_SELECT],
10447    });
10448
10449pub static INFORMATION_SCHEMA_ROUTINES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10450    name: "routines",
10451    schema: INFORMATION_SCHEMA,
10452    oid: oid::VIEW_ROUTINES_OID,
10453    desc: RelationDesc::builder()
10454        .with_column("routine_catalog", SqlScalarType::String.nullable(false))
10455        .with_column("routine_schema", SqlScalarType::String.nullable(false))
10456        .with_column("routine_name", SqlScalarType::String.nullable(false))
10457        .with_column("routine_type", SqlScalarType::String.nullable(false))
10458        .with_column("routine_definition", SqlScalarType::String.nullable(true))
10459        .finish(),
10460    column_comments: BTreeMap::new(),
10461    sql: "SELECT
10462    current_database() as routine_catalog,
10463    s.name AS routine_schema,
10464    f.name AS routine_name,
10465    'FUNCTION' AS routine_type,
10466    NULL::text AS routine_definition
10467FROM mz_catalog.mz_functions f
10468JOIN mz_catalog.mz_schemas s ON s.id = f.schema_id
10469LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10470WHERE s.database_id IS NULL OR d.name = current_database()",
10471    access: vec![PUBLIC_SELECT],
10472});
10473
10474pub static INFORMATION_SCHEMA_SCHEMATA: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10475    name: "schemata",
10476    schema: INFORMATION_SCHEMA,
10477    oid: oid::VIEW_SCHEMATA_OID,
10478    desc: RelationDesc::builder()
10479        .with_column("catalog_name", SqlScalarType::String.nullable(false))
10480        .with_column("schema_name", SqlScalarType::String.nullable(false))
10481        .finish(),
10482    column_comments: BTreeMap::new(),
10483    sql: "
10484SELECT
10485    current_database() as catalog_name,
10486    s.name AS schema_name
10487FROM mz_catalog.mz_schemas s
10488LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10489WHERE s.database_id IS NULL OR d.name = current_database()",
10490    access: vec![PUBLIC_SELECT],
10491});
10492
10493pub static INFORMATION_SCHEMA_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10494    name: "tables",
10495    schema: INFORMATION_SCHEMA,
10496    oid: oid::VIEW_TABLES_OID,
10497    desc: RelationDesc::builder()
10498        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10499        .with_column("table_schema", SqlScalarType::String.nullable(false))
10500        .with_column("table_name", SqlScalarType::String.nullable(false))
10501        .with_column("table_type", SqlScalarType::String.nullable(false))
10502        .finish(),
10503    column_comments: BTreeMap::new(),
10504    sql: "SELECT
10505    current_database() as table_catalog,
10506    s.name AS table_schema,
10507    r.name AS table_name,
10508    CASE r.type
10509        WHEN 'materialized-view' THEN 'MATERIALIZED VIEW'
10510        WHEN 'table' THEN 'BASE TABLE'
10511        ELSE pg_catalog.upper(r.type)
10512    END AS table_type
10513FROM mz_catalog.mz_relations r
10514JOIN mz_catalog.mz_schemas s ON s.id = r.schema_id
10515LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10516WHERE s.database_id IS NULL OR d.name = current_database()",
10517    access: vec![PUBLIC_SELECT],
10518});
10519
10520pub static INFORMATION_SCHEMA_TABLE_CONSTRAINTS: LazyLock<BuiltinView> =
10521    LazyLock::new(|| BuiltinView {
10522        name: "table_constraints",
10523        schema: INFORMATION_SCHEMA,
10524        oid: oid::VIEW_TABLE_CONSTRAINTS_OID,
10525        desc: RelationDesc::builder()
10526            .with_column("constraint_catalog", SqlScalarType::String.nullable(false))
10527            .with_column("constraint_schema", SqlScalarType::String.nullable(false))
10528            .with_column("constraint_name", SqlScalarType::String.nullable(false))
10529            .with_column("table_catalog", SqlScalarType::String.nullable(false))
10530            .with_column("table_schema", SqlScalarType::String.nullable(false))
10531            .with_column("table_name", SqlScalarType::String.nullable(false))
10532            .with_column("constraint_type", SqlScalarType::String.nullable(false))
10533            .with_column("is_deferrable", SqlScalarType::String.nullable(false))
10534            .with_column("initially_deferred", SqlScalarType::String.nullable(false))
10535            .with_column("enforced", SqlScalarType::String.nullable(false))
10536            .with_column("nulls_distinct", SqlScalarType::String.nullable(false))
10537            .with_key(vec![])
10538            .finish(),
10539        column_comments: BTreeMap::new(),
10540        sql: "SELECT
10541    NULL::text AS constraint_catalog,
10542    NULL::text AS constraint_schema,
10543    NULL::text AS constraint_name,
10544    NULL::text AS table_catalog,
10545    NULL::text AS table_schema,
10546    NULL::text AS table_name,
10547    NULL::text AS constraint_type,
10548    NULL::text AS is_deferrable,
10549    NULL::text AS initially_deferred,
10550    NULL::text AS enforced,
10551    NULL::text AS nulls_distinct
10552WHERE false",
10553        access: vec![PUBLIC_SELECT],
10554    });
10555
10556pub static INFORMATION_SCHEMA_TABLE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| {
10557    BuiltinView {
10558        name: "table_privileges",
10559        schema: INFORMATION_SCHEMA,
10560        oid: oid::VIEW_TABLE_PRIVILEGES_OID,
10561        desc: RelationDesc::builder()
10562            .with_column("grantor", SqlScalarType::String.nullable(false))
10563            .with_column("grantee", SqlScalarType::String.nullable(true))
10564            .with_column("table_catalog", SqlScalarType::String.nullable(true))
10565            .with_column("table_schema", SqlScalarType::String.nullable(false))
10566            .with_column("table_name", SqlScalarType::String.nullable(false))
10567            .with_column("privilege_type", SqlScalarType::String.nullable(true))
10568            .with_column("is_grantable", SqlScalarType::String.nullable(false))
10569            .with_column("with_hierarchy", SqlScalarType::String.nullable(false))
10570            .finish(),
10571        column_comments: BTreeMap::new(),
10572        sql: "
10573SELECT
10574    grantor,
10575    grantee,
10576    table_catalog,
10577    table_schema,
10578    table_name,
10579    privilege_type,
10580    is_grantable,
10581    CASE privilege_type
10582        WHEN 'SELECT' THEN 'YES'
10583        ELSE 'NO'
10584    END AS with_hierarchy
10585FROM
10586    (SELECT
10587        grantor.name AS grantor,
10588        CASE mz_internal.mz_aclitem_grantee(privileges)
10589            WHEN 'p' THEN 'PUBLIC'
10590            ELSE grantee.name
10591        END AS grantee,
10592        table_catalog,
10593        table_schema,
10594        table_name,
10595        unnest(mz_internal.mz_format_privileges(mz_internal.mz_aclitem_privileges(privileges))) AS privilege_type,
10596        -- ADMIN OPTION isn't implemented.
10597        'NO' AS is_grantable
10598    FROM
10599        (SELECT
10600            unnest(relations.privileges) AS privileges,
10601            CASE
10602                WHEN schemas.database_id IS NULL THEN current_database()
10603                ELSE databases.name
10604            END AS table_catalog,
10605            schemas.name AS table_schema,
10606            relations.name AS table_name
10607        FROM mz_catalog.mz_relations AS relations
10608        JOIN mz_catalog.mz_schemas AS schemas ON relations.schema_id = schemas.id
10609        LEFT JOIN mz_catalog.mz_databases AS databases ON schemas.database_id = databases.id
10610        WHERE schemas.database_id IS NULL OR databases.name = current_database())
10611    JOIN mz_catalog.mz_roles AS grantor ON mz_internal.mz_aclitem_grantor(privileges) = grantor.id
10612    LEFT JOIN mz_catalog.mz_roles AS grantee ON mz_internal.mz_aclitem_grantee(privileges) = grantee.id)
10613WHERE
10614    -- WHERE clause is not guaranteed to short-circuit and 'PUBLIC' will cause an error when passed
10615    -- to pg_has_role. Therefore we need to use a CASE statement.
10616    CASE
10617        WHEN grantee = 'PUBLIC' THEN true
10618        ELSE mz_catalog.mz_is_superuser()
10619            OR pg_has_role(current_role, grantee, 'USAGE')
10620            OR pg_has_role(current_role, grantor, 'USAGE')
10621    END",
10622        access: vec![PUBLIC_SELECT],
10623    }
10624});
10625
10626pub static INFORMATION_SCHEMA_TRIGGERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10627    name: "triggers",
10628    schema: INFORMATION_SCHEMA,
10629    oid: oid::VIEW_TRIGGERS_OID,
10630    desc: RelationDesc::builder()
10631        .with_column("trigger_catalog", SqlScalarType::String.nullable(false))
10632        .with_column("trigger_schema", SqlScalarType::String.nullable(false))
10633        .with_column("trigger_name", SqlScalarType::String.nullable(false))
10634        .with_column("event_manipulation", SqlScalarType::String.nullable(false))
10635        .with_column(
10636            "event_object_catalog",
10637            SqlScalarType::String.nullable(false),
10638        )
10639        .with_column("event_object_schema", SqlScalarType::String.nullable(false))
10640        .with_column("event_object_table", SqlScalarType::String.nullable(false))
10641        .with_column("action_order", SqlScalarType::Int32.nullable(false))
10642        .with_column("action_condition", SqlScalarType::String.nullable(false))
10643        .with_column("action_statement", SqlScalarType::String.nullable(false))
10644        .with_column("action_orientation", SqlScalarType::String.nullable(false))
10645        .with_column("action_timing", SqlScalarType::String.nullable(false))
10646        .with_column(
10647            "action_reference_old_table",
10648            SqlScalarType::String.nullable(false),
10649        )
10650        .with_column(
10651            "action_reference_new_table",
10652            SqlScalarType::String.nullable(false),
10653        )
10654        .with_key(vec![])
10655        .finish(),
10656    column_comments: BTreeMap::new(),
10657    sql: "SELECT
10658    NULL::text as trigger_catalog,
10659    NULL::text AS trigger_schema,
10660    NULL::text AS trigger_name,
10661    NULL::text AS event_manipulation,
10662    NULL::text AS event_object_catalog,
10663    NULL::text AS event_object_schema,
10664    NULL::text AS event_object_table,
10665    NULL::integer AS action_order,
10666    NULL::text AS action_condition,
10667    NULL::text AS action_statement,
10668    NULL::text AS action_orientation,
10669    NULL::text AS action_timing,
10670    NULL::text AS action_reference_old_table,
10671    NULL::text AS action_reference_new_table
10672WHERE FALSE",
10673    access: vec![PUBLIC_SELECT],
10674});
10675
10676pub static INFORMATION_SCHEMA_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10677    name: "views",
10678    schema: INFORMATION_SCHEMA,
10679    oid: oid::VIEW_VIEWS_OID,
10680    desc: RelationDesc::builder()
10681        .with_column("table_catalog", SqlScalarType::String.nullable(false))
10682        .with_column("table_schema", SqlScalarType::String.nullable(false))
10683        .with_column("table_name", SqlScalarType::String.nullable(false))
10684        .with_column("view_definition", SqlScalarType::String.nullable(false))
10685        .finish(),
10686    column_comments: BTreeMap::new(),
10687    sql: "SELECT
10688    current_database() as table_catalog,
10689    s.name AS table_schema,
10690    v.name AS table_name,
10691    v.definition AS view_definition
10692FROM mz_catalog.mz_views v
10693JOIN mz_catalog.mz_schemas s ON s.id = v.schema_id
10694LEFT JOIN mz_catalog.mz_databases d ON d.id = s.database_id
10695WHERE s.database_id IS NULL OR d.name = current_database()",
10696    access: vec![PUBLIC_SELECT],
10697});
10698
10699pub static INFORMATION_SCHEMA_CHARACTER_SETS: LazyLock<BuiltinView> =
10700    LazyLock::new(|| BuiltinView {
10701        name: "character_sets",
10702        schema: INFORMATION_SCHEMA,
10703        oid: oid::VIEW_CHARACTER_SETS_OID,
10704        desc: RelationDesc::builder()
10705            .with_column(
10706                "character_set_catalog",
10707                SqlScalarType::String.nullable(true),
10708            )
10709            .with_column("character_set_schema", SqlScalarType::String.nullable(true))
10710            .with_column("character_set_name", SqlScalarType::String.nullable(false))
10711            .with_column(
10712                "character_repertoire",
10713                SqlScalarType::String.nullable(false),
10714            )
10715            .with_column("form_of_use", SqlScalarType::String.nullable(false))
10716            .with_column(
10717                "default_collate_catalog",
10718                SqlScalarType::String.nullable(false),
10719            )
10720            .with_column(
10721                "default_collate_schema",
10722                SqlScalarType::String.nullable(false),
10723            )
10724            .with_column(
10725                "default_collate_name",
10726                SqlScalarType::String.nullable(false),
10727            )
10728            .with_key(vec![])
10729            .finish(),
10730        column_comments: BTreeMap::new(),
10731        sql: "SELECT
10732    NULL as character_set_catalog,
10733    NULL as character_set_schema,
10734    'UTF8' as character_set_name,
10735    'UCS' as character_repertoire,
10736    'UTF8' as form_of_use,
10737    current_database() as default_collate_catalog,
10738    'pg_catalog' as default_collate_schema,
10739    'en_US.utf8' as default_collate_name",
10740        access: vec![PUBLIC_SELECT],
10741    });
10742
10743// MZ doesn't support COLLATE so the table is filled with NULLs and made empty. pg_database hard
10744// codes a collation of 'C' for every database, so we could copy that here.
10745pub static PG_COLLATION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10746    name: "pg_collation",
10747    schema: PG_CATALOG_SCHEMA,
10748    oid: oid::VIEW_PG_COLLATION_OID,
10749    desc: RelationDesc::builder()
10750        .with_column("oid", SqlScalarType::Oid.nullable(false))
10751        .with_column("collname", SqlScalarType::String.nullable(false))
10752        .with_column("collnamespace", SqlScalarType::Oid.nullable(false))
10753        .with_column("collowner", SqlScalarType::Oid.nullable(false))
10754        .with_column("collprovider", SqlScalarType::PgLegacyChar.nullable(false))
10755        .with_column("collisdeterministic", SqlScalarType::Bool.nullable(false))
10756        .with_column("collencoding", SqlScalarType::Int32.nullable(false))
10757        .with_column("collcollate", SqlScalarType::String.nullable(false))
10758        .with_column("collctype", SqlScalarType::String.nullable(false))
10759        .with_column("collversion", SqlScalarType::String.nullable(false))
10760        .with_key(vec![])
10761        .finish(),
10762    column_comments: BTreeMap::new(),
10763    sql: "
10764SELECT
10765    NULL::pg_catalog.oid AS oid,
10766    NULL::pg_catalog.text AS collname,
10767    NULL::pg_catalog.oid AS collnamespace,
10768    NULL::pg_catalog.oid AS collowner,
10769    NULL::pg_catalog.\"char\" AS collprovider,
10770    NULL::pg_catalog.bool AS collisdeterministic,
10771    NULL::pg_catalog.int4 AS collencoding,
10772    NULL::pg_catalog.text AS collcollate,
10773    NULL::pg_catalog.text AS collctype,
10774    NULL::pg_catalog.text AS collversion
10775WHERE false",
10776    access: vec![PUBLIC_SELECT],
10777});
10778
10779// MZ doesn't support row level security policies so the table is filled in with NULLs and made empty.
10780pub static PG_POLICY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10781    name: "pg_policy",
10782    schema: PG_CATALOG_SCHEMA,
10783    oid: oid::VIEW_PG_POLICY_OID,
10784    desc: RelationDesc::builder()
10785        .with_column("oid", SqlScalarType::Oid.nullable(false))
10786        .with_column("polname", SqlScalarType::String.nullable(false))
10787        .with_column("polrelid", SqlScalarType::Oid.nullable(false))
10788        .with_column("polcmd", SqlScalarType::PgLegacyChar.nullable(false))
10789        .with_column("polpermissive", SqlScalarType::Bool.nullable(false))
10790        .with_column(
10791            "polroles",
10792            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
10793        )
10794        .with_column("polqual", SqlScalarType::String.nullable(false))
10795        .with_column("polwithcheck", SqlScalarType::String.nullable(false))
10796        .with_key(vec![])
10797        .finish(),
10798    column_comments: BTreeMap::new(),
10799    sql: "
10800SELECT
10801    NULL::pg_catalog.oid AS oid,
10802    NULL::pg_catalog.text AS polname,
10803    NULL::pg_catalog.oid AS polrelid,
10804    NULL::pg_catalog.\"char\" AS polcmd,
10805    NULL::pg_catalog.bool AS polpermissive,
10806    NULL::pg_catalog.oid[] AS polroles,
10807    NULL::pg_catalog.text AS polqual,
10808    NULL::pg_catalog.text AS polwithcheck
10809WHERE false",
10810    access: vec![PUBLIC_SELECT],
10811});
10812
10813// MZ doesn't support table inheritance so the table is filled in with NULLs and made empty.
10814pub static PG_INHERITS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10815    name: "pg_inherits",
10816    schema: PG_CATALOG_SCHEMA,
10817    oid: oid::VIEW_PG_INHERITS_OID,
10818    desc: RelationDesc::builder()
10819        .with_column("inhrelid", SqlScalarType::Oid.nullable(false))
10820        .with_column("inhparent", SqlScalarType::Oid.nullable(false))
10821        .with_column("inhseqno", SqlScalarType::Int32.nullable(false))
10822        .with_column("inhdetachpending", SqlScalarType::Bool.nullable(false))
10823        .with_key(vec![])
10824        .finish(),
10825    column_comments: BTreeMap::new(),
10826    sql: "
10827SELECT
10828    NULL::pg_catalog.oid AS inhrelid,
10829    NULL::pg_catalog.oid AS inhparent,
10830    NULL::pg_catalog.int4 AS inhseqno,
10831    NULL::pg_catalog.bool AS inhdetachpending
10832WHERE false",
10833    access: vec![PUBLIC_SELECT],
10834});
10835
10836pub static PG_LOCKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10837    name: "pg_locks",
10838    schema: PG_CATALOG_SCHEMA,
10839    oid: oid::VIEW_PG_LOCKS_OID,
10840    desc: RelationDesc::builder()
10841        .with_column("locktype", SqlScalarType::String.nullable(false))
10842        .with_column("database", SqlScalarType::Oid.nullable(false))
10843        .with_column("relation", SqlScalarType::Oid.nullable(false))
10844        .with_column("page", SqlScalarType::Int32.nullable(false))
10845        .with_column("tuple", SqlScalarType::Int16.nullable(false))
10846        .with_column("virtualxid", SqlScalarType::String.nullable(false))
10847        .with_column("transactionid", SqlScalarType::String.nullable(false))
10848        .with_column("classid", SqlScalarType::Oid.nullable(false))
10849        .with_column("objid", SqlScalarType::Oid.nullable(false))
10850        .with_column("objsubid", SqlScalarType::Int16.nullable(false))
10851        .with_column("virtualtransaction", SqlScalarType::String.nullable(false))
10852        .with_column("pid", SqlScalarType::Int32.nullable(false))
10853        .with_column("mode", SqlScalarType::String.nullable(false))
10854        .with_column("granted", SqlScalarType::Bool.nullable(false))
10855        .with_column("fastpath", SqlScalarType::Bool.nullable(false))
10856        .with_column(
10857            "waitstart",
10858            SqlScalarType::TimestampTz { precision: None }.nullable(false),
10859        )
10860        .with_key(vec![])
10861        .finish(),
10862    column_comments: BTreeMap::new(),
10863    sql: "
10864SELECT
10865-- While there exist locks in Materialize, we don't expose them, so all of these fields are NULL.
10866    NULL::pg_catalog.text AS locktype,
10867    NULL::pg_catalog.oid AS database,
10868    NULL::pg_catalog.oid AS relation,
10869    NULL::pg_catalog.int4 AS page,
10870    NULL::pg_catalog.int2 AS tuple,
10871    NULL::pg_catalog.text AS virtualxid,
10872    NULL::pg_catalog.text AS transactionid,
10873    NULL::pg_catalog.oid AS classid,
10874    NULL::pg_catalog.oid AS objid,
10875    NULL::pg_catalog.int2 AS objsubid,
10876    NULL::pg_catalog.text AS virtualtransaction,
10877    NULL::pg_catalog.int4 AS pid,
10878    NULL::pg_catalog.text AS mode,
10879    NULL::pg_catalog.bool AS granted,
10880    NULL::pg_catalog.bool AS fastpath,
10881    NULL::pg_catalog.timestamptz AS waitstart
10882WHERE false",
10883    access: vec![PUBLIC_SELECT],
10884});
10885
10886/// Peeled version of `PG_AUTHID`: Excludes the columns rolcreaterole and rolcreatedb, to make this
10887/// view indexable.
10888pub static PG_AUTHID_CORE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10889    name: "pg_authid_core",
10890    schema: MZ_INTERNAL_SCHEMA,
10891    oid: oid::VIEW_PG_AUTHID_CORE_OID,
10892    desc: RelationDesc::builder()
10893        .with_column("oid", SqlScalarType::Oid.nullable(false))
10894        .with_column("rolname", SqlScalarType::String.nullable(false))
10895        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10896        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10897        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10898        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10899        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10900        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10901        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10902        .with_column(
10903            "rolvaliduntil",
10904            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10905        )
10906        .finish(),
10907    column_comments: BTreeMap::new(),
10908    sql: r#"
10909SELECT
10910    r.oid AS oid,
10911    r.name AS rolname,
10912    rolsuper,
10913    inherit AS rolinherit,
10914    COALESCE(r.rolcanlogin, false) AS rolcanlogin,
10915    -- MZ doesn't support replication in the same way Postgres does
10916    false AS rolreplication,
10917    -- MZ doesn't how row level security
10918    false AS rolbypassrls,
10919    -- MZ doesn't have a connection limit
10920    -1 AS rolconnlimit,
10921    a.password_hash AS rolpassword,
10922    NULL::pg_catalog.timestamptz AS rolvaliduntil
10923FROM mz_catalog.mz_roles r
10924LEFT JOIN mz_catalog.mz_role_auth a ON r.oid = a.role_oid"#,
10925    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10926});
10927
10928pub const PG_AUTHID_CORE_IND: BuiltinIndex = BuiltinIndex {
10929    name: "pg_authid_core_ind",
10930    schema: MZ_INTERNAL_SCHEMA,
10931    oid: oid::INDEX_PG_AUTHID_CORE_IND_OID,
10932    sql: "IN CLUSTER mz_catalog_server
10933ON mz_internal.pg_authid_core (rolname)",
10934    is_retained_metrics_object: false,
10935};
10936
10937pub static PG_AUTHID: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
10938    name: "pg_authid",
10939    schema: PG_CATALOG_SCHEMA,
10940    oid: oid::VIEW_PG_AUTHID_OID,
10941    desc: RelationDesc::builder()
10942        .with_column("oid", SqlScalarType::Oid.nullable(false))
10943        .with_column("rolname", SqlScalarType::String.nullable(false))
10944        .with_column("rolsuper", SqlScalarType::Bool.nullable(true))
10945        .with_column("rolinherit", SqlScalarType::Bool.nullable(false))
10946        .with_column("rolcreaterole", SqlScalarType::Bool.nullable(true))
10947        .with_column("rolcreatedb", SqlScalarType::Bool.nullable(true))
10948        .with_column("rolcanlogin", SqlScalarType::Bool.nullable(false))
10949        .with_column("rolreplication", SqlScalarType::Bool.nullable(false))
10950        .with_column("rolbypassrls", SqlScalarType::Bool.nullable(false))
10951        .with_column("rolconnlimit", SqlScalarType::Int32.nullable(false))
10952        .with_column("rolpassword", SqlScalarType::String.nullable(true))
10953        .with_column(
10954            "rolvaliduntil",
10955            SqlScalarType::TimestampTz { precision: None }.nullable(true),
10956        )
10957        .finish(),
10958    column_comments: BTreeMap::new(),
10959    // The `has_system_privilege` invocations for `rolcreaterole` and `rolcreatedb` get expanded
10960    // into very complex subqueries. If we put them into the SELECT clause directly, decorrelation
10961    // produces a very complex plan that the optimizer has a hard time dealing with. In particular,
10962    // the optimizer fails to reduce a query like `SELECT oid FROM pg_authid` to a simple lookup on
10963    // the `pg_authid_core` index and instead produces a large plan that contains a bunch of
10964    // expensive joins and arrangements.
10965    //
10966    // The proper fix is likely to implement `has_system_privileges` in Rust, but for now we work
10967    // around the issue by manually decorrelating `rolcreaterole` and `rolcreatedb`. Note that to
10968    // get the desired behavior we need to make sure that the join with `extra` doesn't change the
10969    // cardinality of `pg_authid_core` (otherwise it can never be optimized away). We ensure this
10970    // by:
10971    //  * using a `LEFT JOIN`, so the optimizer knows that left elements are never filtered
10972    //  * applying a `DISTINCT ON` to the CTE, so the optimizer knows that left elements are never
10973    //    duplicated
10974    sql: r#"
10975WITH extra AS (
10976    SELECT
10977        DISTINCT ON (oid)
10978        oid,
10979        mz_catalog.has_system_privilege(oid, 'CREATEROLE') AS rolcreaterole,
10980        mz_catalog.has_system_privilege(oid, 'CREATEDB') AS rolcreatedb
10981    FROM mz_internal.pg_authid_core
10982)
10983SELECT
10984    oid,
10985    rolname,
10986    rolsuper,
10987    rolinherit,
10988    extra.rolcreaterole,
10989    extra.rolcreatedb,
10990    rolcanlogin,
10991    rolreplication,
10992    rolbypassrls,
10993    rolconnlimit,
10994    rolpassword,
10995    rolvaliduntil
10996FROM mz_internal.pg_authid_core
10997LEFT JOIN extra USING (oid)"#,
10998    access: vec![rbac::owner_privilege(ObjectType::Table, MZ_SYSTEM_ROLE_ID)],
10999});
11000
11001pub static PG_AGGREGATE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11002    name: "pg_aggregate",
11003    schema: PG_CATALOG_SCHEMA,
11004    oid: oid::VIEW_PG_AGGREGATE_OID,
11005    desc: RelationDesc::builder()
11006        .with_column("aggfnoid", SqlScalarType::Oid.nullable(false))
11007        .with_column("aggkind", SqlScalarType::String.nullable(false))
11008        .with_column("aggnumdirectargs", SqlScalarType::Int16.nullable(false))
11009        .with_column("aggtransfn", SqlScalarType::RegProc.nullable(true))
11010        .with_column("aggfinalfn", SqlScalarType::RegProc.nullable(false))
11011        .with_column("aggcombinefn", SqlScalarType::RegProc.nullable(false))
11012        .with_column("aggserialfn", SqlScalarType::RegProc.nullable(false))
11013        .with_column("aggdeserialfn", SqlScalarType::RegProc.nullable(false))
11014        .with_column("aggmtransfn", SqlScalarType::RegProc.nullable(false))
11015        .with_column("aggminvtransfn", SqlScalarType::RegProc.nullable(false))
11016        .with_column("aggmfinalfn", SqlScalarType::RegProc.nullable(false))
11017        .with_column("aggfinalextra", SqlScalarType::Bool.nullable(false))
11018        .with_column("aggmfinalextra", SqlScalarType::Bool.nullable(false))
11019        .with_column("aggfinalmodify", SqlScalarType::PgLegacyChar.nullable(true))
11020        .with_column(
11021            "aggmfinalmodify",
11022            SqlScalarType::PgLegacyChar.nullable(true),
11023        )
11024        .with_column("aggsortop", SqlScalarType::Oid.nullable(false))
11025        .with_column("aggtranstype", SqlScalarType::Oid.nullable(true))
11026        .with_column("aggtransspace", SqlScalarType::Int32.nullable(true))
11027        .with_column("aggmtranstype", SqlScalarType::Oid.nullable(false))
11028        .with_column("aggmtransspace", SqlScalarType::Int32.nullable(true))
11029        .with_column("agginitval", SqlScalarType::String.nullable(true))
11030        .with_column("aggminitval", SqlScalarType::String.nullable(true))
11031        .finish(),
11032    column_comments: BTreeMap::new(),
11033    sql: "SELECT
11034    a.oid as aggfnoid,
11035    -- Currently Materialize only support 'normal' aggregate functions.
11036    a.agg_kind as aggkind,
11037    a.agg_num_direct_args as aggnumdirectargs,
11038    -- Materialize doesn't support these fields.
11039    NULL::pg_catalog.regproc as aggtransfn,
11040    '0'::pg_catalog.regproc as aggfinalfn,
11041    '0'::pg_catalog.regproc as aggcombinefn,
11042    '0'::pg_catalog.regproc as aggserialfn,
11043    '0'::pg_catalog.regproc as aggdeserialfn,
11044    '0'::pg_catalog.regproc as aggmtransfn,
11045    '0'::pg_catalog.regproc as aggminvtransfn,
11046    '0'::pg_catalog.regproc as aggmfinalfn,
11047    false as aggfinalextra,
11048    false as aggmfinalextra,
11049    NULL::pg_catalog.\"char\" AS aggfinalmodify,
11050    NULL::pg_catalog.\"char\" AS aggmfinalmodify,
11051    '0'::pg_catalog.oid as aggsortop,
11052    NULL::pg_catalog.oid as aggtranstype,
11053    NULL::pg_catalog.int4 as aggtransspace,
11054    '0'::pg_catalog.oid as aggmtranstype,
11055    NULL::pg_catalog.int4 as aggmtransspace,
11056    NULL::pg_catalog.text as agginitval,
11057    NULL::pg_catalog.text as aggminitval
11058FROM mz_internal.mz_aggregates a",
11059    access: vec![PUBLIC_SELECT],
11060});
11061
11062pub static PG_TRIGGER: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11063    name: "pg_trigger",
11064    schema: PG_CATALOG_SCHEMA,
11065    oid: oid::VIEW_PG_TRIGGER_OID,
11066    desc: RelationDesc::builder()
11067        .with_column("oid", SqlScalarType::Oid.nullable(false))
11068        .with_column("tgrelid", SqlScalarType::Oid.nullable(false))
11069        .with_column("tgparentid", SqlScalarType::Oid.nullable(false))
11070        .with_column("tgname", SqlScalarType::String.nullable(false))
11071        .with_column("tgfoid", SqlScalarType::Oid.nullable(false))
11072        .with_column("tgtype", SqlScalarType::Int16.nullable(false))
11073        .with_column("tgenabled", SqlScalarType::PgLegacyChar.nullable(false))
11074        .with_column("tgisinternal", SqlScalarType::Bool.nullable(false))
11075        .with_column("tgconstrrelid", SqlScalarType::Oid.nullable(false))
11076        .with_column("tgconstrindid", SqlScalarType::Oid.nullable(false))
11077        .with_column("tgconstraint", SqlScalarType::Oid.nullable(false))
11078        .with_column("tgdeferrable", SqlScalarType::Bool.nullable(false))
11079        .with_column("tginitdeferred", SqlScalarType::Bool.nullable(false))
11080        .with_column("tgnargs", SqlScalarType::Int16.nullable(false))
11081        .with_column("tgattr", SqlScalarType::Int2Vector.nullable(false))
11082        .with_column("tgargs", SqlScalarType::Bytes.nullable(false))
11083        .with_column("tgqual", SqlScalarType::String.nullable(false))
11084        .with_column("tgoldtable", SqlScalarType::String.nullable(false))
11085        .with_column("tgnewtable", SqlScalarType::String.nullable(false))
11086        .with_key(vec![])
11087        .finish(),
11088    column_comments: BTreeMap::new(),
11089    sql: "SELECT
11090    -- MZ doesn't support triggers so all of these fields are NULL.
11091    NULL::pg_catalog.oid AS oid,
11092    NULL::pg_catalog.oid AS tgrelid,
11093    NULL::pg_catalog.oid AS tgparentid,
11094    NULL::pg_catalog.text AS tgname,
11095    NULL::pg_catalog.oid AS tgfoid,
11096    NULL::pg_catalog.int2 AS tgtype,
11097    NULL::pg_catalog.\"char\" AS tgenabled,
11098    NULL::pg_catalog.bool AS tgisinternal,
11099    NULL::pg_catalog.oid AS tgconstrrelid,
11100    NULL::pg_catalog.oid AS tgconstrindid,
11101    NULL::pg_catalog.oid AS tgconstraint,
11102    NULL::pg_catalog.bool AS tgdeferrable,
11103    NULL::pg_catalog.bool AS tginitdeferred,
11104    NULL::pg_catalog.int2 AS tgnargs,
11105    NULL::pg_catalog.int2vector AS tgattr,
11106    NULL::pg_catalog.bytea AS tgargs,
11107    -- NOTE: The tgqual column is actually type `pg_node_tree` which we don't support. CockroachDB
11108    -- uses text as a placeholder, so we'll follow their lead here.
11109    NULL::pg_catalog.text AS tgqual,
11110    NULL::pg_catalog.text AS tgoldtable,
11111    NULL::pg_catalog.text AS tgnewtable
11112WHERE false
11113    ",
11114    access: vec![PUBLIC_SELECT],
11115});
11116
11117pub static PG_REWRITE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11118    name: "pg_rewrite",
11119    schema: PG_CATALOG_SCHEMA,
11120    oid: oid::VIEW_PG_REWRITE_OID,
11121    desc: RelationDesc::builder()
11122        .with_column("oid", SqlScalarType::Oid.nullable(false))
11123        .with_column("rulename", SqlScalarType::String.nullable(false))
11124        .with_column("ev_class", SqlScalarType::Oid.nullable(false))
11125        .with_column("ev_type", SqlScalarType::PgLegacyChar.nullable(false))
11126        .with_column("ev_enabled", SqlScalarType::PgLegacyChar.nullable(false))
11127        .with_column("is_instead", SqlScalarType::Bool.nullable(false))
11128        .with_column("ev_qual", SqlScalarType::String.nullable(false))
11129        .with_column("ev_action", SqlScalarType::String.nullable(false))
11130        .with_key(vec![])
11131        .finish(),
11132    column_comments: BTreeMap::new(),
11133    sql: "SELECT
11134    -- MZ doesn't support rewrite rules so all of these fields are NULL.
11135    NULL::pg_catalog.oid AS oid,
11136    NULL::pg_catalog.text AS rulename,
11137    NULL::pg_catalog.oid AS ev_class,
11138    NULL::pg_catalog.\"char\" AS ev_type,
11139    NULL::pg_catalog.\"char\" AS ev_enabled,
11140    NULL::pg_catalog.bool AS is_instead,
11141    -- NOTE: The ev_qual and ev_action columns are actually type `pg_node_tree` which we don't
11142    -- support. CockroachDB uses text as a placeholder, so we'll follow their lead here.
11143    NULL::pg_catalog.text AS ev_qual,
11144    NULL::pg_catalog.text AS ev_action
11145WHERE false
11146    ",
11147    access: vec![PUBLIC_SELECT],
11148});
11149
11150pub static PG_EXTENSION: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11151    name: "pg_extension",
11152    schema: PG_CATALOG_SCHEMA,
11153    oid: oid::VIEW_PG_EXTENSION_OID,
11154    desc: RelationDesc::builder()
11155        .with_column("oid", SqlScalarType::Oid.nullable(false))
11156        .with_column("extname", SqlScalarType::String.nullable(false))
11157        .with_column("extowner", SqlScalarType::Oid.nullable(false))
11158        .with_column("extnamespace", SqlScalarType::Oid.nullable(false))
11159        .with_column("extrelocatable", SqlScalarType::Bool.nullable(false))
11160        .with_column("extversion", SqlScalarType::String.nullable(false))
11161        .with_column(
11162            "extconfig",
11163            SqlScalarType::Array(Box::new(SqlScalarType::Oid)).nullable(false),
11164        )
11165        .with_column(
11166            "extcondition",
11167            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11168        )
11169        .with_key(vec![])
11170        .finish(),
11171    column_comments: BTreeMap::new(),
11172    sql: "SELECT
11173    -- MZ doesn't support extensions so all of these fields are NULL.
11174    NULL::pg_catalog.oid AS oid,
11175    NULL::pg_catalog.text AS extname,
11176    NULL::pg_catalog.oid AS extowner,
11177    NULL::pg_catalog.oid AS extnamespace,
11178    NULL::pg_catalog.bool AS extrelocatable,
11179    NULL::pg_catalog.text AS extversion,
11180    NULL::pg_catalog.oid[] AS extconfig,
11181    NULL::pg_catalog.text[] AS extcondition
11182WHERE false
11183    ",
11184    access: vec![PUBLIC_SELECT],
11185});
11186
11187pub static MZ_SHOW_ALL_OBJECTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11188    name: "mz_show_all_objects",
11189    schema: MZ_INTERNAL_SCHEMA,
11190    oid: oid::VIEW_MZ_SHOW_ALL_OBJECTS_OID,
11191    desc: RelationDesc::builder()
11192        .with_column("schema_id", SqlScalarType::String.nullable(false))
11193        .with_column("name", SqlScalarType::String.nullable(false))
11194        .with_column("type", SqlScalarType::String.nullable(false))
11195        .with_column("comment", SqlScalarType::String.nullable(false))
11196        .finish(),
11197    column_comments: BTreeMap::new(),
11198    sql: "WITH comments AS (
11199        SELECT id, object_type, comment
11200        FROM mz_internal.mz_comments
11201        WHERE object_sub_id IS NULL
11202    )
11203    SELECT schema_id, name, type, COALESCE(comment, '') AS comment
11204    FROM mz_catalog.mz_objects AS objs
11205    LEFT JOIN comments ON objs.id = comments.id
11206    WHERE (comments.object_type = objs.type OR comments.object_type IS NULL)",
11207    access: vec![PUBLIC_SELECT],
11208});
11209
11210pub static MZ_SHOW_CLUSTERS: LazyLock<BuiltinView> = LazyLock::new(|| {
11211    BuiltinView {
11212    name: "mz_show_clusters",
11213    schema: MZ_INTERNAL_SCHEMA,
11214    oid: oid::VIEW_MZ_SHOW_CLUSTERS_OID,
11215    desc: RelationDesc::builder()
11216        .with_column("name", SqlScalarType::String.nullable(false))
11217        .with_column("replicas", SqlScalarType::String.nullable(true))
11218        .with_column("comment", SqlScalarType::String.nullable(false))
11219        .finish(),
11220    column_comments: BTreeMap::new(),
11221    sql: "
11222    WITH clusters AS (
11223        SELECT
11224            mc.id,
11225            mc.name,
11226            pg_catalog.string_agg(mcr.name || ' (' || mcr.size || ')', ', ' ORDER BY mcr.name) AS replicas
11227        FROM mz_catalog.mz_clusters mc
11228        LEFT JOIN mz_catalog.mz_cluster_replicas mcr
11229        ON mc.id = mcr.cluster_id
11230        GROUP BY mc.id, mc.name
11231    ),
11232    comments AS (
11233        SELECT id, comment
11234        FROM mz_internal.mz_comments
11235        WHERE object_type = 'cluster' AND object_sub_id IS NULL
11236    )
11237    SELECT name, replicas, COALESCE(comment, '') as comment
11238    FROM clusters
11239    LEFT JOIN comments ON clusters.id = comments.id",
11240    access: vec![PUBLIC_SELECT],
11241}
11242});
11243
11244pub static MZ_SHOW_SECRETS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11245    name: "mz_show_secrets",
11246    schema: MZ_INTERNAL_SCHEMA,
11247    oid: oid::VIEW_MZ_SHOW_SECRETS_OID,
11248    desc: RelationDesc::builder()
11249        .with_column("schema_id", SqlScalarType::String.nullable(false))
11250        .with_column("name", SqlScalarType::String.nullable(false))
11251        .with_column("comment", SqlScalarType::String.nullable(false))
11252        .finish(),
11253    column_comments: BTreeMap::new(),
11254    sql: "WITH comments AS (
11255        SELECT id, comment
11256        FROM mz_internal.mz_comments
11257        WHERE object_type = 'secret' AND object_sub_id IS NULL
11258    )
11259    SELECT schema_id, name, COALESCE(comment, '') as comment
11260    FROM mz_catalog.mz_secrets secrets
11261    LEFT JOIN comments ON secrets.id = comments.id",
11262    access: vec![PUBLIC_SELECT],
11263});
11264
11265pub static MZ_SHOW_COLUMNS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11266    name: "mz_show_columns",
11267    schema: MZ_INTERNAL_SCHEMA,
11268    oid: oid::VIEW_MZ_SHOW_COLUMNS_OID,
11269    desc: RelationDesc::builder()
11270        .with_column("id", SqlScalarType::String.nullable(false))
11271        .with_column("name", SqlScalarType::String.nullable(false))
11272        .with_column("nullable", SqlScalarType::Bool.nullable(false))
11273        .with_column("type", SqlScalarType::String.nullable(false))
11274        .with_column("position", SqlScalarType::UInt64.nullable(false))
11275        .with_column("comment", SqlScalarType::String.nullable(false))
11276        .finish(),
11277    column_comments: BTreeMap::new(),
11278    sql: "
11279    SELECT columns.id, name, nullable, type, position, COALESCE(comment, '') as comment
11280    FROM mz_catalog.mz_columns columns
11281    LEFT JOIN mz_internal.mz_comments comments
11282    ON columns.id = comments.id AND columns.position = comments.object_sub_id",
11283    access: vec![PUBLIC_SELECT],
11284});
11285
11286pub static MZ_SHOW_DATABASES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11287    name: "mz_show_databases",
11288    schema: MZ_INTERNAL_SCHEMA,
11289    oid: oid::VIEW_MZ_SHOW_DATABASES_OID,
11290    desc: RelationDesc::builder()
11291        .with_column("name", SqlScalarType::String.nullable(false))
11292        .with_column("comment", SqlScalarType::String.nullable(false))
11293        .finish(),
11294    column_comments: BTreeMap::new(),
11295    sql: "WITH comments AS (
11296        SELECT id, comment
11297        FROM mz_internal.mz_comments
11298        WHERE object_type = 'database' AND object_sub_id IS NULL
11299    )
11300    SELECT name, COALESCE(comment, '') as comment
11301    FROM mz_catalog.mz_databases databases
11302    LEFT JOIN comments ON databases.id = comments.id",
11303    access: vec![PUBLIC_SELECT],
11304});
11305
11306pub static MZ_SHOW_SCHEMAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11307    name: "mz_show_schemas",
11308    schema: MZ_INTERNAL_SCHEMA,
11309    oid: oid::VIEW_MZ_SHOW_SCHEMAS_OID,
11310    desc: RelationDesc::builder()
11311        .with_column("database_id", SqlScalarType::String.nullable(true))
11312        .with_column("name", SqlScalarType::String.nullable(false))
11313        .with_column("comment", SqlScalarType::String.nullable(false))
11314        .finish(),
11315    column_comments: BTreeMap::new(),
11316    sql: "WITH comments AS (
11317        SELECT id, comment
11318        FROM mz_internal.mz_comments
11319        WHERE object_type = 'schema' AND object_sub_id IS NULL
11320    )
11321    SELECT database_id, name, COALESCE(comment, '') as comment
11322    FROM mz_catalog.mz_schemas schemas
11323    LEFT JOIN comments ON schemas.id = comments.id",
11324    access: vec![PUBLIC_SELECT],
11325});
11326
11327pub static MZ_SHOW_ROLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11328    name: "mz_show_roles",
11329    schema: MZ_INTERNAL_SCHEMA,
11330    oid: oid::VIEW_MZ_SHOW_ROLES_OID,
11331    desc: RelationDesc::builder()
11332        .with_column("name", SqlScalarType::String.nullable(false))
11333        .with_column("comment", SqlScalarType::String.nullable(false))
11334        .finish(),
11335    column_comments: BTreeMap::new(),
11336    sql: "WITH comments AS (
11337        SELECT id, comment
11338        FROM mz_internal.mz_comments
11339        WHERE object_type = 'role' AND object_sub_id IS NULL
11340    )
11341    SELECT name, COALESCE(comment, '') as comment
11342    FROM mz_catalog.mz_roles roles
11343    LEFT JOIN comments ON roles.id = comments.id
11344    WHERE roles.id NOT LIKE 's%'
11345      AND roles.id NOT LIKE 'g%'",
11346    access: vec![PUBLIC_SELECT],
11347});
11348
11349pub static MZ_SHOW_TABLES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11350    name: "mz_show_tables",
11351    schema: MZ_INTERNAL_SCHEMA,
11352    oid: oid::VIEW_MZ_SHOW_TABLES_OID,
11353    desc: RelationDesc::builder()
11354        .with_column("schema_id", SqlScalarType::String.nullable(false))
11355        .with_column("name", SqlScalarType::String.nullable(false))
11356        .with_column("comment", SqlScalarType::String.nullable(false))
11357        .with_column("source_id", SqlScalarType::String.nullable(true))
11358        .finish(),
11359    column_comments: BTreeMap::new(),
11360    sql: "WITH comments AS (
11361        SELECT id, comment
11362        FROM mz_internal.mz_comments
11363        WHERE object_type = 'table' AND object_sub_id IS NULL
11364    )
11365    SELECT schema_id, name, COALESCE(comment, '') as comment, source_id
11366    FROM mz_catalog.mz_tables tables
11367    LEFT JOIN comments ON tables.id = comments.id",
11368    access: vec![PUBLIC_SELECT],
11369});
11370
11371pub static MZ_SHOW_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11372    name: "mz_show_views",
11373    schema: MZ_INTERNAL_SCHEMA,
11374    oid: oid::VIEW_MZ_SHOW_VIEWS_OID,
11375    desc: RelationDesc::builder()
11376        .with_column("schema_id", SqlScalarType::String.nullable(false))
11377        .with_column("name", SqlScalarType::String.nullable(false))
11378        .with_column("comment", SqlScalarType::String.nullable(false))
11379        .finish(),
11380    column_comments: BTreeMap::new(),
11381    sql: "WITH comments AS (
11382        SELECT id, comment
11383        FROM mz_internal.mz_comments
11384        WHERE object_type = 'view' AND object_sub_id IS NULL
11385    )
11386    SELECT schema_id, name, COALESCE(comment, '') as comment
11387    FROM mz_catalog.mz_views views
11388    LEFT JOIN comments ON views.id = comments.id",
11389    access: vec![PUBLIC_SELECT],
11390});
11391
11392pub static MZ_SHOW_TYPES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11393    name: "mz_show_types",
11394    schema: MZ_INTERNAL_SCHEMA,
11395    oid: oid::VIEW_MZ_SHOW_TYPES_OID,
11396    desc: RelationDesc::builder()
11397        .with_column("schema_id", SqlScalarType::String.nullable(false))
11398        .with_column("name", SqlScalarType::String.nullable(false))
11399        .with_column("comment", SqlScalarType::String.nullable(false))
11400        .finish(),
11401    column_comments: BTreeMap::new(),
11402    sql: "WITH comments AS (
11403        SELECT id, comment
11404        FROM mz_internal.mz_comments
11405        WHERE object_type = 'type' AND object_sub_id IS NULL
11406    )
11407    SELECT schema_id, name, COALESCE(comment, '') as comment
11408    FROM mz_catalog.mz_types types
11409    LEFT JOIN comments ON types.id = comments.id",
11410    access: vec![PUBLIC_SELECT],
11411});
11412
11413pub static MZ_SHOW_CONNECTIONS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11414    name: "mz_show_connections",
11415    schema: MZ_INTERNAL_SCHEMA,
11416    oid: oid::VIEW_MZ_SHOW_CONNECTIONS_OID,
11417    desc: RelationDesc::builder()
11418        .with_column("schema_id", SqlScalarType::String.nullable(false))
11419        .with_column("name", SqlScalarType::String.nullable(false))
11420        .with_column("type", SqlScalarType::String.nullable(false))
11421        .with_column("comment", SqlScalarType::String.nullable(false))
11422        .finish(),
11423    column_comments: BTreeMap::new(),
11424    sql: "WITH comments AS (
11425        SELECT id, comment
11426        FROM mz_internal.mz_comments
11427        WHERE object_type = 'connection' AND object_sub_id IS NULL
11428    )
11429    SELECT schema_id, name, type, COALESCE(comment, '') as comment
11430    FROM mz_catalog.mz_connections connections
11431    LEFT JOIN comments ON connections.id = comments.id",
11432    access: vec![PUBLIC_SELECT],
11433});
11434
11435pub static MZ_SHOW_SOURCES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11436    name: "mz_show_sources",
11437    schema: MZ_INTERNAL_SCHEMA,
11438    oid: oid::VIEW_MZ_SHOW_SOURCES_OID,
11439    desc: RelationDesc::builder()
11440        .with_column("id", SqlScalarType::String.nullable(false))
11441        .with_column("name", SqlScalarType::String.nullable(false))
11442        .with_column("type", SqlScalarType::String.nullable(false))
11443        .with_column("cluster", SqlScalarType::String.nullable(true))
11444        .with_column("schema_id", SqlScalarType::String.nullable(false))
11445        .with_column("cluster_id", SqlScalarType::String.nullable(true))
11446        .with_column("comment", SqlScalarType::String.nullable(false))
11447        .finish(),
11448    column_comments: BTreeMap::new(),
11449    sql: "
11450WITH comments AS (
11451    SELECT id, comment
11452    FROM mz_internal.mz_comments
11453    WHERE object_type = 'source' AND object_sub_id IS NULL
11454)
11455SELECT
11456    sources.id,
11457    sources.name,
11458    sources.type,
11459    clusters.name AS cluster,
11460    schema_id,
11461    cluster_id,
11462    COALESCE(comments.comment, '') as comment
11463FROM
11464    mz_catalog.mz_sources AS sources
11465        LEFT JOIN
11466            mz_catalog.mz_clusters AS clusters
11467            ON clusters.id = sources.cluster_id
11468        LEFT JOIN comments ON sources.id = comments.id",
11469    access: vec![PUBLIC_SELECT],
11470});
11471
11472pub static MZ_SHOW_SINKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11473    name: "mz_show_sinks",
11474    schema: MZ_INTERNAL_SCHEMA,
11475    oid: oid::VIEW_MZ_SHOW_SINKS_OID,
11476    desc: RelationDesc::builder()
11477        .with_column("id", SqlScalarType::String.nullable(false))
11478        .with_column("name", SqlScalarType::String.nullable(false))
11479        .with_column("type", SqlScalarType::String.nullable(false))
11480        .with_column("cluster", SqlScalarType::String.nullable(false))
11481        .with_column("schema_id", SqlScalarType::String.nullable(false))
11482        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11483        .with_column("comment", SqlScalarType::String.nullable(false))
11484        .finish(),
11485    column_comments: BTreeMap::new(),
11486    sql: "
11487WITH comments AS (
11488    SELECT id, comment
11489    FROM mz_internal.mz_comments
11490    WHERE object_type = 'sink' AND object_sub_id IS NULL
11491)
11492SELECT
11493    sinks.id,
11494    sinks.name,
11495    sinks.type,
11496    clusters.name AS cluster,
11497    schema_id,
11498    cluster_id,
11499    COALESCE(comments.comment, '') as comment
11500FROM
11501    mz_catalog.mz_sinks AS sinks
11502    JOIN
11503        mz_catalog.mz_clusters AS clusters
11504        ON clusters.id = sinks.cluster_id
11505    LEFT JOIN comments ON sinks.id = comments.id",
11506    access: vec![PUBLIC_SELECT],
11507});
11508
11509pub static MZ_SHOW_MATERIALIZED_VIEWS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11510    name: "mz_show_materialized_views",
11511    schema: MZ_INTERNAL_SCHEMA,
11512    oid: oid::VIEW_MZ_SHOW_MATERIALIZED_VIEWS_OID,
11513    desc: RelationDesc::builder()
11514        .with_column("id", SqlScalarType::String.nullable(false))
11515        .with_column("name", SqlScalarType::String.nullable(false))
11516        .with_column("cluster", SqlScalarType::String.nullable(false))
11517        .with_column("schema_id", SqlScalarType::String.nullable(false))
11518        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11519        .with_column("comment", SqlScalarType::String.nullable(false))
11520        .finish(),
11521    column_comments: BTreeMap::new(),
11522    sql: "
11523WITH
11524    comments AS (
11525        SELECT id, comment
11526        FROM mz_internal.mz_comments
11527        WHERE object_type = 'materialized-view' AND object_sub_id IS NULL
11528    )
11529SELECT
11530    mviews.id as id,
11531    mviews.name,
11532    clusters.name AS cluster,
11533    schema_id,
11534    cluster_id,
11535    COALESCE(comments.comment, '') as comment
11536FROM
11537    mz_catalog.mz_materialized_views AS mviews
11538    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = mviews.cluster_id
11539    LEFT JOIN comments ON mviews.id = comments.id",
11540    access: vec![PUBLIC_SELECT],
11541});
11542
11543pub static MZ_SHOW_INDEXES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11544    name: "mz_show_indexes",
11545    schema: MZ_INTERNAL_SCHEMA,
11546    oid: oid::VIEW_MZ_SHOW_INDEXES_OID,
11547    desc: RelationDesc::builder()
11548        .with_column("id", SqlScalarType::String.nullable(false))
11549        .with_column("name", SqlScalarType::String.nullable(false))
11550        .with_column("on", SqlScalarType::String.nullable(false))
11551        .with_column("cluster", SqlScalarType::String.nullable(false))
11552        .with_column(
11553            "key",
11554            SqlScalarType::Array(Box::new(SqlScalarType::String)).nullable(false),
11555        )
11556        .with_column("on_id", SqlScalarType::String.nullable(false))
11557        .with_column("schema_id", SqlScalarType::String.nullable(false))
11558        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11559        .with_column("comment", SqlScalarType::String.nullable(false))
11560        .finish(),
11561    column_comments: BTreeMap::new(),
11562    sql: "
11563WITH comments AS (
11564    SELECT id, comment
11565    FROM mz_internal.mz_comments
11566    WHERE object_type = 'index' AND object_sub_id IS NULL
11567)
11568SELECT
11569    idxs.id AS id,
11570    idxs.name AS name,
11571    objs.name AS on,
11572    clusters.name AS cluster,
11573    COALESCE(keys.key, '{}'::_text) AS key,
11574    idxs.on_id AS on_id,
11575    objs.schema_id AS schema_id,
11576    clusters.id AS cluster_id,
11577    COALESCE(comments.comment, '') as comment
11578FROM
11579    mz_catalog.mz_indexes AS idxs
11580    JOIN mz_catalog.mz_objects AS objs ON idxs.on_id = objs.id
11581    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = idxs.cluster_id
11582    LEFT JOIN
11583        (SELECT
11584            idxs.id,
11585            ARRAY_AGG(
11586                CASE
11587                    WHEN idx_cols.on_expression IS NULL THEN obj_cols.name
11588                    ELSE idx_cols.on_expression
11589                END
11590                ORDER BY idx_cols.index_position ASC
11591            ) AS key
11592        FROM
11593            mz_catalog.mz_indexes AS idxs
11594            JOIN mz_catalog.mz_index_columns idx_cols ON idxs.id = idx_cols.index_id
11595            LEFT JOIN mz_catalog.mz_columns obj_cols ON
11596                idxs.on_id = obj_cols.id AND idx_cols.on_position = obj_cols.position
11597        GROUP BY idxs.id) AS keys
11598    ON idxs.id = keys.id
11599    LEFT JOIN comments ON idxs.id = comments.id",
11600    access: vec![PUBLIC_SELECT],
11601});
11602
11603pub static MZ_SHOW_CLUSTER_REPLICAS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11604    name: "mz_show_cluster_replicas",
11605    schema: MZ_INTERNAL_SCHEMA,
11606    oid: oid::VIEW_MZ_SHOW_CLUSTER_REPLICAS_OID,
11607    desc: RelationDesc::builder()
11608        .with_column("cluster", SqlScalarType::String.nullable(false))
11609        .with_column("replica", SqlScalarType::String.nullable(false))
11610        .with_column("replica_id", SqlScalarType::String.nullable(false))
11611        .with_column("size", SqlScalarType::String.nullable(true))
11612        .with_column("ready", SqlScalarType::Bool.nullable(false))
11613        .with_column("comment", SqlScalarType::String.nullable(false))
11614        .finish(),
11615    column_comments: BTreeMap::new(),
11616    sql: r#"SELECT
11617    mz_catalog.mz_clusters.name AS cluster,
11618    mz_catalog.mz_cluster_replicas.name AS replica,
11619    mz_catalog.mz_cluster_replicas.id as replica_id,
11620    mz_catalog.mz_cluster_replicas.size AS size,
11621    coalesce(statuses.ready, FALSE) AS ready,
11622    coalesce(comments.comment, '') as comment
11623FROM
11624    mz_catalog.mz_cluster_replicas
11625        JOIN mz_catalog.mz_clusters
11626            ON mz_catalog.mz_cluster_replicas.cluster_id = mz_catalog.mz_clusters.id
11627        LEFT JOIN
11628            (
11629                SELECT
11630                    replica_id,
11631                    bool_and(hydrated) AS ready
11632                FROM mz_internal.mz_hydration_statuses
11633                WHERE replica_id is not null
11634                GROUP BY replica_id
11635            ) AS statuses
11636            ON mz_catalog.mz_cluster_replicas.id = statuses.replica_id
11637        LEFT JOIN mz_internal.mz_comments comments
11638            ON mz_catalog.mz_cluster_replicas.id = comments.id
11639WHERE (comments.object_type = 'cluster-replica' OR comments.object_type IS NULL)
11640ORDER BY 1, 2"#,
11641    access: vec![PUBLIC_SELECT],
11642});
11643
11644pub static MZ_SHOW_CONTINUAL_TASKS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11645    name: "mz_show_continual_tasks",
11646    schema: MZ_INTERNAL_SCHEMA,
11647    oid: oid::VIEW_MZ_SHOW_CONTINUAL_TASKS_OID,
11648    desc: RelationDesc::builder()
11649        .with_column("id", SqlScalarType::String.nullable(false))
11650        .with_column("name", SqlScalarType::String.nullable(false))
11651        .with_column("cluster", SqlScalarType::String.nullable(false))
11652        .with_column("schema_id", SqlScalarType::String.nullable(false))
11653        .with_column("cluster_id", SqlScalarType::String.nullable(false))
11654        .with_column("comment", SqlScalarType::String.nullable(false))
11655        .finish(),
11656    column_comments: BTreeMap::new(),
11657    sql: "
11658WITH comments AS (
11659    SELECT id, comment
11660    FROM mz_internal.mz_comments
11661    WHERE object_type = 'continual-task' AND object_sub_id IS NULL
11662)
11663SELECT
11664    cts.id as id,
11665    cts.name,
11666    clusters.name AS cluster,
11667    schema_id,
11668    cluster_id,
11669    COALESCE(comments.comment, '') as comment
11670FROM
11671    mz_internal.mz_continual_tasks AS cts
11672    JOIN mz_catalog.mz_clusters AS clusters ON clusters.id = cts.cluster_id
11673    LEFT JOIN comments ON cts.id = comments.id",
11674    access: vec![PUBLIC_SELECT],
11675});
11676
11677/// Lightweight data product discovery for MCP (Model Context Protocol).
11678///
11679/// Lists materialized views and indexed views that the current user has
11680/// SELECT privileges on. Non-indexed regular views are excluded because
11681/// querying them would trigger a full recompute. Comments are optional
11682/// enrichment.
11683/// Used by the `get_data_products` and `read_data_product` MCP tools.
11684/// Does not include schema details: use `mz_mcp_data_product_details` for that.
11685pub static MZ_MCP_DATA_PRODUCTS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11686    name: "mz_mcp_data_products",
11687    schema: MZ_INTERNAL_SCHEMA,
11688    oid: oid::VIEW_MZ_MCP_DATA_PRODUCTS_OID,
11689    desc: RelationDesc::builder()
11690        .with_column("object_name", SqlScalarType::String.nullable(false))
11691        .with_column("cluster", SqlScalarType::String.nullable(true))
11692        .with_column("description", SqlScalarType::String.nullable(true))
11693        .with_key(vec![0, 1, 2])
11694        .finish(),
11695    column_comments: BTreeMap::from_iter([
11696        (
11697            "object_name",
11698            "Fully qualified object name (database.schema.name).",
11699        ),
11700        (
11701            "cluster",
11702            "Cluster where the object computes or its index is hosted. The object can be read from any cluster.",
11703        ),
11704        (
11705            "description",
11706            "Index comment if available, otherwise object comment. Used as data product description.",
11707        ),
11708    ]),
11709    sql: r#"
11710SELECT DISTINCT
11711    '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS object_name,
11712    COALESCE(c_idx.name, c_obj.name) AS cluster,
11713    COALESCE(cts_idx.comment, cts_obj.comment) AS description
11714FROM mz_internal.mz_show_my_object_privileges op
11715JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type
11716JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id
11717JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id
11718LEFT JOIN mz_indexes i ON i.on_id = o.id
11719LEFT JOIN mz_clusters c_idx ON c_idx.id = i.cluster_id
11720LEFT JOIN mz_clusters c_obj ON c_obj.id = o.cluster_id
11721LEFT JOIN mz_internal.mz_comments cts_idx ON cts_idx.id = i.id AND cts_idx.object_sub_id IS NULL
11722LEFT JOIN mz_internal.mz_comments cts_obj ON cts_obj.id = o.id AND cts_obj.object_sub_id IS NULL
11723WHERE op.privilege_type = 'SELECT'
11724  AND (o.type = 'materialized-view' OR (o.type = 'view' AND i.id IS NOT NULL))
11725  AND s.name NOT IN ('mz_catalog', 'mz_internal', 'pg_catalog', 'information_schema', 'mz_introspection')
11726"#,
11727    access: vec![PUBLIC_SELECT],
11728});
11729
11730/// Full data product details with JSON Schema for MCP agents.
11731///
11732/// Extends `mz_mcp_data_products` with column types, index keys (when
11733/// available), and column comments, formatted as a JSON Schema object.
11734/// Used by the `get_data_product_details` MCP tool. Lists materialized
11735/// views and indexed views; non-indexed regular views are excluded to
11736/// avoid triggering full recompute on query. Comments are optional
11737/// enrichment.
11738pub static MZ_MCP_DATA_PRODUCT_DETAILS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11739    name: "mz_mcp_data_product_details",
11740    schema: MZ_INTERNAL_SCHEMA,
11741    oid: oid::VIEW_MZ_MCP_DATA_PRODUCT_DETAILS_OID,
11742    desc: RelationDesc::builder()
11743        .with_column("object_name", SqlScalarType::String.nullable(false))
11744        .with_column("cluster", SqlScalarType::String.nullable(true))
11745        .with_column("description", SqlScalarType::String.nullable(true))
11746        .with_column("schema", SqlScalarType::Jsonb.nullable(false))
11747        .with_key(vec![0, 1, 2])
11748        .finish(),
11749    column_comments: BTreeMap::from_iter([
11750        (
11751            "object_name",
11752            "Fully qualified object name (database.schema.name).",
11753        ),
11754        (
11755            "cluster",
11756            "Cluster where the object computes or its index is hosted. The object can be read from any cluster.",
11757        ),
11758        (
11759            "description",
11760            "Index comment if available, otherwise object comment. Used as data product description.",
11761        ),
11762        (
11763            "schema",
11764            "JSON Schema describing the object's columns and types.",
11765        ),
11766    ]),
11767    sql: r#"
11768SELECT * FROM (
11769    SELECT
11770        '"' || op.database || '"."' || op.schema || '"."' || op.name || '"' AS object_name,
11771        COALESCE(c_idx.name, c_obj.name) AS cluster,
11772        COALESCE(cts_idx.comment, cts_obj.comment) AS description,
11773        COALESCE(jsonb_build_object(
11774        'type', 'object',
11775        'required', jsonb_agg(distinct ccol.name) FILTER (WHERE ccol.position = ic.on_position),
11776        'properties', jsonb_strip_nulls(jsonb_object_agg(
11777            ccol.name,
11778            CASE
11779                WHEN ccol.type IN (
11780                    'uint2', 'uint4','uint8', 'int', 'integer', 'smallint',
11781                    'double', 'double precision', 'bigint', 'float',
11782                    'numeric', 'real'
11783                ) THEN jsonb_build_object(
11784                    'type', 'number',
11785                    'description', cts_col.comment
11786                )
11787                WHEN ccol.type = 'boolean' THEN jsonb_build_object(
11788                    'type', 'boolean',
11789                    'description', cts_col.comment
11790                )
11791                WHEN ccol.type = 'bytea' THEN jsonb_build_object(
11792                    'type', 'string',
11793                    'description', cts_col.comment,
11794                    'contentEncoding', 'base64',
11795                    'contentMediaType', 'application/octet-stream'
11796                )
11797                WHEN ccol.type = 'date' THEN jsonb_build_object(
11798                    'type', 'string',
11799                    'format', 'date',
11800                    'description', cts_col.comment
11801                )
11802                WHEN ccol.type = 'time' THEN jsonb_build_object(
11803                    'type', 'string',
11804                    'format', 'time',
11805                    'description', cts_col.comment
11806                )
11807                WHEN ccol.type ilike 'timestamp%%' THEN jsonb_build_object(
11808                    'type', 'string',
11809                    'format', 'date-time',
11810                    'description', cts_col.comment
11811                )
11812                WHEN ccol.type = 'jsonb' THEN jsonb_build_object(
11813                    'type', 'object',
11814                    'description', cts_col.comment
11815                )
11816                WHEN ccol.type = 'uuid' THEN jsonb_build_object(
11817                    'type', 'string',
11818                    'format', 'uuid',
11819                    'description', cts_col.comment
11820                )
11821                ELSE jsonb_build_object(
11822                    'type', 'string',
11823                    'description', cts_col.comment
11824                )
11825            END
11826        ))
11827    ), '{"type": "object", "properties": {}}'::jsonb) AS schema
11828FROM mz_internal.mz_show_my_object_privileges op
11829JOIN mz_objects o ON op.name = o.name AND op.object_type = o.type
11830JOIN mz_schemas s ON s.name = op.schema AND s.id = o.schema_id
11831JOIN mz_databases d ON d.name = op.database AND d.id = s.database_id
11832JOIN mz_columns ccol ON ccol.id = o.id
11833LEFT JOIN mz_indexes i ON i.on_id = o.id
11834LEFT JOIN mz_index_columns ic ON i.id = ic.index_id
11835LEFT JOIN mz_clusters c_idx ON c_idx.id = i.cluster_id
11836LEFT JOIN mz_clusters c_obj ON c_obj.id = o.cluster_id
11837LEFT JOIN mz_internal.mz_comments cts_idx ON cts_idx.id = i.id AND cts_idx.object_sub_id IS NULL
11838LEFT JOIN mz_internal.mz_comments cts_obj ON cts_obj.id = o.id AND cts_obj.object_sub_id IS NULL
11839LEFT JOIN mz_internal.mz_comments cts_col ON cts_col.id = o.id AND cts_col.object_sub_id = ccol.position
11840WHERE op.privilege_type = 'SELECT'
11841  AND (o.type = 'materialized-view' OR (o.type = 'view' AND i.id IS NOT NULL))
11842  AND s.name NOT IN ('mz_catalog', 'mz_internal', 'pg_catalog', 'information_schema', 'mz_introspection')
11843GROUP BY 1, 2, 3
11844)
11845"#,
11846    access: vec![PUBLIC_SELECT],
11847});
11848
11849pub static MZ_SHOW_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11850    name: "mz_show_role_members",
11851    schema: MZ_INTERNAL_SCHEMA,
11852    oid: oid::VIEW_MZ_SHOW_ROLE_MEMBERS_OID,
11853    desc: RelationDesc::builder()
11854        .with_column("role", SqlScalarType::String.nullable(false))
11855        .with_column("member", SqlScalarType::String.nullable(false))
11856        .with_column("grantor", SqlScalarType::String.nullable(false))
11857        .finish(),
11858    column_comments: BTreeMap::from_iter([
11859        ("role", "The role that `member` is a member of."),
11860        ("member", "The role that is a member of `role`."),
11861        (
11862            "grantor",
11863            "The role that granted membership of `member` to `role`.",
11864        ),
11865    ]),
11866    sql: r#"SELECT
11867    r1.name AS role,
11868    r2.name AS member,
11869    r3.name AS grantor
11870FROM mz_catalog.mz_role_members rm
11871JOIN mz_catalog.mz_roles r1 ON r1.id = rm.role_id
11872JOIN mz_catalog.mz_roles r2 ON r2.id = rm.member
11873JOIN mz_catalog.mz_roles r3 ON r3.id = rm.grantor
11874ORDER BY role"#,
11875    access: vec![PUBLIC_SELECT],
11876});
11877
11878pub static MZ_SHOW_MY_ROLE_MEMBERS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11879    name: "mz_show_my_role_members",
11880    schema: MZ_INTERNAL_SCHEMA,
11881    oid: oid::VIEW_MZ_SHOW_MY_ROLE_MEMBERS_OID,
11882    desc: RelationDesc::builder()
11883        .with_column("role", SqlScalarType::String.nullable(false))
11884        .with_column("member", SqlScalarType::String.nullable(false))
11885        .with_column("grantor", SqlScalarType::String.nullable(false))
11886        .finish(),
11887    column_comments: BTreeMap::from_iter([
11888        ("role", "The role that `member` is a member of."),
11889        ("member", "The role that is a member of `role`."),
11890        (
11891            "grantor",
11892            "The role that granted membership of `member` to `role`.",
11893        ),
11894    ]),
11895    sql: r#"SELECT role, member, grantor
11896FROM mz_internal.mz_show_role_members
11897WHERE pg_has_role(member, 'USAGE')"#,
11898    access: vec![PUBLIC_SELECT],
11899});
11900
11901pub static MZ_SHOW_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11902    name: "mz_show_system_privileges",
11903    schema: MZ_INTERNAL_SCHEMA,
11904    oid: oid::VIEW_MZ_SHOW_SYSTEM_PRIVILEGES_OID,
11905    desc: RelationDesc::builder()
11906        .with_column("grantor", SqlScalarType::String.nullable(true))
11907        .with_column("grantee", SqlScalarType::String.nullable(true))
11908        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11909        .finish(),
11910    column_comments: BTreeMap::from_iter([
11911        ("grantor", "The role that granted the privilege."),
11912        ("grantee", "The role that the privilege was granted to."),
11913        ("privilege_type", "They type of privilege granted."),
11914    ]),
11915    sql: r#"SELECT
11916    grantor.name AS grantor,
11917    CASE privileges.grantee
11918        WHEN 'p' THEN 'PUBLIC'
11919        ELSE grantee.name
11920    END AS grantee,
11921    privileges.privilege_type AS privilege_type
11922FROM
11923    (SELECT mz_internal.mz_aclexplode(ARRAY[privileges]).*
11924    FROM mz_catalog.mz_system_privileges) AS privileges
11925LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11926LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11927WHERE privileges.grantee NOT LIKE 's%'"#,
11928    access: vec![PUBLIC_SELECT],
11929});
11930
11931pub static MZ_SHOW_MY_SYSTEM_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11932    name: "mz_show_my_system_privileges",
11933    schema: MZ_INTERNAL_SCHEMA,
11934    oid: oid::VIEW_MZ_SHOW_MY_SYSTEM_PRIVILEGES_OID,
11935    desc: RelationDesc::builder()
11936        .with_column("grantor", SqlScalarType::String.nullable(true))
11937        .with_column("grantee", SqlScalarType::String.nullable(true))
11938        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11939        .finish(),
11940    column_comments: BTreeMap::from_iter([
11941        ("grantor", "The role that granted the privilege."),
11942        ("grantee", "The role that the privilege was granted to."),
11943        ("privilege_type", "They type of privilege granted."),
11944    ]),
11945    sql: r#"SELECT grantor, grantee, privilege_type
11946FROM mz_internal.mz_show_system_privileges
11947WHERE
11948    CASE
11949        WHEN grantee = 'PUBLIC' THEN true
11950        ELSE pg_has_role(grantee, 'USAGE')
11951    END"#,
11952    access: vec![PUBLIC_SELECT],
11953});
11954
11955pub static MZ_SHOW_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11956    name: "mz_show_cluster_privileges",
11957    schema: MZ_INTERNAL_SCHEMA,
11958    oid: oid::VIEW_MZ_SHOW_CLUSTER_PRIVILEGES_OID,
11959    desc: RelationDesc::builder()
11960        .with_column("grantor", SqlScalarType::String.nullable(true))
11961        .with_column("grantee", SqlScalarType::String.nullable(true))
11962        .with_column("name", SqlScalarType::String.nullable(false))
11963        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11964        .finish(),
11965    column_comments: BTreeMap::from_iter([
11966        ("grantor", "The role that granted the privilege."),
11967        ("grantee", "The role that the privilege was granted to."),
11968        ("name", "The name of the cluster."),
11969        ("privilege_type", "They type of privilege granted."),
11970    ]),
11971    sql: r#"SELECT
11972    grantor.name AS grantor,
11973    CASE privileges.grantee
11974        WHEN 'p' THEN 'PUBLIC'
11975        ELSE grantee.name
11976    END AS grantee,
11977    privileges.name AS name,
11978    privileges.privilege_type AS privilege_type
11979FROM
11980    (SELECT mz_internal.mz_aclexplode(privileges).*, name
11981    FROM mz_catalog.mz_clusters
11982    WHERE id NOT LIKE 's%') AS privileges
11983LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
11984LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
11985WHERE privileges.grantee NOT LIKE 's%'"#,
11986    access: vec![PUBLIC_SELECT],
11987});
11988
11989pub static MZ_SHOW_MY_CLUSTER_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
11990    name: "mz_show_my_cluster_privileges",
11991    schema: MZ_INTERNAL_SCHEMA,
11992    oid: oid::VIEW_MZ_SHOW_MY_CLUSTER_PRIVILEGES_OID,
11993    desc: RelationDesc::builder()
11994        .with_column("grantor", SqlScalarType::String.nullable(true))
11995        .with_column("grantee", SqlScalarType::String.nullable(true))
11996        .with_column("name", SqlScalarType::String.nullable(false))
11997        .with_column("privilege_type", SqlScalarType::String.nullable(false))
11998        .finish(),
11999    column_comments: BTreeMap::from_iter([
12000        ("grantor", "The role that granted the privilege."),
12001        ("grantee", "The role that the privilege was granted to."),
12002        ("name", "The name of the cluster."),
12003        ("privilege_type", "They type of privilege granted."),
12004    ]),
12005    sql: r#"SELECT grantor, grantee, name, privilege_type
12006FROM mz_internal.mz_show_cluster_privileges
12007WHERE
12008    CASE
12009        WHEN grantee = 'PUBLIC' THEN true
12010        ELSE pg_has_role(grantee, 'USAGE')
12011    END"#,
12012    access: vec![PUBLIC_SELECT],
12013});
12014
12015pub static MZ_SHOW_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12016    name: "mz_show_database_privileges",
12017    schema: MZ_INTERNAL_SCHEMA,
12018    oid: oid::VIEW_MZ_SHOW_DATABASE_PRIVILEGES_OID,
12019    desc: RelationDesc::builder()
12020        .with_column("grantor", SqlScalarType::String.nullable(true))
12021        .with_column("grantee", SqlScalarType::String.nullable(true))
12022        .with_column("name", SqlScalarType::String.nullable(false))
12023        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12024        .finish(),
12025    column_comments: BTreeMap::from_iter([
12026        ("grantor", "The role that granted the privilege."),
12027        ("grantee", "The role that the privilege was granted to."),
12028        ("name", "The name of the database."),
12029        ("privilege_type", "They type of privilege granted."),
12030    ]),
12031    sql: r#"SELECT
12032    grantor.name AS grantor,
12033    CASE privileges.grantee
12034        WHEN 'p' THEN 'PUBLIC'
12035        ELSE grantee.name
12036    END AS grantee,
12037    privileges.name AS name,
12038    privileges.privilege_type AS privilege_type
12039FROM
12040    (SELECT mz_internal.mz_aclexplode(privileges).*, name
12041    FROM mz_catalog.mz_databases
12042    WHERE id NOT LIKE 's%') AS privileges
12043LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
12044LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
12045WHERE privileges.grantee NOT LIKE 's%'"#,
12046    access: vec![PUBLIC_SELECT],
12047});
12048
12049pub static MZ_SHOW_MY_DATABASE_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12050    name: "mz_show_my_database_privileges",
12051    schema: MZ_INTERNAL_SCHEMA,
12052    oid: oid::VIEW_MZ_SHOW_MY_DATABASE_PRIVILEGES_OID,
12053    desc: RelationDesc::builder()
12054        .with_column("grantor", SqlScalarType::String.nullable(true))
12055        .with_column("grantee", SqlScalarType::String.nullable(true))
12056        .with_column("name", SqlScalarType::String.nullable(false))
12057        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12058        .finish(),
12059    column_comments: BTreeMap::from_iter([
12060        ("grantor", "The role that granted the privilege."),
12061        ("grantee", "The role that the privilege was granted to."),
12062        ("name", "The name of the cluster."),
12063        ("privilege_type", "They type of privilege granted."),
12064    ]),
12065    sql: r#"SELECT grantor, grantee, name, privilege_type
12066FROM mz_internal.mz_show_database_privileges
12067WHERE
12068    CASE
12069        WHEN grantee = 'PUBLIC' THEN true
12070        ELSE pg_has_role(grantee, 'USAGE')
12071    END"#,
12072    access: vec![PUBLIC_SELECT],
12073});
12074
12075pub static MZ_SHOW_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12076    name: "mz_show_schema_privileges",
12077    schema: MZ_INTERNAL_SCHEMA,
12078    oid: oid::VIEW_MZ_SHOW_SCHEMA_PRIVILEGES_OID,
12079    desc: RelationDesc::builder()
12080        .with_column("grantor", SqlScalarType::String.nullable(true))
12081        .with_column("grantee", SqlScalarType::String.nullable(true))
12082        .with_column("database", SqlScalarType::String.nullable(true))
12083        .with_column("name", SqlScalarType::String.nullable(false))
12084        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12085        .finish(),
12086    column_comments: BTreeMap::from_iter([
12087        ("grantor", "The role that granted the privilege."),
12088        ("grantee", "The role that the privilege was granted to."),
12089        (
12090            "database",
12091            "The name of the database containing the schema.",
12092        ),
12093        ("name", "The name of the schema."),
12094        ("privilege_type", "They type of privilege granted."),
12095    ]),
12096    sql: r#"SELECT
12097    grantor.name AS grantor,
12098    CASE privileges.grantee
12099        WHEN 'p' THEN 'PUBLIC'
12100        ELSE grantee.name
12101    END AS grantee,
12102    databases.name AS database,
12103    privileges.name AS name,
12104    privileges.privilege_type AS privilege_type
12105FROM
12106    (SELECT mz_internal.mz_aclexplode(privileges).*, database_id, name
12107    FROM mz_catalog.mz_schemas
12108    WHERE id NOT LIKE 's%') AS privileges
12109LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
12110LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
12111LEFT JOIN mz_catalog.mz_databases databases ON privileges.database_id = databases.id
12112WHERE privileges.grantee NOT LIKE 's%'"#,
12113    access: vec![PUBLIC_SELECT],
12114});
12115
12116pub static MZ_SHOW_MY_SCHEMA_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12117    name: "mz_show_my_schema_privileges",
12118    schema: MZ_INTERNAL_SCHEMA,
12119    oid: oid::VIEW_MZ_SHOW_MY_SCHEMA_PRIVILEGES_OID,
12120    desc: RelationDesc::builder()
12121        .with_column("grantor", SqlScalarType::String.nullable(true))
12122        .with_column("grantee", SqlScalarType::String.nullable(true))
12123        .with_column("database", SqlScalarType::String.nullable(true))
12124        .with_column("name", SqlScalarType::String.nullable(false))
12125        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12126        .finish(),
12127    column_comments: BTreeMap::from_iter([
12128        ("grantor", "The role that granted the privilege."),
12129        ("grantee", "The role that the privilege was granted to."),
12130        (
12131            "database",
12132            "The name of the database containing the schema.",
12133        ),
12134        ("name", "The name of the schema."),
12135        ("privilege_type", "They type of privilege granted."),
12136    ]),
12137    sql: r#"SELECT grantor, grantee, database, name, privilege_type
12138FROM mz_internal.mz_show_schema_privileges
12139WHERE
12140    CASE
12141        WHEN grantee = 'PUBLIC' THEN true
12142        ELSE pg_has_role(grantee, 'USAGE')
12143    END"#,
12144    access: vec![PUBLIC_SELECT],
12145});
12146
12147pub static MZ_SHOW_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12148    name: "mz_show_object_privileges",
12149    schema: MZ_INTERNAL_SCHEMA,
12150    oid: oid::VIEW_MZ_SHOW_OBJECT_PRIVILEGES_OID,
12151    desc: RelationDesc::builder()
12152        .with_column("grantor", SqlScalarType::String.nullable(true))
12153        .with_column("grantee", SqlScalarType::String.nullable(true))
12154        .with_column("database", SqlScalarType::String.nullable(true))
12155        .with_column("schema", SqlScalarType::String.nullable(true))
12156        .with_column("name", SqlScalarType::String.nullable(false))
12157        .with_column("object_type", SqlScalarType::String.nullable(false))
12158        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12159        .finish(),
12160    column_comments: BTreeMap::from_iter([
12161        ("grantor", "The role that granted the privilege."),
12162        ("grantee", "The role that the privilege was granted to."),
12163        (
12164            "database",
12165            "The name of the database containing the object.",
12166        ),
12167        ("schema", "The name of the schema containing the object."),
12168        ("name", "The name of the object."),
12169        (
12170            "object_type",
12171            "The type of object the privilege is granted on.",
12172        ),
12173        ("privilege_type", "They type of privilege granted."),
12174    ]),
12175    sql: r#"SELECT
12176    grantor.name AS grantor,
12177    CASE privileges.grantee
12178            WHEN 'p' THEN 'PUBLIC'
12179            ELSE grantee.name
12180        END AS grantee,
12181    databases.name AS database,
12182    schemas.name AS schema,
12183    privileges.name AS name,
12184    privileges.type AS object_type,
12185    privileges.privilege_type AS privilege_type
12186FROM
12187    (SELECT mz_internal.mz_aclexplode(privileges).*, schema_id, name, type
12188    FROM mz_catalog.mz_objects
12189    WHERE id NOT LIKE 's%') AS privileges
12190LEFT JOIN mz_catalog.mz_roles grantor ON privileges.grantor = grantor.id
12191LEFT JOIN mz_catalog.mz_roles grantee ON privileges.grantee = grantee.id
12192LEFT JOIN mz_catalog.mz_schemas schemas ON privileges.schema_id = schemas.id
12193LEFT JOIN mz_catalog.mz_databases databases ON schemas.database_id = databases.id
12194WHERE privileges.grantee NOT LIKE 's%'"#,
12195    access: vec![PUBLIC_SELECT],
12196});
12197
12198pub static MZ_SHOW_MY_OBJECT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12199    name: "mz_show_my_object_privileges",
12200    schema: MZ_INTERNAL_SCHEMA,
12201    oid: oid::VIEW_MZ_SHOW_MY_OBJECT_PRIVILEGES_OID,
12202    desc: RelationDesc::builder()
12203        .with_column("grantor", SqlScalarType::String.nullable(true))
12204        .with_column("grantee", SqlScalarType::String.nullable(true))
12205        .with_column("database", SqlScalarType::String.nullable(true))
12206        .with_column("schema", SqlScalarType::String.nullable(true))
12207        .with_column("name", SqlScalarType::String.nullable(false))
12208        .with_column("object_type", SqlScalarType::String.nullable(false))
12209        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12210        .finish(),
12211    column_comments: BTreeMap::from_iter([
12212        ("grantor", "The role that granted the privilege."),
12213        ("grantee", "The role that the privilege was granted to."),
12214        (
12215            "database",
12216            "The name of the database containing the object.",
12217        ),
12218        ("schema", "The name of the schema containing the object."),
12219        ("name", "The name of the object."),
12220        (
12221            "object_type",
12222            "The type of object the privilege is granted on.",
12223        ),
12224        ("privilege_type", "They type of privilege granted."),
12225    ]),
12226    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12227FROM mz_internal.mz_show_object_privileges
12228WHERE
12229    CASE
12230        WHEN grantee = 'PUBLIC' THEN true
12231        ELSE pg_has_role(grantee, 'USAGE')
12232    END"#,
12233    access: vec![PUBLIC_SELECT],
12234});
12235
12236pub static MZ_SHOW_ALL_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12237    name: "mz_show_all_privileges",
12238    schema: MZ_INTERNAL_SCHEMA,
12239    oid: oid::VIEW_MZ_SHOW_ALL_PRIVILEGES_OID,
12240    desc: RelationDesc::builder()
12241        .with_column("grantor", SqlScalarType::String.nullable(true))
12242        .with_column("grantee", SqlScalarType::String.nullable(true))
12243        .with_column("database", SqlScalarType::String.nullable(true))
12244        .with_column("schema", SqlScalarType::String.nullable(true))
12245        .with_column("name", SqlScalarType::String.nullable(true))
12246        .with_column("object_type", SqlScalarType::String.nullable(false))
12247        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12248        .finish(),
12249    column_comments: BTreeMap::from_iter([
12250        ("grantor", "The role that granted the privilege."),
12251        ("grantee", "The role that the privilege was granted to."),
12252        (
12253            "database",
12254            "The name of the database containing the object.",
12255        ),
12256        ("schema", "The name of the schema containing the object."),
12257        ("name", "The name of the privilege target."),
12258        (
12259            "object_type",
12260            "The type of object the privilege is granted on.",
12261        ),
12262        ("privilege_type", "They type of privilege granted."),
12263    ]),
12264    sql: r#"SELECT grantor, grantee, NULL AS database, NULL AS schema, NULL AS name, 'system' AS object_type, privilege_type
12265FROM mz_internal.mz_show_system_privileges
12266UNION ALL
12267SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'cluster' AS object_type, privilege_type
12268FROM mz_internal.mz_show_cluster_privileges
12269UNION ALL
12270SELECT grantor, grantee, NULL AS database, NULL AS schema, name, 'database' AS object_type, privilege_type
12271FROM mz_internal.mz_show_database_privileges
12272UNION ALL
12273SELECT grantor, grantee, database, NULL AS schema, name, 'schema' AS object_type, privilege_type
12274FROM mz_internal.mz_show_schema_privileges
12275UNION ALL
12276SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12277FROM mz_internal.mz_show_object_privileges"#,
12278    access: vec![PUBLIC_SELECT],
12279});
12280
12281pub static MZ_SHOW_ALL_MY_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12282    name: "mz_show_all_my_privileges",
12283    schema: MZ_INTERNAL_SCHEMA,
12284    oid: oid::VIEW_MZ_SHOW_ALL_MY_PRIVILEGES_OID,
12285    desc: RelationDesc::builder()
12286        .with_column("grantor", SqlScalarType::String.nullable(true))
12287        .with_column("grantee", SqlScalarType::String.nullable(true))
12288        .with_column("database", SqlScalarType::String.nullable(true))
12289        .with_column("schema", SqlScalarType::String.nullable(true))
12290        .with_column("name", SqlScalarType::String.nullable(true))
12291        .with_column("object_type", SqlScalarType::String.nullable(false))
12292        .with_column("privilege_type", SqlScalarType::String.nullable(false))
12293        .finish(),
12294    column_comments: BTreeMap::from_iter([
12295        ("grantor", "The role that granted the privilege."),
12296        ("grantee", "The role that the privilege was granted to."),
12297        (
12298            "database",
12299            "The name of the database containing the object.",
12300        ),
12301        ("schema", "The name of the schema containing the object."),
12302        ("name", "The name of the privilege target."),
12303        (
12304            "object_type",
12305            "The type of object the privilege is granted on.",
12306        ),
12307        ("privilege_type", "They type of privilege granted."),
12308    ]),
12309    sql: r#"SELECT grantor, grantee, database, schema, name, object_type, privilege_type
12310FROM mz_internal.mz_show_all_privileges
12311WHERE
12312    CASE
12313        WHEN grantee = 'PUBLIC' THEN true
12314        ELSE pg_has_role(grantee, 'USAGE')
12315    END"#,
12316    access: vec![PUBLIC_SELECT],
12317});
12318
12319pub static MZ_SHOW_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12320    name: "mz_show_default_privileges",
12321    schema: MZ_INTERNAL_SCHEMA,
12322    oid: oid::VIEW_MZ_SHOW_DEFAULT_PRIVILEGES_OID,
12323    desc: RelationDesc::builder()
12324        .with_column("object_owner", SqlScalarType::String.nullable(true))
12325        .with_column("database", SqlScalarType::String.nullable(true))
12326        .with_column("schema", SqlScalarType::String.nullable(true))
12327        .with_column("object_type", SqlScalarType::String.nullable(false))
12328        .with_column("grantee", SqlScalarType::String.nullable(true))
12329        .with_column("privilege_type", SqlScalarType::String.nullable(true))
12330        .finish(),
12331    column_comments: BTreeMap::from_iter([
12332        (
12333            "object_owner",
12334            "Privileges described in this row will be granted on objects created by `object_owner`.",
12335        ),
12336        (
12337            "database",
12338            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
12339        ),
12340        (
12341            "schema",
12342            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
12343        ),
12344        (
12345            "object_type",
12346            "Privileges described in this row will be granted only on objects of type `object_type`.",
12347        ),
12348        (
12349            "grantee",
12350            "Privileges described in this row will be granted to `grantee`.",
12351        ),
12352        ("privilege_type", "They type of privilege to be granted."),
12353    ]),
12354    sql: r#"SELECT
12355    CASE defaults.role_id
12356        WHEN 'p' THEN 'PUBLIC'
12357        ELSE object_owner.name
12358    END AS object_owner,
12359    databases.name AS database,
12360    schemas.name AS schema,
12361    object_type,
12362    CASE defaults.grantee
12363        WHEN 'p' THEN 'PUBLIC'
12364        ELSE grantee.name
12365    END AS grantee,
12366    unnest(mz_internal.mz_format_privileges(defaults.privileges)) AS privilege_type
12367FROM mz_catalog.mz_default_privileges defaults
12368LEFT JOIN mz_catalog.mz_roles AS object_owner ON defaults.role_id = object_owner.id
12369LEFT JOIN mz_catalog.mz_roles AS grantee ON defaults.grantee = grantee.id
12370LEFT JOIN mz_catalog.mz_databases AS databases ON defaults.database_id = databases.id
12371LEFT JOIN mz_catalog.mz_schemas AS schemas ON defaults.schema_id = schemas.id
12372WHERE defaults.grantee NOT LIKE 's%'
12373    AND defaults.database_id IS NULL OR defaults.database_id NOT LIKE 's%'
12374    AND defaults.schema_id IS NULL OR defaults.schema_id NOT LIKE 's%'"#,
12375    access: vec![PUBLIC_SELECT],
12376});
12377
12378pub static MZ_SHOW_MY_DEFAULT_PRIVILEGES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12379    name: "mz_show_my_default_privileges",
12380    schema: MZ_INTERNAL_SCHEMA,
12381    oid: oid::VIEW_MZ_SHOW_MY_DEFAULT_PRIVILEGES_OID,
12382    desc: RelationDesc::builder()
12383        .with_column("object_owner", SqlScalarType::String.nullable(true))
12384        .with_column("database", SqlScalarType::String.nullable(true))
12385        .with_column("schema", SqlScalarType::String.nullable(true))
12386        .with_column("object_type", SqlScalarType::String.nullable(false))
12387        .with_column("grantee", SqlScalarType::String.nullable(true))
12388        .with_column("privilege_type", SqlScalarType::String.nullable(true))
12389        .finish(),
12390    column_comments: BTreeMap::from_iter([
12391        (
12392            "object_owner",
12393            "Privileges described in this row will be granted on objects created by `object_owner`.",
12394        ),
12395        (
12396            "database",
12397            "Privileges described in this row will be granted only on objects created in `database` if non-null.",
12398        ),
12399        (
12400            "schema",
12401            "Privileges described in this row will be granted only on objects created in `schema` if non-null.",
12402        ),
12403        (
12404            "object_type",
12405            "Privileges described in this row will be granted only on objects of type `object_type`.",
12406        ),
12407        (
12408            "grantee",
12409            "Privileges described in this row will be granted to `grantee`.",
12410        ),
12411        ("privilege_type", "They type of privilege to be granted."),
12412    ]),
12413    sql: r#"SELECT object_owner, database, schema, object_type, grantee, privilege_type
12414FROM mz_internal.mz_show_default_privileges
12415WHERE
12416    CASE
12417        WHEN grantee = 'PUBLIC' THEN true
12418        ELSE pg_has_role(grantee, 'USAGE')
12419    END"#,
12420    access: vec![PUBLIC_SELECT],
12421});
12422
12423pub static MZ_SHOW_NETWORK_POLICIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12424    name: "mz_show_network_policies",
12425    schema: MZ_INTERNAL_SCHEMA,
12426    oid: oid::VIEW_MZ_SHOW_NETWORK_POLICIES_OID,
12427    desc: RelationDesc::builder()
12428        .with_column("name", SqlScalarType::String.nullable(false))
12429        .with_column("rules", SqlScalarType::String.nullable(true))
12430        .with_column("comment", SqlScalarType::String.nullable(false))
12431        .finish(),
12432    column_comments: BTreeMap::new(),
12433    sql: "
12434WITH comments AS (
12435    SELECT id, comment
12436    FROM mz_internal.mz_comments
12437    WHERE object_type = 'network-policy' AND object_sub_id IS NULL
12438)
12439SELECT
12440    policy.name,
12441    pg_catalog.string_agg(rule.name,',' ORDER BY rule.name) as rules,
12442    COALESCE(comment, '') as comment
12443FROM
12444    mz_internal.mz_network_policies as policy
12445LEFT JOIN
12446    mz_internal.mz_network_policy_rules as rule ON policy.id = rule.policy_id
12447LEFT JOIN
12448    comments ON policy.id = comments.id
12449WHERE
12450    policy.id NOT LIKE 's%'
12451AND
12452    policy.id NOT LIKE 'g%'
12453GROUP BY policy.name, comments.comment;",
12454    access: vec![PUBLIC_SELECT],
12455});
12456
12457pub static MZ_CLUSTER_REPLICA_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12458    name: "mz_cluster_replica_history",
12459    schema: MZ_INTERNAL_SCHEMA,
12460    oid: oid::VIEW_MZ_CLUSTER_REPLICA_HISTORY_OID,
12461    desc: RelationDesc::builder()
12462        .with_column("replica_id", SqlScalarType::String.nullable(true))
12463        .with_column("size", SqlScalarType::String.nullable(true))
12464        .with_column("cluster_id", SqlScalarType::String.nullable(true))
12465        .with_column("cluster_name", SqlScalarType::String.nullable(true))
12466        .with_column("replica_name", SqlScalarType::String.nullable(true))
12467        .with_column(
12468            "created_at",
12469            SqlScalarType::TimestampTz { precision: None }.nullable(false),
12470        )
12471        .with_column(
12472            "dropped_at",
12473            SqlScalarType::TimestampTz { precision: None }.nullable(true),
12474        )
12475        .with_column(
12476            "credits_per_hour",
12477            SqlScalarType::Numeric { max_scale: None }.nullable(true),
12478        )
12479        .finish(),
12480    column_comments: BTreeMap::from_iter([
12481        ("replica_id", "The ID of a cluster replica."),
12482        (
12483            "size",
12484            "The size of the cluster replica. Corresponds to `mz_cluster_replica_sizes.size`.",
12485        ),
12486        (
12487            "cluster_id",
12488            "The ID of the cluster associated with the replica.",
12489        ),
12490        (
12491            "cluster_name",
12492            "The name of the cluster associated with the replica.",
12493        ),
12494        ("replica_name", "The name of the replica."),
12495        ("created_at", "The time at which the replica was created."),
12496        (
12497            "dropped_at",
12498            "The time at which the replica was dropped, or `NULL` if it still exists.",
12499        ),
12500        (
12501            "credits_per_hour",
12502            "The number of compute credits consumed per hour. Corresponds to `mz_cluster_replica_sizes.credits_per_hour`.",
12503        ),
12504    ]),
12505    sql: r#"
12506        WITH
12507            creates AS
12508            (
12509                SELECT
12510                    details ->> 'logical_size' AS size,
12511                    details ->> 'replica_id' AS replica_id,
12512                    details ->> 'replica_name' AS replica_name,
12513                    details ->> 'cluster_name' AS cluster_name,
12514                    details ->> 'cluster_id' AS cluster_id,
12515                    occurred_at
12516                FROM mz_catalog.mz_audit_events
12517                WHERE
12518                    object_type = 'cluster-replica' AND event_type = 'create'
12519                        AND
12520                    details ->> 'replica_id' IS NOT NULL
12521                        AND
12522                    details ->> 'cluster_id' !~~ 's%'
12523            ),
12524            drops AS
12525            (
12526                SELECT details ->> 'replica_id' AS replica_id, occurred_at
12527                FROM mz_catalog.mz_audit_events
12528                WHERE object_type = 'cluster-replica' AND event_type = 'drop'
12529            )
12530        SELECT
12531            creates.replica_id,
12532            creates.size,
12533            creates.cluster_id,
12534            creates.cluster_name,
12535            creates.replica_name,
12536            creates.occurred_at AS created_at,
12537            drops.occurred_at AS dropped_at,
12538            mz_cluster_replica_sizes.credits_per_hour as credits_per_hour
12539        FROM
12540            creates
12541                LEFT JOIN drops ON creates.replica_id = drops.replica_id
12542                LEFT JOIN
12543                    mz_catalog.mz_cluster_replica_sizes
12544                    ON mz_cluster_replica_sizes.size = creates.size"#,
12545    access: vec![PUBLIC_SELECT],
12546});
12547
12548pub static MZ_CLUSTER_REPLICA_NAME_HISTORY: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12549    name: "mz_cluster_replica_name_history",
12550    schema: MZ_INTERNAL_SCHEMA,
12551    oid: oid::VIEW_MZ_CLUSTER_REPLICA_NAME_HISTORY_OID,
12552    desc: RelationDesc::builder()
12553        .with_column(
12554            "occurred_at",
12555            SqlScalarType::TimestampTz { precision: None }.nullable(true),
12556        )
12557        .with_column("id", SqlScalarType::String.nullable(true))
12558        .with_column("previous_name", SqlScalarType::String.nullable(true))
12559        .with_column("new_name", SqlScalarType::String.nullable(true))
12560        .finish(),
12561    column_comments: BTreeMap::from_iter([
12562        (
12563            "occurred_at",
12564            "The time at which the cluster replica was created or renamed. `NULL` if it's a built in system cluster replica.",
12565        ),
12566        ("id", "The ID of the cluster replica."),
12567        (
12568            "previous_name",
12569            "The previous name of the cluster replica. `NULL` if there was no previous name.",
12570        ),
12571        ("new_name", "The new name of the cluster replica."),
12572    ]),
12573    sql: r#"WITH user_replica_alter_history AS (
12574  SELECT occurred_at,
12575    audit_events.details->>'replica_id' AS id,
12576    audit_events.details->>'old_name' AS previous_name,
12577    audit_events.details->>'new_name' AS new_name
12578  FROM mz_catalog.mz_audit_events AS audit_events
12579  WHERE object_type = 'cluster-replica'
12580    AND audit_events.event_type = 'alter'
12581    AND audit_events.details->>'replica_id' like 'u%'
12582),
12583user_replica_create_history AS (
12584  SELECT occurred_at,
12585    audit_events.details->>'replica_id' AS id,
12586    NULL AS previous_name,
12587    audit_events.details->>'replica_name' AS new_name
12588  FROM mz_catalog.mz_audit_events AS audit_events
12589  WHERE object_type = 'cluster-replica'
12590    AND audit_events.event_type = 'create'
12591    AND audit_events.details->>'replica_id' like 'u%'
12592),
12593-- Because built in system cluster replicas don't have audit events, we need to manually add them
12594system_replicas AS (
12595  -- We assume that the system cluster replicas were created at the beginning of time
12596  SELECT NULL::timestamptz AS occurred_at,
12597    id,
12598    NULL AS previous_name,
12599    name AS new_name
12600  FROM mz_catalog.mz_cluster_replicas
12601  WHERE id LIKE 's%'
12602)
12603SELECT *
12604FROM user_replica_alter_history
12605UNION ALL
12606SELECT *
12607FROM user_replica_create_history
12608UNION ALL
12609SELECT *
12610FROM system_replicas"#,
12611    access: vec![PUBLIC_SELECT],
12612});
12613
12614pub static MZ_HYDRATION_STATUSES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12615    name: "mz_hydration_statuses",
12616    schema: MZ_INTERNAL_SCHEMA,
12617    oid: oid::VIEW_MZ_HYDRATION_STATUSES_OID,
12618    desc: RelationDesc::builder()
12619        .with_column("object_id", SqlScalarType::String.nullable(false))
12620        .with_column("replica_id", SqlScalarType::String.nullable(true))
12621        .with_column("hydrated", SqlScalarType::Bool.nullable(true))
12622        .finish(),
12623    column_comments: BTreeMap::from_iter([
12624        (
12625            "object_id",
12626            "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`.",
12627        ),
12628        ("replica_id", "The ID of a cluster replica."),
12629        ("hydrated", "Whether the object is hydrated on the replica."),
12630    ]),
12631    sql: r#"WITH
12632-- Joining against the linearizable catalog tables ensures that this view
12633-- always contains the set of installed objects, even when it depends
12634-- on introspection relations that may received delayed updates.
12635--
12636-- Note that this view only includes objects that are maintained by dataflows.
12637-- In particular, some source types (webhook, introspection, ...) are not and
12638-- are therefore omitted.
12639indexes AS (
12640    SELECT
12641        i.id AS object_id,
12642        h.replica_id,
12643        COALESCE(h.hydrated, false) AS hydrated
12644    FROM mz_catalog.mz_indexes i
12645    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12646        ON (h.object_id = i.id)
12647),
12648materialized_views AS (
12649    SELECT
12650        i.id AS object_id,
12651        h.replica_id,
12652        COALESCE(h.hydrated, false) AS hydrated
12653    FROM mz_catalog.mz_materialized_views i
12654    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12655        ON (h.object_id = i.id)
12656),
12657continual_tasks AS (
12658    SELECT
12659        i.id AS object_id,
12660        h.replica_id,
12661        COALESCE(h.hydrated, false) AS hydrated
12662    FROM mz_internal.mz_continual_tasks i
12663    LEFT JOIN mz_internal.mz_compute_hydration_statuses h
12664        ON (h.object_id = i.id)
12665),
12666-- Hydration is a dataflow concept and not all sources are maintained by
12667-- dataflows, so we need to find the ones that are. Generally, sources that
12668-- have a cluster ID are maintained by a dataflow running on that cluster.
12669-- Webhook sources are an exception to this rule.
12670sources_with_clusters AS (
12671    SELECT id, cluster_id
12672    FROM mz_catalog.mz_sources
12673    WHERE cluster_id IS NOT NULL AND type != 'webhook'
12674),
12675sources AS (
12676    SELECT
12677        s.id AS object_id,
12678        ss.replica_id AS replica_id,
12679        ss.rehydration_latency IS NOT NULL AS hydrated
12680    FROM sources_with_clusters s
12681    LEFT JOIN mz_internal.mz_source_statistics ss USING (id)
12682),
12683-- We don't yet report sink hydration status (database-issues#8331), so we do a best effort attempt here and
12684-- define a sink as hydrated when it's both "running" and has a frontier greater than the minimum.
12685-- There is likely still a possibility of FPs.
12686sinks AS (
12687    SELECT
12688        s.id AS object_id,
12689        r.id AS replica_id,
12690        ss.status = 'running' AND COALESCE(f.write_frontier, 0) > 0 AS hydrated
12691    FROM mz_catalog.mz_sinks s
12692    LEFT JOIN mz_internal.mz_sink_statuses ss USING (id)
12693    JOIN mz_catalog.mz_cluster_replicas r
12694        ON (r.cluster_id = s.cluster_id)
12695    LEFT JOIN mz_catalog.mz_cluster_replica_frontiers f
12696        ON (f.object_id = s.id AND f.replica_id = r.id)
12697)
12698SELECT * FROM indexes
12699UNION ALL
12700SELECT * FROM materialized_views
12701UNION ALL
12702SELECT * FROM continual_tasks
12703UNION ALL
12704SELECT * FROM sources
12705UNION ALL
12706SELECT * FROM sinks"#,
12707    access: vec![PUBLIC_SELECT],
12708});
12709
12710pub const MZ_HYDRATION_STATUSES_IND: BuiltinIndex = BuiltinIndex {
12711    name: "mz_hydration_statuses_ind",
12712    schema: MZ_INTERNAL_SCHEMA,
12713    oid: oid::INDEX_MZ_HYDRATION_STATUSES_IND_OID,
12714    sql: "IN CLUSTER mz_catalog_server
12715ON mz_internal.mz_hydration_statuses (object_id, replica_id)",
12716    is_retained_metrics_object: false,
12717};
12718
12719pub static MZ_MATERIALIZATION_DEPENDENCIES: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12720    name: "mz_materialization_dependencies",
12721    schema: MZ_INTERNAL_SCHEMA,
12722    oid: oid::VIEW_MZ_MATERIALIZATION_DEPENDENCIES_OID,
12723    desc: RelationDesc::builder()
12724        .with_column("object_id", SqlScalarType::String.nullable(false))
12725        .with_column("dependency_id", SqlScalarType::String.nullable(false))
12726        .finish(),
12727    column_comments: BTreeMap::from_iter([
12728        (
12729            "object_id",
12730            "The ID of a materialization. Corresponds to `mz_catalog.mz_indexes.id`, `mz_catalog.mz_materialized_views.id`, or `mz_catalog.mz_sinks.id`.",
12731        ),
12732        (
12733            "dependency_id",
12734            "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`.",
12735        ),
12736    ]),
12737    sql: "
12738SELECT object_id, dependency_id
12739FROM mz_internal.mz_compute_dependencies
12740UNION ALL
12741SELECT s.id, d.referenced_object_id AS dependency_id
12742FROM mz_internal.mz_object_dependencies d
12743JOIN mz_catalog.mz_sinks s ON (s.id = d.object_id)
12744JOIN mz_catalog.mz_relations r ON (r.id = d.referenced_object_id)",
12745    access: vec![PUBLIC_SELECT],
12746});
12747
12748pub static MZ_MATERIALIZATION_LAG: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
12749    name: "mz_materialization_lag",
12750    schema: MZ_INTERNAL_SCHEMA,
12751    oid: oid::VIEW_MZ_MATERIALIZATION_LAG_OID,
12752    desc: RelationDesc::builder()
12753        .with_column("object_id", SqlScalarType::String.nullable(false))
12754        .with_column("local_lag", SqlScalarType::Interval.nullable(true))
12755        .with_column("global_lag", SqlScalarType::Interval.nullable(true))
12756        .with_column(
12757            "slowest_local_input_id",
12758            SqlScalarType::String.nullable(false),
12759        )
12760        .with_column(
12761            "slowest_global_input_id",
12762            SqlScalarType::String.nullable(false),
12763        )
12764        .finish(),
12765    column_comments: BTreeMap::from_iter([
12766        (
12767            "object_id",
12768            "The ID of the materialized view, index, or sink.",
12769        ),
12770        (
12771            "local_lag",
12772            "The amount of time the materialization lags behind its direct inputs.",
12773        ),
12774        (
12775            "global_lag",
12776            "The amount of time the materialization lags behind its root inputs (sources and tables).",
12777        ),
12778        (
12779            "slowest_local_input_id",
12780            "The ID of the slowest direct input.",
12781        ),
12782        (
12783            "slowest_global_input_id",
12784            "The ID of the slowest root input.",
12785        ),
12786    ]),
12787    sql: "
12788WITH MUTUALLY RECURSIVE
12789    -- IDs of objects for which we want to know the lag.
12790    materializations (id text) AS (
12791        SELECT id FROM mz_catalog.mz_indexes
12792        UNION ALL
12793        SELECT id FROM mz_catalog.mz_materialized_views
12794        UNION ALL
12795        SELECT id FROM mz_internal.mz_continual_tasks
12796        UNION ALL
12797        SELECT id FROM mz_catalog.mz_sinks
12798    ),
12799    -- Direct dependencies of materializations.
12800    direct_dependencies (id text, dep_id text) AS (
12801        SELECT m.id, d.dependency_id
12802        FROM materializations m
12803        JOIN mz_internal.mz_materialization_dependencies d ON (m.id = d.object_id)
12804    ),
12805    -- All transitive dependencies of materializations.
12806    transitive_dependencies (id text, dep_id text) AS (
12807        SELECT id, dep_id FROM direct_dependencies
12808        UNION
12809        SELECT td.id, dd.dep_id
12810        FROM transitive_dependencies td
12811        JOIN direct_dependencies dd ON (dd.id = td.dep_id)
12812    ),
12813    -- Root dependencies of materializations (sources and tables).
12814    root_dependencies (id text, dep_id text) AS (
12815        SELECT *
12816        FROM transitive_dependencies td
12817        WHERE NOT EXISTS (
12818            SELECT 1
12819            FROM direct_dependencies dd
12820            WHERE dd.id = td.dep_id
12821        )
12822    ),
12823    -- Write progress times of materializations.
12824    materialization_times (id text, time timestamptz) AS (
12825        SELECT m.id, to_timestamp(f.write_frontier::text::double / 1000)
12826        FROM materializations m
12827        JOIN mz_internal.mz_frontiers f ON (m.id = f.object_id)
12828    ),
12829    -- Write progress times of direct dependencies of materializations.
12830    input_times (id text, slowest_dep text, time timestamptz) AS (
12831        SELECT DISTINCT ON (d.id)
12832            d.id,
12833            d.dep_id,
12834            to_timestamp(f.write_frontier::text::double / 1000)
12835        FROM direct_dependencies d
12836        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12837        ORDER BY d.id, f.write_frontier ASC
12838    ),
12839    -- Write progress times of root dependencies of materializations.
12840    root_times (id text, slowest_dep text, time timestamptz) AS (
12841        SELECT DISTINCT ON (d.id)
12842            d.id,
12843            d.dep_id,
12844            to_timestamp(f.write_frontier::text::double / 1000)
12845        FROM root_dependencies d
12846        JOIN mz_internal.mz_frontiers f ON (d.dep_id = f.object_id)
12847        ORDER BY d.id, f.write_frontier ASC
12848    )
12849SELECT
12850    id AS object_id,
12851    -- Ensure that lag values are always NULL for materializations that have reached the empty
12852    -- frontier, as those have processed all their input data.
12853    -- Also make sure that lag values are never negative, even when input frontiers are before
12854    -- output frontiers (as can happen during hydration).
12855    CASE
12856        WHEN m.time IS NULL THEN INTERVAL '0'
12857        WHEN i.time IS NULL THEN NULL
12858        ELSE greatest(i.time - m.time, INTERVAL '0')
12859    END AS local_lag,
12860    CASE
12861        WHEN m.time IS NULL THEN INTERVAL '0'
12862        WHEN r.time IS NULL THEN NULL
12863        ELSE greatest(r.time - m.time, INTERVAL '0')
12864    END AS global_lag,
12865    i.slowest_dep AS slowest_local_input_id,
12866    r.slowest_dep AS slowest_global_input_id
12867FROM materialization_times m
12868JOIN input_times i USING (id)
12869JOIN root_times r USING (id)",
12870    access: vec![PUBLIC_SELECT],
12871});
12872
12873/**
12874 * This view is used to display the cluster utilization over 14 days bucketed by 8 hours.
12875 * It's specifically for the Console's environment overview page to speed up load times.
12876 * This query should be kept in sync with MaterializeInc/console/src/api/materialize/cluster/replicaUtilizationHistory.ts
12877 */
12878pub static MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW: LazyLock<BuiltinView> = LazyLock::new(|| {
12879    BuiltinView {
12880        name: "mz_console_cluster_utilization_overview",
12881        schema: MZ_INTERNAL_SCHEMA,
12882        oid: oid::VIEW_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_OID,
12883        desc: RelationDesc::builder()
12884            .with_column(
12885                "bucket_start",
12886                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12887            )
12888            .with_column("replica_id", SqlScalarType::String.nullable(false))
12889            .with_column("memory_percent", SqlScalarType::Float64.nullable(true))
12890            .with_column(
12891                "max_memory_at",
12892                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12893            )
12894            .with_column("disk_percent", SqlScalarType::Float64.nullable(true))
12895            .with_column(
12896                "max_disk_at",
12897                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12898            )
12899            .with_column(
12900                "memory_and_disk_percent",
12901                SqlScalarType::Float64.nullable(true),
12902            )
12903            .with_column(
12904                "max_memory_and_disk_memory_percent",
12905                SqlScalarType::Float64.nullable(true),
12906            )
12907            .with_column(
12908                "max_memory_and_disk_disk_percent",
12909                SqlScalarType::Float64.nullable(true),
12910            )
12911            .with_column(
12912                "max_memory_and_disk_at",
12913                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12914            )
12915            .with_column("heap_percent", SqlScalarType::Float64.nullable(true))
12916            .with_column(
12917                "max_heap_at",
12918                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12919            )
12920            .with_column("max_cpu_percent", SqlScalarType::Float64.nullable(true))
12921            .with_column(
12922                "max_cpu_at",
12923                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12924            )
12925            .with_column("offline_events", SqlScalarType::Jsonb.nullable(true))
12926            .with_column(
12927                "bucket_end",
12928                SqlScalarType::TimestampTz { precision: None }.nullable(false),
12929            )
12930            .with_column("name", SqlScalarType::String.nullable(true))
12931            .with_column("cluster_id", SqlScalarType::String.nullable(true))
12932            .with_column("size", SqlScalarType::String.nullable(true))
12933            .finish(),
12934        column_comments: BTreeMap::new(),
12935        sql: r#"WITH replica_history AS (
12936  SELECT replica_id,
12937    size,
12938    cluster_id
12939  FROM mz_internal.mz_cluster_replica_history
12940  UNION
12941  -- We need to union the current set of cluster replicas since mz_cluster_replica_history doesn't include system clusters
12942  SELECT id AS replica_id,
12943    size,
12944    cluster_id
12945  FROM mz_catalog.mz_cluster_replicas
12946),
12947replica_metrics_history AS (
12948  SELECT
12949    m.occurred_at,
12950    m.replica_id,
12951    r.size,
12952    (SUM(m.cpu_nano_cores::float8) / NULLIF(s.cpu_nano_cores, 0)) / NULLIF(s.processes, 0) AS cpu_percent,
12953    (SUM(m.memory_bytes::float8) / NULLIF(s.memory_bytes, 0)) / NULLIF(s.processes, 0) AS memory_percent,
12954    (SUM(m.disk_bytes::float8) / NULLIF(s.disk_bytes, 0)) / NULLIF(s.processes, 0) AS disk_percent,
12955    (SUM(m.heap_bytes::float8) / NULLIF(m.heap_limit, 0)) / NULLIF(s.processes, 0) AS heap_percent,
12956    SUM(m.disk_bytes::float8) AS disk_bytes,
12957    SUM(m.memory_bytes::float8) AS memory_bytes,
12958    s.disk_bytes::numeric * s.processes AS total_disk_bytes,
12959    s.memory_bytes::numeric * s.processes AS total_memory_bytes
12960  FROM
12961    replica_history AS r
12962    INNER JOIN mz_catalog.mz_cluster_replica_sizes AS s ON r.size = s.size
12963    INNER JOIN mz_internal.mz_cluster_replica_metrics_history AS m ON m.replica_id = r.replica_id
12964  GROUP BY
12965    m.occurred_at,
12966    m.replica_id,
12967    r.size,
12968    s.cpu_nano_cores,
12969    s.memory_bytes,
12970    s.disk_bytes,
12971    m.heap_limit,
12972    s.processes
12973),
12974replica_utilization_history_binned AS (
12975  SELECT m.occurred_at,
12976    m.replica_id,
12977    m.cpu_percent,
12978    m.memory_percent,
12979    m.memory_bytes,
12980    m.disk_percent,
12981    m.disk_bytes,
12982    m.heap_percent,
12983    m.total_disk_bytes,
12984    m.total_memory_bytes,
12985    m.size,
12986    date_bin(
12987      '8 HOURS',
12988      occurred_at,
12989      '1970-01-01'::timestamp
12990    ) AS bucket_start
12991  FROM replica_history AS r
12992    JOIN replica_metrics_history AS m ON m.replica_id = r.replica_id
12993  WHERE mz_now() <= date_bin(
12994      '8 HOURS',
12995      occurred_at,
12996      '1970-01-01'::timestamp
12997    ) + INTERVAL '14 DAYS'
12998),
12999-- For each (replica, bucket), take the (replica, bucket) with the highest memory
13000max_memory AS (
13001  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
13002    replica_id,
13003    memory_percent,
13004    occurred_at
13005  FROM replica_utilization_history_binned
13006  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
13007  ORDER BY bucket_start,
13008    replica_id,
13009    COALESCE(memory_bytes, 0) DESC
13010),
13011max_disk AS (
13012  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
13013    replica_id,
13014    disk_percent,
13015    occurred_at
13016  FROM replica_utilization_history_binned
13017  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
13018  ORDER BY bucket_start,
13019    replica_id,
13020    COALESCE(disk_bytes, 0) DESC
13021),
13022max_cpu AS (
13023  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
13024    replica_id,
13025    cpu_percent,
13026    occurred_at
13027  FROM replica_utilization_history_binned
13028  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
13029  ORDER BY bucket_start,
13030    replica_id,
13031    COALESCE(cpu_percent, 0) DESC
13032),
13033/*
13034 This is different
13035 from adding max_memory
13036 and max_disk per bucket because both
13037 values may not occur at the same time if the bucket interval is large.
13038 */
13039max_memory_and_disk AS (
13040  SELECT DISTINCT ON (bucket_start, replica_id) bucket_start,
13041    replica_id,
13042    memory_percent,
13043    disk_percent,
13044    memory_and_disk_percent,
13045    occurred_at
13046  FROM (
13047      SELECT *,
13048        CASE
13049          WHEN disk_bytes IS NULL
13050          AND memory_bytes IS NULL THEN NULL
13051          ELSE (COALESCE(disk_bytes, 0) + COALESCE(memory_bytes, 0))
13052               / (total_disk_bytes::numeric + total_memory_bytes::numeric)
13053        END AS memory_and_disk_percent
13054      FROM replica_utilization_history_binned
13055    ) AS max_memory_and_disk_inner
13056  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
13057  ORDER BY bucket_start,
13058    replica_id,
13059    COALESCE(memory_and_disk_percent, 0) DESC
13060),
13061max_heap AS (
13062  SELECT DISTINCT ON (bucket_start, replica_id)
13063    bucket_start,
13064    replica_id,
13065    heap_percent,
13066    occurred_at
13067  FROM replica_utilization_history_binned
13068  OPTIONS (DISTINCT ON INPUT GROUP SIZE = 480)
13069  ORDER BY bucket_start, replica_id, COALESCE(heap_percent, 0) DESC
13070),
13071-- For each (replica, bucket), get its offline events at that time
13072replica_offline_event_history AS (
13073  SELECT date_bin(
13074      '8 HOURS',
13075      occurred_at,
13076      '1970-01-01'::timestamp
13077    ) AS bucket_start,
13078    replica_id,
13079    jsonb_agg(
13080      jsonb_build_object(
13081        'replicaId',
13082        rsh.replica_id,
13083        'occurredAt',
13084        rsh.occurred_at,
13085        'status',
13086        rsh.status,
13087        'reason',
13088        rsh.reason
13089      )
13090    ) AS offline_events
13091  FROM mz_internal.mz_cluster_replica_status_history AS rsh -- We assume the statuses for process 0 are the same as all processes
13092  WHERE process_id = '0'
13093    AND status = 'offline'
13094    AND mz_now() <= date_bin(
13095      '8 HOURS',
13096      occurred_at,
13097      '1970-01-01'::timestamp
13098    ) + INTERVAL '14 DAYS'
13099  GROUP BY bucket_start,
13100    replica_id
13101)
13102SELECT
13103  bucket_start,
13104  replica_id,
13105  max_memory.memory_percent,
13106  max_memory.occurred_at as max_memory_at,
13107  max_disk.disk_percent,
13108  max_disk.occurred_at as max_disk_at,
13109  max_memory_and_disk.memory_and_disk_percent as memory_and_disk_percent,
13110  max_memory_and_disk.memory_percent as max_memory_and_disk_memory_percent,
13111  max_memory_and_disk.disk_percent as max_memory_and_disk_disk_percent,
13112  max_memory_and_disk.occurred_at as max_memory_and_disk_at,
13113  max_heap.heap_percent,
13114  max_heap.occurred_at as max_heap_at,
13115  max_cpu.cpu_percent as max_cpu_percent,
13116  max_cpu.occurred_at as max_cpu_at,
13117  replica_offline_event_history.offline_events,
13118  bucket_start + INTERVAL '8 HOURS' as bucket_end,
13119  replica_name_history.new_name AS name,
13120  replica_history.cluster_id,
13121  replica_history.size
13122FROM max_memory
13123JOIN max_disk USING (bucket_start, replica_id)
13124JOIN max_cpu USING (bucket_start, replica_id)
13125JOIN max_memory_and_disk USING (bucket_start, replica_id)
13126JOIN max_heap USING (bucket_start, replica_id)
13127JOIN replica_history USING (replica_id)
13128CROSS JOIN LATERAL (
13129  SELECT new_name
13130  FROM mz_internal.mz_cluster_replica_name_history as replica_name_history
13131  WHERE replica_id = replica_name_history.id -- We treat NULLs as the beginning of time
13132    AND bucket_start + INTERVAL '8 HOURS' >= COALESCE(
13133      replica_name_history.occurred_at,
13134      '1970-01-01'::timestamp
13135    )
13136  ORDER BY replica_name_history.occurred_at DESC
13137  LIMIT '1'
13138) AS replica_name_history
13139LEFT JOIN replica_offline_event_history USING (bucket_start, replica_id)"#,
13140        access: vec![PUBLIC_SELECT],
13141    }
13142});
13143
13144/**
13145 * Traces the blue/green deployment lineage in the audit log to determine all cluster
13146 * IDs that are logically the same cluster.
13147 * cluster_id: The ID of a cluster.
13148 * current_deployment_cluster_id: The cluster ID of the last cluster in
13149 *   cluster_id's blue/green lineage.
13150 * cluster_name: The name of the cluster.
13151 * The approach taken is as follows. First, find all extant clusters and add them
13152 * to the result set. Per cluster, we do the following:
13153 * 1. Find the most recent create or rename event. This moment represents when the
13154 *    cluster took on its final logical identity.
13155 * 2. Look for a cluster that had the same name (or the same name with `_dbt_deploy`
13156 *    appended) that was dropped within one minute of that moment. That cluster is
13157 *    almost certainly the logical predecessor of the current cluster. Add the cluster
13158 *    to the result set.
13159 * 3. Repeat the procedure until a cluster with no logical predecessor is discovered.
13160 * Limiting the search for a dropped cluster to a window of one minute is a heuristic,
13161 * but one that's likely to be pretty good one. If a name is reused after more
13162 * than one minute, that's a good sign that it wasn't an automatic blue/green
13163 * process, but someone turning on a new use case that happens to have the same
13164 * name as a previous but logically distinct use case.
13165 */
13166pub static MZ_CLUSTER_DEPLOYMENT_LINEAGE: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13167    name: "mz_cluster_deployment_lineage",
13168    schema: MZ_INTERNAL_SCHEMA,
13169    oid: oid::VIEW_MZ_CLUSTER_DEPLOYMENT_LINEAGE_OID,
13170    desc: RelationDesc::builder()
13171        .with_column("cluster_id", SqlScalarType::String.nullable(true))
13172        .with_column(
13173            "current_deployment_cluster_id",
13174            SqlScalarType::String.nullable(false),
13175        )
13176        .with_column("cluster_name", SqlScalarType::String.nullable(false))
13177        .with_key(vec![0, 1, 2])
13178        .finish(),
13179    column_comments: BTreeMap::from_iter([
13180        (
13181            "cluster_id",
13182            "The ID of the cluster. Corresponds to `mz_clusters.id` (though the cluster may no longer exist).",
13183        ),
13184        (
13185            "current_deployment_cluster_id",
13186            "The cluster ID of the last cluster in `cluster_id`'s blue/green lineage (the cluster is guaranteed to exist).",
13187        ),
13188        ("cluster_name", "The name of the cluster"),
13189    ]),
13190    sql: r#"WITH MUTUALLY RECURSIVE cluster_events (
13191  cluster_id text,
13192  cluster_name text,
13193  event_type text,
13194  occurred_at timestamptz
13195) AS (
13196  SELECT coalesce(details->>'id', details->>'cluster_id') AS cluster_id,
13197    coalesce(details->>'name', details->>'new_name') AS cluster_name,
13198    event_type,
13199    occurred_at
13200  FROM mz_audit_events
13201  WHERE (
13202      event_type IN ('create', 'drop')
13203      OR (
13204        event_type = 'alter'
13205        AND details ? 'new_name'
13206      )
13207    )
13208    AND object_type = 'cluster'
13209    AND mz_now() < occurred_at + INTERVAL '30 days'
13210),
13211mz_cluster_deployment_lineage (
13212  cluster_id text,
13213  current_deployment_cluster_id text,
13214  cluster_name text
13215) AS (
13216  SELECT c.id,
13217    c.id,
13218    c.name
13219  FROM mz_clusters c
13220  WHERE c.id LIKE 'u%'
13221  UNION
13222  SELECT *
13223  FROM dropped_clusters
13224),
13225-- Closest create or rename event based on the current clusters in the result set
13226most_recent_create_or_rename (
13227  cluster_id text,
13228  current_deployment_cluster_id text,
13229  cluster_name text,
13230  occurred_at timestamptz
13231) AS (
13232  SELECT DISTINCT ON (e.cluster_id) e.cluster_id,
13233    c.current_deployment_cluster_id,
13234    e.cluster_name,
13235    e.occurred_at
13236  FROM mz_cluster_deployment_lineage c
13237    JOIN cluster_events e ON c.cluster_id = e.cluster_id
13238    AND c.cluster_name = e.cluster_name
13239  WHERE e.event_type <> 'drop'
13240  ORDER BY e.cluster_id,
13241    e.occurred_at DESC
13242),
13243-- Clusters that were dropped most recently within 1 minute of most_recent_create_or_rename
13244dropped_clusters (
13245  cluster_id text,
13246  current_deployment_cluster_id text,
13247  cluster_name text
13248) AS (
13249  SELECT DISTINCT ON (cr.cluster_id) e.cluster_id,
13250    cr.current_deployment_cluster_id,
13251    cr.cluster_name
13252  FROM most_recent_create_or_rename cr
13253    JOIN cluster_events e ON e.occurred_at BETWEEN cr.occurred_at - interval '1 minute'
13254    AND cr.occurred_at + interval '1 minute'
13255    AND (
13256      e.cluster_name = cr.cluster_name
13257      OR e.cluster_name = cr.cluster_name || '_dbt_deploy'
13258    )
13259  WHERE e.event_type = 'drop'
13260  ORDER BY cr.cluster_id,
13261    abs(
13262      extract(
13263        epoch
13264        FROM cr.occurred_at - e.occurred_at
13265      )
13266    )
13267)
13268SELECT *
13269FROM mz_cluster_deployment_lineage"#,
13270    access: vec![PUBLIC_SELECT],
13271});
13272
13273pub const MZ_SHOW_DATABASES_IND: BuiltinIndex = BuiltinIndex {
13274    name: "mz_show_databases_ind",
13275    schema: MZ_INTERNAL_SCHEMA,
13276    oid: oid::INDEX_MZ_SHOW_DATABASES_IND_OID,
13277    sql: "IN CLUSTER mz_catalog_server
13278ON mz_internal.mz_show_databases (name)",
13279    is_retained_metrics_object: false,
13280};
13281
13282pub const MZ_SHOW_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
13283    name: "mz_show_schemas_ind",
13284    schema: MZ_INTERNAL_SCHEMA,
13285    oid: oid::INDEX_MZ_SHOW_SCHEMAS_IND_OID,
13286    sql: "IN CLUSTER mz_catalog_server
13287ON mz_internal.mz_show_schemas (database_id)",
13288    is_retained_metrics_object: false,
13289};
13290
13291pub const MZ_SHOW_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
13292    name: "mz_show_connections_ind",
13293    schema: MZ_INTERNAL_SCHEMA,
13294    oid: oid::INDEX_MZ_SHOW_CONNECTIONS_IND_OID,
13295    sql: "IN CLUSTER mz_catalog_server
13296ON mz_internal.mz_show_connections (schema_id)",
13297    is_retained_metrics_object: false,
13298};
13299
13300pub const MZ_SHOW_TABLES_IND: BuiltinIndex = BuiltinIndex {
13301    name: "mz_show_tables_ind",
13302    schema: MZ_INTERNAL_SCHEMA,
13303    oid: oid::INDEX_MZ_SHOW_TABLES_IND_OID,
13304    sql: "IN CLUSTER mz_catalog_server
13305ON mz_internal.mz_show_tables (schema_id)",
13306    is_retained_metrics_object: false,
13307};
13308
13309pub const MZ_SHOW_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13310    name: "mz_show_sources_ind",
13311    schema: MZ_INTERNAL_SCHEMA,
13312    oid: oid::INDEX_MZ_SHOW_SOURCES_IND_OID,
13313    sql: "IN CLUSTER mz_catalog_server
13314ON mz_internal.mz_show_sources (schema_id)",
13315    is_retained_metrics_object: false,
13316};
13317
13318pub const MZ_SHOW_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13319    name: "mz_show_views_ind",
13320    schema: MZ_INTERNAL_SCHEMA,
13321    oid: oid::INDEX_MZ_SHOW_VIEWS_IND_OID,
13322    sql: "IN CLUSTER mz_catalog_server
13323ON mz_internal.mz_show_views (schema_id)",
13324    is_retained_metrics_object: false,
13325};
13326
13327pub const MZ_SHOW_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13328    name: "mz_show_materialized_views_ind",
13329    schema: MZ_INTERNAL_SCHEMA,
13330    oid: oid::INDEX_MZ_SHOW_MATERIALIZED_VIEWS_IND_OID,
13331    sql: "IN CLUSTER mz_catalog_server
13332ON mz_internal.mz_show_materialized_views (schema_id)",
13333    is_retained_metrics_object: false,
13334};
13335
13336pub const MZ_SHOW_SINKS_IND: BuiltinIndex = BuiltinIndex {
13337    name: "mz_show_sinks_ind",
13338    schema: MZ_INTERNAL_SCHEMA,
13339    oid: oid::INDEX_MZ_SHOW_SINKS_IND_OID,
13340    sql: "IN CLUSTER mz_catalog_server
13341ON mz_internal.mz_show_sinks (schema_id)",
13342    is_retained_metrics_object: false,
13343};
13344
13345pub const MZ_SHOW_TYPES_IND: BuiltinIndex = BuiltinIndex {
13346    name: "mz_show_types_ind",
13347    schema: MZ_INTERNAL_SCHEMA,
13348    oid: oid::INDEX_MZ_SHOW_TYPES_IND_OID,
13349    sql: "IN CLUSTER mz_catalog_server
13350ON mz_internal.mz_show_types (schema_id)",
13351    is_retained_metrics_object: false,
13352};
13353
13354pub const MZ_SHOW_ROLES_IND: BuiltinIndex = BuiltinIndex {
13355    name: "mz_show_roles_ind",
13356    schema: MZ_INTERNAL_SCHEMA,
13357    oid: oid::INDEX_MZ_SHOW_ROLES_IND_OID,
13358    sql: "IN CLUSTER mz_catalog_server
13359ON mz_internal.mz_show_roles (name)",
13360    is_retained_metrics_object: false,
13361};
13362
13363pub const MZ_SHOW_ALL_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
13364    name: "mz_show_all_objects_ind",
13365    schema: MZ_INTERNAL_SCHEMA,
13366    oid: oid::INDEX_MZ_SHOW_ALL_OBJECTS_IND_OID,
13367    sql: "IN CLUSTER mz_catalog_server
13368ON mz_internal.mz_show_all_objects (schema_id)",
13369    is_retained_metrics_object: false,
13370};
13371
13372pub const MZ_SHOW_INDEXES_IND: BuiltinIndex = BuiltinIndex {
13373    name: "mz_show_indexes_ind",
13374    schema: MZ_INTERNAL_SCHEMA,
13375    oid: oid::INDEX_MZ_SHOW_INDEXES_IND_OID,
13376    sql: "IN CLUSTER mz_catalog_server
13377ON mz_internal.mz_show_indexes (schema_id)",
13378    is_retained_metrics_object: false,
13379};
13380
13381pub const MZ_SHOW_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
13382    name: "mz_show_columns_ind",
13383    schema: MZ_INTERNAL_SCHEMA,
13384    oid: oid::INDEX_MZ_SHOW_COLUMNS_IND_OID,
13385    sql: "IN CLUSTER mz_catalog_server
13386ON mz_internal.mz_show_columns (id)",
13387    is_retained_metrics_object: false,
13388};
13389
13390pub const MZ_SHOW_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
13391    name: "mz_show_clusters_ind",
13392    schema: MZ_INTERNAL_SCHEMA,
13393    oid: oid::INDEX_MZ_SHOW_CLUSTERS_IND_OID,
13394    sql: "IN CLUSTER mz_catalog_server
13395ON mz_internal.mz_show_clusters (name)",
13396    is_retained_metrics_object: false,
13397};
13398
13399pub const MZ_SHOW_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13400    name: "mz_show_cluster_replicas_ind",
13401    schema: MZ_INTERNAL_SCHEMA,
13402    oid: oid::INDEX_MZ_SHOW_CLUSTER_REPLICAS_IND_OID,
13403    sql: "IN CLUSTER mz_catalog_server
13404ON mz_internal.mz_show_cluster_replicas (cluster)",
13405    is_retained_metrics_object: false,
13406};
13407
13408pub const MZ_SHOW_SECRETS_IND: BuiltinIndex = BuiltinIndex {
13409    name: "mz_show_secrets_ind",
13410    schema: MZ_INTERNAL_SCHEMA,
13411    oid: oid::INDEX_MZ_SHOW_SECRETS_IND_OID,
13412    sql: "IN CLUSTER mz_catalog_server
13413ON mz_internal.mz_show_secrets (schema_id)",
13414    is_retained_metrics_object: false,
13415};
13416
13417pub const MZ_DATABASES_IND: BuiltinIndex = BuiltinIndex {
13418    name: "mz_databases_ind",
13419    schema: MZ_CATALOG_SCHEMA,
13420    oid: oid::INDEX_MZ_DATABASES_IND_OID,
13421    sql: "IN CLUSTER mz_catalog_server
13422ON mz_catalog.mz_databases (name)",
13423    is_retained_metrics_object: false,
13424};
13425
13426pub const MZ_SCHEMAS_IND: BuiltinIndex = BuiltinIndex {
13427    name: "mz_schemas_ind",
13428    schema: MZ_CATALOG_SCHEMA,
13429    oid: oid::INDEX_MZ_SCHEMAS_IND_OID,
13430    sql: "IN CLUSTER mz_catalog_server
13431ON mz_catalog.mz_schemas (database_id)",
13432    is_retained_metrics_object: false,
13433};
13434
13435pub const MZ_CONNECTIONS_IND: BuiltinIndex = BuiltinIndex {
13436    name: "mz_connections_ind",
13437    schema: MZ_CATALOG_SCHEMA,
13438    oid: oid::INDEX_MZ_CONNECTIONS_IND_OID,
13439    sql: "IN CLUSTER mz_catalog_server
13440ON mz_catalog.mz_connections (schema_id)",
13441    is_retained_metrics_object: false,
13442};
13443
13444pub const MZ_TABLES_IND: BuiltinIndex = BuiltinIndex {
13445    name: "mz_tables_ind",
13446    schema: MZ_CATALOG_SCHEMA,
13447    oid: oid::INDEX_MZ_TABLES_IND_OID,
13448    sql: "IN CLUSTER mz_catalog_server
13449ON mz_catalog.mz_tables (schema_id)",
13450    is_retained_metrics_object: false,
13451};
13452
13453pub const MZ_TYPES_IND: BuiltinIndex = BuiltinIndex {
13454    name: "mz_types_ind",
13455    schema: MZ_CATALOG_SCHEMA,
13456    oid: oid::INDEX_MZ_TYPES_IND_OID,
13457    sql: "IN CLUSTER mz_catalog_server
13458ON mz_catalog.mz_types (schema_id)",
13459    is_retained_metrics_object: false,
13460};
13461
13462pub const MZ_OBJECTS_IND: BuiltinIndex = BuiltinIndex {
13463    name: "mz_objects_ind",
13464    schema: MZ_CATALOG_SCHEMA,
13465    oid: oid::INDEX_MZ_OBJECTS_IND_OID,
13466    sql: "IN CLUSTER mz_catalog_server
13467ON mz_catalog.mz_objects (schema_id)",
13468    is_retained_metrics_object: false,
13469};
13470
13471pub const MZ_COLUMNS_IND: BuiltinIndex = BuiltinIndex {
13472    name: "mz_columns_ind",
13473    schema: MZ_CATALOG_SCHEMA,
13474    oid: oid::INDEX_MZ_COLUMNS_IND_OID,
13475    sql: "IN CLUSTER mz_catalog_server
13476ON mz_catalog.mz_columns (name)",
13477    is_retained_metrics_object: false,
13478};
13479
13480pub const MZ_SECRETS_IND: BuiltinIndex = BuiltinIndex {
13481    name: "mz_secrets_ind",
13482    schema: MZ_CATALOG_SCHEMA,
13483    oid: oid::INDEX_MZ_SECRETS_IND_OID,
13484    sql: "IN CLUSTER mz_catalog_server
13485ON mz_catalog.mz_secrets (name)",
13486    is_retained_metrics_object: false,
13487};
13488
13489pub const MZ_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13490    name: "mz_views_ind",
13491    schema: MZ_CATALOG_SCHEMA,
13492    oid: oid::INDEX_MZ_VIEWS_IND_OID,
13493    sql: "IN CLUSTER mz_catalog_server
13494ON mz_catalog.mz_views (schema_id)",
13495    is_retained_metrics_object: false,
13496};
13497
13498pub const MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND: BuiltinIndex = BuiltinIndex {
13499    name: "mz_console_cluster_utilization_overview_ind",
13500    schema: MZ_INTERNAL_SCHEMA,
13501    oid: oid::INDEX_MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND_OID,
13502    sql: "IN CLUSTER mz_catalog_server
13503ON mz_internal.mz_console_cluster_utilization_overview (cluster_id)",
13504    is_retained_metrics_object: false,
13505};
13506
13507pub const MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND: BuiltinIndex = BuiltinIndex {
13508    name: "mz_cluster_deployment_lineage_ind",
13509    schema: MZ_INTERNAL_SCHEMA,
13510    oid: oid::INDEX_MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND_OID,
13511    sql: "IN CLUSTER mz_catalog_server
13512ON mz_internal.mz_cluster_deployment_lineage (cluster_id)",
13513    is_retained_metrics_object: false,
13514};
13515
13516pub const MZ_CLUSTERS_IND: BuiltinIndex = BuiltinIndex {
13517    name: "mz_clusters_ind",
13518    schema: MZ_CATALOG_SCHEMA,
13519    oid: oid::INDEX_MZ_CLUSTERS_IND_OID,
13520    sql: "IN CLUSTER mz_catalog_server
13521ON mz_catalog.mz_clusters (id)",
13522    is_retained_metrics_object: false,
13523};
13524
13525pub const MZ_INDEXES_IND: BuiltinIndex = BuiltinIndex {
13526    name: "mz_indexes_ind",
13527    schema: MZ_CATALOG_SCHEMA,
13528    oid: oid::INDEX_MZ_INDEXES_IND_OID,
13529    sql: "IN CLUSTER mz_catalog_server
13530ON mz_catalog.mz_indexes (id)",
13531    is_retained_metrics_object: false,
13532};
13533
13534pub const MZ_ROLES_IND: BuiltinIndex = BuiltinIndex {
13535    name: "mz_roles_ind",
13536    schema: MZ_CATALOG_SCHEMA,
13537    oid: oid::INDEX_MZ_ROLES_IND_OID,
13538    sql: "IN CLUSTER mz_catalog_server
13539ON mz_catalog.mz_roles (id)",
13540    is_retained_metrics_object: false,
13541};
13542
13543pub const MZ_SOURCES_IND: BuiltinIndex = BuiltinIndex {
13544    name: "mz_sources_ind",
13545    schema: MZ_CATALOG_SCHEMA,
13546    oid: oid::INDEX_MZ_SOURCES_IND_OID,
13547    sql: "IN CLUSTER mz_catalog_server
13548ON mz_catalog.mz_sources (id)",
13549    is_retained_metrics_object: true,
13550};
13551
13552pub const MZ_SINKS_IND: BuiltinIndex = BuiltinIndex {
13553    name: "mz_sinks_ind",
13554    schema: MZ_CATALOG_SCHEMA,
13555    oid: oid::INDEX_MZ_SINKS_IND_OID,
13556    sql: "IN CLUSTER mz_catalog_server
13557ON mz_catalog.mz_sinks (id)",
13558    is_retained_metrics_object: true,
13559};
13560
13561pub const MZ_MATERIALIZED_VIEWS_IND: BuiltinIndex = BuiltinIndex {
13562    name: "mz_materialized_views_ind",
13563    schema: MZ_CATALOG_SCHEMA,
13564    oid: oid::INDEX_MZ_MATERIALIZED_VIEWS_IND_OID,
13565    sql: "IN CLUSTER mz_catalog_server
13566ON mz_catalog.mz_materialized_views (id)",
13567    is_retained_metrics_object: false,
13568};
13569
13570pub const MZ_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13571    name: "mz_continual_tasks_ind",
13572    schema: MZ_INTERNAL_SCHEMA,
13573    oid: oid::INDEX_MZ_CONTINUAL_TASKS_IND_OID,
13574    sql: "IN CLUSTER mz_catalog_server
13575ON mz_internal.mz_continual_tasks (id)",
13576    is_retained_metrics_object: false,
13577};
13578
13579pub const MZ_SOURCE_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13580    name: "mz_source_statuses_ind",
13581    schema: MZ_INTERNAL_SCHEMA,
13582    oid: oid::INDEX_MZ_SOURCE_STATUSES_IND_OID,
13583    sql: "IN CLUSTER mz_catalog_server
13584ON mz_internal.mz_source_statuses (id)",
13585    is_retained_metrics_object: false,
13586};
13587
13588pub const MZ_SINK_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13589    name: "mz_sink_statuses_ind",
13590    schema: MZ_INTERNAL_SCHEMA,
13591    oid: oid::INDEX_MZ_SINK_STATUSES_IND_OID,
13592    sql: "IN CLUSTER mz_catalog_server
13593ON mz_internal.mz_sink_statuses (id)",
13594    is_retained_metrics_object: false,
13595};
13596
13597pub const MZ_SOURCE_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13598    name: "mz_source_status_history_ind",
13599    schema: MZ_INTERNAL_SCHEMA,
13600    oid: oid::INDEX_MZ_SOURCE_STATUS_HISTORY_IND_OID,
13601    sql: "IN CLUSTER mz_catalog_server
13602ON mz_internal.mz_source_status_history (source_id)",
13603    is_retained_metrics_object: false,
13604};
13605
13606pub const MZ_SINK_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13607    name: "mz_sink_status_history_ind",
13608    schema: MZ_INTERNAL_SCHEMA,
13609    oid: oid::INDEX_MZ_SINK_STATUS_HISTORY_IND_OID,
13610    sql: "IN CLUSTER mz_catalog_server
13611ON mz_internal.mz_sink_status_history (sink_id)",
13612    is_retained_metrics_object: false,
13613};
13614
13615pub const MZ_SHOW_CONTINUAL_TASKS_IND: BuiltinIndex = BuiltinIndex {
13616    name: "mz_show_continual_tasks_ind",
13617    schema: MZ_INTERNAL_SCHEMA,
13618    oid: oid::INDEX_MZ_SHOW_CONTINUAL_TASKS_OID,
13619    sql: "IN CLUSTER mz_catalog_server
13620ON mz_internal.mz_show_continual_tasks (id)",
13621    is_retained_metrics_object: false,
13622};
13623
13624// In both `mz_source_statistics` and `mz_sink_statistics` we cast the `SUM` of
13625// uint8's to `uint8` instead of leaving them as `numeric`. This is because we want to
13626// save index space, and we don't expect the sum to be > 2^63
13627// (even if a source with 2000 workers, that each produce 400 terabytes in a month ~ 2^61).
13628//
13629//
13630// These aggregations are just to make `GROUP BY` happy. Each id has a single row in the
13631// underlying relation.
13632//
13633// We append WITH_HISTORY because we want to build a separate view + index that doesn't
13634// retain history. This is because retaining its history causes MZ_SOURCE_STATISTICS_WITH_HISTORY_IND
13635// to hold all records/updates, which causes CPU and latency of querying it to spike.
13636pub static MZ_SOURCE_STATISTICS_WITH_HISTORY: LazyLock<BuiltinView> =
13637    LazyLock::new(|| BuiltinView {
13638        name: "mz_source_statistics_with_history",
13639        schema: MZ_INTERNAL_SCHEMA,
13640        oid: oid::VIEW_MZ_SOURCE_STATISTICS_WITH_HISTORY_OID,
13641        desc: RelationDesc::builder()
13642            .with_column("id", SqlScalarType::String.nullable(false))
13643            .with_column("replica_id", SqlScalarType::String.nullable(true))
13644            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13645            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13646            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13647            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13648            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13649            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13650            .with_column(
13651                "rehydration_latency",
13652                SqlScalarType::Interval.nullable(true),
13653            )
13654            .with_column(
13655                "snapshot_records_known",
13656                SqlScalarType::UInt64.nullable(true),
13657            )
13658            .with_column(
13659                "snapshot_records_staged",
13660                SqlScalarType::UInt64.nullable(true),
13661            )
13662            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13663            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13664            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13665            .with_key(vec![0, 1])
13666            .finish(),
13667        column_comments: BTreeMap::new(),
13668        sql: "
13669WITH
13670    -- For each subsource, statistics are reported as its parent source
13671    subsource_to_parent AS
13672    (
13673        SELECT subsource.id AS id, parent.id AS report_id
13674        FROM mz_catalog.mz_sources AS subsource
13675            JOIN mz_internal.mz_object_dependencies AS dep ON subsource.id = dep.object_id
13676            JOIN mz_catalog.mz_sources AS parent ON parent.id = dep.referenced_object_id
13677        WHERE subsource.type = 'subsource'
13678    ),
13679    -- For each table from source, statistics are reported as its parent source
13680    table_to_parent AS
13681    (
13682        SELECT id, source_id AS report_id
13683        FROM mz_catalog.mz_tables
13684        WHERE source_id IS NOT NULL
13685    ),
13686    -- For each source and subsource, statistics are reported as itself
13687    source_refl AS
13688    (
13689        SELECT id, id AS report_id
13690        FROM mz_catalog.mz_sources
13691        WHERE type NOT IN ('progress', 'log')
13692    ),
13693    -- For each table from source, statistics are reported as itself
13694    table_refl AS
13695    (
13696        SELECT id, id AS report_id
13697        FROM mz_catalog.mz_tables
13698        WHERE source_id IS NOT NULL
13699    ),
13700    report_paths AS
13701    (
13702        SELECT id, report_id FROM subsource_to_parent
13703        UNION ALL SELECT id, report_id FROM table_to_parent
13704        UNION ALL SELECT id, report_id FROM source_refl
13705        UNION ALL SELECT id, report_id FROM table_refl
13706    )
13707SELECT
13708    report_paths.report_id AS id,
13709    replica_id,
13710    -- Counters
13711    SUM(messages_received)::uint8 AS messages_received,
13712    SUM(bytes_received)::uint8 AS bytes_received,
13713    SUM(updates_staged)::uint8 AS updates_staged,
13714    SUM(updates_committed)::uint8 AS updates_committed,
13715    -- Resetting Gauges
13716    SUM(records_indexed)::uint8 AS records_indexed,
13717    SUM(bytes_indexed)::uint8 AS bytes_indexed,
13718    -- Ensure we aggregate to NULL when not all workers are done rehydrating.
13719    CASE
13720        WHEN bool_or(rehydration_latency IS NULL) THEN NULL
13721        ELSE MAX(rehydration_latency)::interval
13722    END AS rehydration_latency,
13723    SUM(snapshot_records_known)::uint8 AS snapshot_records_known,
13724    SUM(snapshot_records_staged)::uint8 AS snapshot_records_staged,
13725    bool_and(snapshot_committed) as snapshot_committed,
13726    -- Gauges
13727    MAX(offset_known)::uint8 AS offset_known,
13728    MIN(offset_committed)::uint8 AS offset_committed
13729FROM mz_internal.mz_source_statistics_raw
13730    JOIN report_paths USING (id)
13731GROUP BY report_paths.report_id, replica_id",
13732        access: vec![PUBLIC_SELECT],
13733    });
13734
13735pub const MZ_SOURCE_STATISTICS_WITH_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13736    name: "mz_source_statistics_with_history_ind",
13737    schema: MZ_INTERNAL_SCHEMA,
13738    oid: oid::INDEX_MZ_SOURCE_STATISTICS_WITH_HISTORY_IND_OID,
13739    sql: "IN CLUSTER mz_catalog_server
13740ON mz_internal.mz_source_statistics_with_history (id, replica_id)",
13741    is_retained_metrics_object: true,
13742};
13743
13744// The non historical version of MZ_SOURCE_STATISTICS_WITH_HISTORY.
13745// Used to query MZ_SOURCE_STATISTICS at the current time.
13746pub static MZ_SOURCE_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| {
13747    BuiltinView {
13748        name: "mz_source_statistics",
13749        schema: MZ_INTERNAL_SCHEMA,
13750        oid: oid::VIEW_MZ_SOURCE_STATISTICS_OID,
13751        // We need to add a redundant where clause for a new dataflow to be created.
13752        desc: RelationDesc::builder()
13753            .with_column("id", SqlScalarType::String.nullable(false))
13754            .with_column("replica_id", SqlScalarType::String.nullable(true))
13755            .with_column("messages_received", SqlScalarType::UInt64.nullable(false))
13756            .with_column("bytes_received", SqlScalarType::UInt64.nullable(false))
13757            .with_column("updates_staged", SqlScalarType::UInt64.nullable(false))
13758            .with_column("updates_committed", SqlScalarType::UInt64.nullable(false))
13759            .with_column("records_indexed", SqlScalarType::UInt64.nullable(false))
13760            .with_column("bytes_indexed", SqlScalarType::UInt64.nullable(false))
13761            .with_column(
13762                "rehydration_latency",
13763                SqlScalarType::Interval.nullable(true),
13764            )
13765            .with_column(
13766                "snapshot_records_known",
13767                SqlScalarType::UInt64.nullable(true),
13768            )
13769            .with_column(
13770                "snapshot_records_staged",
13771                SqlScalarType::UInt64.nullable(true),
13772            )
13773            .with_column("snapshot_committed", SqlScalarType::Bool.nullable(false))
13774            .with_column("offset_known", SqlScalarType::UInt64.nullable(true))
13775            .with_column("offset_committed", SqlScalarType::UInt64.nullable(true))
13776            .with_key(vec![0, 1])
13777            .finish(),
13778        column_comments: BTreeMap::from_iter([
13779            (
13780                "id",
13781                "The ID of the source. Corresponds to `mz_catalog.mz_sources.id`.",
13782            ),
13783            (
13784                "replica_id",
13785                "The ID of a replica running the source. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13786            ),
13787            (
13788                "messages_received",
13789                "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.",
13790            ),
13791            (
13792                "bytes_received",
13793                "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.",
13794            ),
13795            (
13796                "updates_staged",
13797                "The number of updates (insertions plus deletions) the source has written but not yet committed to the storage layer.",
13798            ),
13799            (
13800                "updates_committed",
13801                "The number of updates (insertions plus deletions) the source has committed to the storage layer.",
13802            ),
13803            (
13804                "records_indexed",
13805                "The number of individual records indexed in the source envelope state.",
13806            ),
13807            (
13808                "bytes_indexed",
13809                "The number of bytes stored in the source's internal index, if any.",
13810            ),
13811            (
13812                "rehydration_latency",
13813                "The amount of time it took for the source to rehydrate its internal index, if any, after the source last restarted.",
13814            ),
13815            (
13816                "snapshot_records_known",
13817                "The size of the source's snapshot, measured in number of records. See below to learn what constitutes a record.",
13818            ),
13819            (
13820                "snapshot_records_staged",
13821                "The number of records in the source's snapshot that Materialize has read. See below to learn what constitutes a record.",
13822            ),
13823            (
13824                "snapshot_committed",
13825                "Whether the source has committed the initial snapshot for a source.",
13826            ),
13827            (
13828                "offset_known",
13829                "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.",
13830            ),
13831            (
13832                "offset_committed",
13833                "The offset of the the data that Materialize has durably ingested. See below to learn what constitutes an offset.",
13834            ),
13835        ]),
13836        sql: "SELECT * FROM mz_internal.mz_source_statistics_with_history WHERE length(id) > 0",
13837        access: vec![PUBLIC_SELECT],
13838    }
13839});
13840
13841pub const MZ_SOURCE_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13842    name: "mz_source_statistics_ind",
13843    schema: MZ_INTERNAL_SCHEMA,
13844    oid: oid::INDEX_MZ_SOURCE_STATISTICS_IND_OID,
13845    sql: "IN CLUSTER mz_catalog_server
13846ON mz_internal.mz_source_statistics (id, replica_id)",
13847    is_retained_metrics_object: false,
13848};
13849
13850pub static MZ_SINK_STATISTICS: LazyLock<BuiltinView> = LazyLock::new(|| BuiltinView {
13851    name: "mz_sink_statistics",
13852    schema: MZ_INTERNAL_SCHEMA,
13853    oid: oid::VIEW_MZ_SINK_STATISTICS_OID,
13854    desc: RelationDesc::builder()
13855        .with_column("id", SqlScalarType::String.nullable(false))
13856        .with_column("replica_id", SqlScalarType::String.nullable(true))
13857        .with_column("messages_staged", SqlScalarType::UInt64.nullable(false))
13858        .with_column("messages_committed", SqlScalarType::UInt64.nullable(false))
13859        .with_column("bytes_staged", SqlScalarType::UInt64.nullable(false))
13860        .with_column("bytes_committed", SqlScalarType::UInt64.nullable(false))
13861        .with_key(vec![0, 1])
13862        .finish(),
13863    column_comments: BTreeMap::from_iter([
13864        (
13865            "id",
13866            "The ID of the sink. Corresponds to `mz_catalog.mz_sinks.id`.",
13867        ),
13868        (
13869            "replica_id",
13870            "The ID of a replica running the sink. Corresponds to `mz_catalog.mz_cluster_replicas.id`.",
13871        ),
13872        (
13873            "messages_staged",
13874            "The number of messages staged but possibly not committed to the sink.",
13875        ),
13876        (
13877            "messages_committed",
13878            "The number of messages committed to the sink.",
13879        ),
13880        (
13881            "bytes_staged",
13882            "The number of bytes staged but possibly not committed to the sink. This counts both keys and values, if applicable.",
13883        ),
13884        (
13885            "bytes_committed",
13886            "The number of bytes committed to the sink. This counts both keys and values, if applicable.",
13887        ),
13888    ]),
13889    sql: "
13890SELECT
13891    id,
13892    replica_id,
13893    SUM(messages_staged)::uint8 AS messages_staged,
13894    SUM(messages_committed)::uint8 AS messages_committed,
13895    SUM(bytes_staged)::uint8 AS bytes_staged,
13896    SUM(bytes_committed)::uint8 AS bytes_committed
13897FROM mz_internal.mz_sink_statistics_raw
13898GROUP BY id, replica_id",
13899    access: vec![PUBLIC_SELECT],
13900});
13901
13902pub const MZ_SINK_STATISTICS_IND: BuiltinIndex = BuiltinIndex {
13903    name: "mz_sink_statistics_ind",
13904    schema: MZ_INTERNAL_SCHEMA,
13905    oid: oid::INDEX_MZ_SINK_STATISTICS_IND_OID,
13906    sql: "IN CLUSTER mz_catalog_server
13907ON mz_internal.mz_sink_statistics (id, replica_id)",
13908    is_retained_metrics_object: true,
13909};
13910
13911pub const MZ_CLUSTER_REPLICAS_IND: BuiltinIndex = BuiltinIndex {
13912    name: "mz_cluster_replicas_ind",
13913    schema: MZ_CATALOG_SCHEMA,
13914    oid: oid::INDEX_MZ_CLUSTER_REPLICAS_IND_OID,
13915    sql: "IN CLUSTER mz_catalog_server
13916ON mz_catalog.mz_cluster_replicas (id)",
13917    is_retained_metrics_object: true,
13918};
13919
13920pub const MZ_CLUSTER_REPLICA_SIZES_IND: BuiltinIndex = BuiltinIndex {
13921    name: "mz_cluster_replica_sizes_ind",
13922    schema: MZ_CATALOG_SCHEMA,
13923    oid: oid::INDEX_MZ_CLUSTER_REPLICA_SIZES_IND_OID,
13924    sql: "IN CLUSTER mz_catalog_server
13925ON mz_catalog.mz_cluster_replica_sizes (size)",
13926    is_retained_metrics_object: true,
13927};
13928
13929pub const MZ_CLUSTER_REPLICA_STATUSES_IND: BuiltinIndex = BuiltinIndex {
13930    name: "mz_cluster_replica_statuses_ind",
13931    schema: MZ_INTERNAL_SCHEMA,
13932    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUSES_IND_OID,
13933    sql: "IN CLUSTER mz_catalog_server
13934ON mz_internal.mz_cluster_replica_statuses (replica_id)",
13935    is_retained_metrics_object: false,
13936};
13937
13938pub const MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13939    name: "mz_cluster_replica_status_history_ind",
13940    schema: MZ_INTERNAL_SCHEMA,
13941    oid: oid::INDEX_MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND_OID,
13942    sql: "IN CLUSTER mz_catalog_server
13943ON mz_internal.mz_cluster_replica_status_history (replica_id)",
13944    is_retained_metrics_object: false,
13945};
13946
13947pub const MZ_CLUSTER_REPLICA_METRICS_IND: BuiltinIndex = BuiltinIndex {
13948    name: "mz_cluster_replica_metrics_ind",
13949    schema: MZ_INTERNAL_SCHEMA,
13950    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_IND_OID,
13951    sql: "IN CLUSTER mz_catalog_server
13952ON mz_internal.mz_cluster_replica_metrics (replica_id)",
13953    is_retained_metrics_object: false,
13954};
13955
13956pub const MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13957    name: "mz_cluster_replica_metrics_history_ind",
13958    schema: MZ_INTERNAL_SCHEMA,
13959    oid: oid::INDEX_MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND_OID,
13960    sql: "IN CLUSTER mz_catalog_server
13961ON mz_internal.mz_cluster_replica_metrics_history (replica_id)",
13962    is_retained_metrics_object: false,
13963};
13964
13965pub const MZ_CLUSTER_REPLICA_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13966    name: "mz_cluster_replica_history_ind",
13967    schema: MZ_INTERNAL_SCHEMA,
13968    oid: oid::INDEX_MZ_CLUSTER_REPLICA_HISTORY_IND_OID,
13969    sql: "IN CLUSTER mz_catalog_server
13970ON mz_internal.mz_cluster_replica_history (dropped_at)",
13971    is_retained_metrics_object: true,
13972};
13973
13974pub const MZ_CLUSTER_REPLICA_NAME_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13975    name: "mz_cluster_replica_name_history_ind",
13976    schema: MZ_INTERNAL_SCHEMA,
13977    oid: oid::INDEX_MZ_CLUSTER_REPLICA_NAME_HISTORY_IND_OID,
13978    sql: "IN CLUSTER mz_catalog_server
13979ON mz_internal.mz_cluster_replica_name_history (id)",
13980    is_retained_metrics_object: false,
13981};
13982
13983pub const MZ_OBJECT_LIFETIMES_IND: BuiltinIndex = BuiltinIndex {
13984    name: "mz_object_lifetimes_ind",
13985    schema: MZ_INTERNAL_SCHEMA,
13986    oid: oid::INDEX_MZ_OBJECT_LIFETIMES_IND_OID,
13987    sql: "IN CLUSTER mz_catalog_server
13988ON mz_internal.mz_object_lifetimes (id)",
13989    is_retained_metrics_object: false,
13990};
13991
13992pub const MZ_OBJECT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
13993    name: "mz_object_history_ind",
13994    schema: MZ_INTERNAL_SCHEMA,
13995    oid: oid::INDEX_MZ_OBJECT_HISTORY_IND_OID,
13996    sql: "IN CLUSTER mz_catalog_server
13997ON mz_internal.mz_object_history (id)",
13998    is_retained_metrics_object: false,
13999};
14000
14001pub const MZ_OBJECT_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
14002    name: "mz_object_dependencies_ind",
14003    schema: MZ_INTERNAL_SCHEMA,
14004    oid: oid::INDEX_MZ_OBJECT_DEPENDENCIES_IND_OID,
14005    sql: "IN CLUSTER mz_catalog_server
14006ON mz_internal.mz_object_dependencies (object_id)",
14007    is_retained_metrics_object: true,
14008};
14009
14010pub const MZ_COMPUTE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
14011    name: "mz_compute_dependencies_ind",
14012    schema: MZ_INTERNAL_SCHEMA,
14013    oid: oid::INDEX_MZ_COMPUTE_DEPENDENCIES_IND_OID,
14014    sql: "IN CLUSTER mz_catalog_server
14015ON mz_internal.mz_compute_dependencies (dependency_id)",
14016    is_retained_metrics_object: false,
14017};
14018
14019pub const MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND: BuiltinIndex = BuiltinIndex {
14020    name: "mz_object_transitive_dependencies_ind",
14021    schema: MZ_INTERNAL_SCHEMA,
14022    oid: oid::INDEX_MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND_OID,
14023    sql: "IN CLUSTER mz_catalog_server
14024ON mz_internal.mz_object_transitive_dependencies (object_id)",
14025    is_retained_metrics_object: false,
14026};
14027
14028pub const MZ_FRONTIERS_IND: BuiltinIndex = BuiltinIndex {
14029    name: "mz_frontiers_ind",
14030    schema: MZ_INTERNAL_SCHEMA,
14031    oid: oid::INDEX_MZ_FRONTIERS_IND_OID,
14032    sql: "IN CLUSTER mz_catalog_server
14033ON mz_internal.mz_frontiers (object_id)",
14034    is_retained_metrics_object: false,
14035};
14036
14037pub const MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND: BuiltinIndex = BuiltinIndex {
14038    name: "mz_wallclock_global_lag_recent_history_ind",
14039    schema: MZ_INTERNAL_SCHEMA,
14040    oid: oid::INDEX_MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND_OID,
14041    sql: "IN CLUSTER mz_catalog_server
14042ON mz_internal.mz_wallclock_global_lag_recent_history (object_id)",
14043    is_retained_metrics_object: false,
14044};
14045
14046pub const MZ_RECENT_ACTIVITY_LOG_THINNED_IND: BuiltinIndex = BuiltinIndex {
14047    name: "mz_recent_activity_log_thinned_ind",
14048    schema: MZ_INTERNAL_SCHEMA,
14049    oid: oid::INDEX_MZ_RECENT_ACTIVITY_LOG_THINNED_IND_OID,
14050    sql: "IN CLUSTER mz_catalog_server
14051-- sql_hash because we plan to join
14052-- this against mz_internal.mz_sql_text
14053ON mz_internal.mz_recent_activity_log_thinned (sql_hash)",
14054    is_retained_metrics_object: false,
14055};
14056
14057pub const MZ_KAFKA_SOURCES_IND: BuiltinIndex = BuiltinIndex {
14058    name: "mz_kafka_sources_ind",
14059    schema: MZ_CATALOG_SCHEMA,
14060    oid: oid::INDEX_MZ_KAFKA_SOURCES_IND_OID,
14061    sql: "IN CLUSTER mz_catalog_server
14062ON mz_catalog.mz_kafka_sources (id)",
14063    is_retained_metrics_object: true,
14064};
14065
14066pub const MZ_WEBHOOK_SOURCES_IND: BuiltinIndex = BuiltinIndex {
14067    name: "mz_webhook_sources_ind",
14068    schema: MZ_INTERNAL_SCHEMA,
14069    oid: oid::INDEX_MZ_WEBHOOK_SOURCES_IND_OID,
14070    sql: "IN CLUSTER mz_catalog_server
14071ON mz_internal.mz_webhook_sources (id)",
14072    is_retained_metrics_object: true,
14073};
14074
14075pub const MZ_COMMENTS_IND: BuiltinIndex = BuiltinIndex {
14076    name: "mz_comments_ind",
14077    schema: MZ_INTERNAL_SCHEMA,
14078    oid: oid::INDEX_MZ_COMMENTS_IND_OID,
14079    sql: "IN CLUSTER mz_catalog_server
14080ON mz_internal.mz_comments (id)",
14081    is_retained_metrics_object: true,
14082};
14083
14084pub static MZ_ANALYTICS: BuiltinConnection = BuiltinConnection {
14085    name: "mz_analytics",
14086    schema: MZ_INTERNAL_SCHEMA,
14087    oid: oid::CONNECTION_MZ_ANALYTICS_OID,
14088    sql: "CREATE CONNECTION mz_internal.mz_analytics TO AWS (ASSUME ROLE ARN = '')",
14089    access: &[MzAclItem {
14090        grantee: MZ_SYSTEM_ROLE_ID,
14091        grantor: MZ_ANALYTICS_ROLE_ID,
14092        acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Connection)),
14093    }],
14094    owner_id: &MZ_ANALYTICS_ROLE_ID,
14095    runtime_alterable: true,
14096};
14097
14098pub const MZ_SYSTEM_ROLE: BuiltinRole = BuiltinRole {
14099    id: MZ_SYSTEM_ROLE_ID,
14100    name: SYSTEM_USER_NAME,
14101    oid: oid::ROLE_MZ_SYSTEM_OID,
14102    attributes: RoleAttributesRaw::new().with_all(),
14103};
14104
14105pub const MZ_SUPPORT_ROLE: BuiltinRole = BuiltinRole {
14106    id: MZ_SUPPORT_ROLE_ID,
14107    name: SUPPORT_USER_NAME,
14108    oid: oid::ROLE_MZ_SUPPORT_OID,
14109    attributes: RoleAttributesRaw::new(),
14110};
14111
14112pub const MZ_ANALYTICS_ROLE: BuiltinRole = BuiltinRole {
14113    id: MZ_ANALYTICS_ROLE_ID,
14114    name: ANALYTICS_USER_NAME,
14115    oid: oid::ROLE_MZ_ANALYTICS_OID,
14116    attributes: RoleAttributesRaw::new(),
14117};
14118
14119/// This role can `SELECT` from various query history objects,
14120/// e.g. `mz_prepared_statement_history`.
14121pub const MZ_MONITOR_ROLE: BuiltinRole = BuiltinRole {
14122    id: MZ_MONITOR_ROLE_ID,
14123    name: "mz_monitor",
14124    oid: oid::ROLE_MZ_MONITOR_OID,
14125    attributes: RoleAttributesRaw::new(),
14126};
14127
14128/// This role is like [`MZ_MONITOR_ROLE`], but can only query
14129/// the redacted versions of the objects.
14130pub const MZ_MONITOR_REDACTED: BuiltinRole = BuiltinRole {
14131    id: MZ_MONITOR_REDACTED_ROLE_ID,
14132    name: "mz_monitor_redacted",
14133    oid: oid::ROLE_MZ_MONITOR_REDACTED_OID,
14134    attributes: RoleAttributesRaw::new(),
14135};
14136
14137pub const MZ_SYSTEM_CLUSTER: BuiltinCluster = BuiltinCluster {
14138    name: SYSTEM_USER_NAME,
14139    owner_id: &MZ_SYSTEM_ROLE_ID,
14140    privileges: &[
14141        MzAclItem {
14142            grantee: MZ_SUPPORT_ROLE_ID,
14143            grantor: MZ_SYSTEM_ROLE_ID,
14144            acl_mode: AclMode::USAGE,
14145        },
14146        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
14147    ],
14148};
14149
14150pub const MZ_SYSTEM_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
14151    name: BUILTIN_CLUSTER_REPLICA_NAME,
14152    cluster_name: MZ_SYSTEM_CLUSTER.name,
14153};
14154
14155pub const MZ_CATALOG_SERVER_CLUSTER: BuiltinCluster = BuiltinCluster {
14156    name: "mz_catalog_server",
14157    owner_id: &MZ_SYSTEM_ROLE_ID,
14158    privileges: &[
14159        MzAclItem {
14160            grantee: RoleId::Public,
14161            grantor: MZ_SYSTEM_ROLE_ID,
14162            acl_mode: AclMode::USAGE,
14163        },
14164        MzAclItem {
14165            grantee: MZ_SUPPORT_ROLE_ID,
14166            grantor: MZ_SYSTEM_ROLE_ID,
14167            acl_mode: AclMode::USAGE.union(AclMode::CREATE),
14168        },
14169        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
14170    ],
14171};
14172
14173pub const MZ_CATALOG_SERVER_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
14174    name: BUILTIN_CLUSTER_REPLICA_NAME,
14175    cluster_name: MZ_CATALOG_SERVER_CLUSTER.name,
14176};
14177
14178pub const MZ_PROBE_CLUSTER: BuiltinCluster = BuiltinCluster {
14179    name: "mz_probe",
14180    owner_id: &MZ_SYSTEM_ROLE_ID,
14181    privileges: &[
14182        MzAclItem {
14183            grantee: MZ_SUPPORT_ROLE_ID,
14184            grantor: MZ_SYSTEM_ROLE_ID,
14185            acl_mode: AclMode::USAGE,
14186        },
14187        MzAclItem {
14188            grantee: MZ_MONITOR_ROLE_ID,
14189            grantor: MZ_SYSTEM_ROLE_ID,
14190            acl_mode: AclMode::USAGE,
14191        },
14192        rbac::owner_privilege(ObjectType::Cluster, MZ_SYSTEM_ROLE_ID),
14193    ],
14194};
14195pub const MZ_PROBE_CLUSTER_REPLICA: BuiltinClusterReplica = BuiltinClusterReplica {
14196    name: BUILTIN_CLUSTER_REPLICA_NAME,
14197    cluster_name: MZ_PROBE_CLUSTER.name,
14198};
14199
14200pub const MZ_SUPPORT_CLUSTER: BuiltinCluster = BuiltinCluster {
14201    name: "mz_support",
14202    owner_id: &MZ_SUPPORT_ROLE_ID,
14203    privileges: &[
14204        MzAclItem {
14205            grantee: MZ_SYSTEM_ROLE_ID,
14206            grantor: MZ_SUPPORT_ROLE_ID,
14207            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
14208        },
14209        rbac::owner_privilege(ObjectType::Cluster, MZ_SUPPORT_ROLE_ID),
14210    ],
14211};
14212
14213pub const MZ_ANALYTICS_CLUSTER: BuiltinCluster = BuiltinCluster {
14214    name: "mz_analytics",
14215    owner_id: &MZ_ANALYTICS_ROLE_ID,
14216    privileges: &[
14217        MzAclItem {
14218            grantee: MZ_SYSTEM_ROLE_ID,
14219            grantor: MZ_ANALYTICS_ROLE_ID,
14220            acl_mode: rbac::all_object_privileges(SystemObjectType::Object(ObjectType::Cluster)),
14221        },
14222        rbac::owner_privilege(ObjectType::Cluster, MZ_ANALYTICS_ROLE_ID),
14223    ],
14224};
14225
14226/// List of all builtin objects sorted topologically by dependency.
14227pub static BUILTINS_STATIC: LazyLock<Vec<Builtin<NameReference>>> = LazyLock::new(|| {
14228    let mut builtin_types = vec![
14229        Builtin::Type(&TYPE_ANY),
14230        Builtin::Type(&TYPE_ANYARRAY),
14231        Builtin::Type(&TYPE_ANYELEMENT),
14232        Builtin::Type(&TYPE_ANYNONARRAY),
14233        Builtin::Type(&TYPE_ANYRANGE),
14234        Builtin::Type(&TYPE_BOOL),
14235        Builtin::Type(&TYPE_BOOL_ARRAY),
14236        Builtin::Type(&TYPE_BYTEA),
14237        Builtin::Type(&TYPE_BYTEA_ARRAY),
14238        Builtin::Type(&TYPE_BPCHAR),
14239        Builtin::Type(&TYPE_BPCHAR_ARRAY),
14240        Builtin::Type(&TYPE_CHAR),
14241        Builtin::Type(&TYPE_CHAR_ARRAY),
14242        Builtin::Type(&TYPE_DATE),
14243        Builtin::Type(&TYPE_DATE_ARRAY),
14244        Builtin::Type(&TYPE_FLOAT4),
14245        Builtin::Type(&TYPE_FLOAT4_ARRAY),
14246        Builtin::Type(&TYPE_FLOAT8),
14247        Builtin::Type(&TYPE_FLOAT8_ARRAY),
14248        Builtin::Type(&TYPE_INT4),
14249        Builtin::Type(&TYPE_INT4_ARRAY),
14250        Builtin::Type(&TYPE_INT8),
14251        Builtin::Type(&TYPE_INT8_ARRAY),
14252        Builtin::Type(&TYPE_INTERVAL),
14253        Builtin::Type(&TYPE_INTERVAL_ARRAY),
14254        Builtin::Type(&TYPE_JSONB),
14255        Builtin::Type(&TYPE_JSONB_ARRAY),
14256        Builtin::Type(&TYPE_LIST),
14257        Builtin::Type(&TYPE_MAP),
14258        Builtin::Type(&TYPE_NAME),
14259        Builtin::Type(&TYPE_NAME_ARRAY),
14260        Builtin::Type(&TYPE_NUMERIC),
14261        Builtin::Type(&TYPE_NUMERIC_ARRAY),
14262        Builtin::Type(&TYPE_OID),
14263        Builtin::Type(&TYPE_OID_ARRAY),
14264        Builtin::Type(&TYPE_RECORD),
14265        Builtin::Type(&TYPE_RECORD_ARRAY),
14266        Builtin::Type(&TYPE_REGCLASS),
14267        Builtin::Type(&TYPE_REGCLASS_ARRAY),
14268        Builtin::Type(&TYPE_REGPROC),
14269        Builtin::Type(&TYPE_REGPROC_ARRAY),
14270        Builtin::Type(&TYPE_REGTYPE),
14271        Builtin::Type(&TYPE_REGTYPE_ARRAY),
14272        Builtin::Type(&TYPE_INT2),
14273        Builtin::Type(&TYPE_INT2_ARRAY),
14274        Builtin::Type(&TYPE_TEXT),
14275        Builtin::Type(&TYPE_TEXT_ARRAY),
14276        Builtin::Type(&TYPE_TIME),
14277        Builtin::Type(&TYPE_TIME_ARRAY),
14278        Builtin::Type(&TYPE_TIMESTAMP),
14279        Builtin::Type(&TYPE_TIMESTAMP_ARRAY),
14280        Builtin::Type(&TYPE_TIMESTAMPTZ),
14281        Builtin::Type(&TYPE_TIMESTAMPTZ_ARRAY),
14282        Builtin::Type(&TYPE_UUID),
14283        Builtin::Type(&TYPE_UUID_ARRAY),
14284        Builtin::Type(&TYPE_VARCHAR),
14285        Builtin::Type(&TYPE_VARCHAR_ARRAY),
14286        Builtin::Type(&TYPE_INT2_VECTOR),
14287        Builtin::Type(&TYPE_INT2_VECTOR_ARRAY),
14288        Builtin::Type(&TYPE_ANYCOMPATIBLE),
14289        Builtin::Type(&TYPE_ANYCOMPATIBLEARRAY),
14290        Builtin::Type(&TYPE_ANYCOMPATIBLENONARRAY),
14291        Builtin::Type(&TYPE_ANYCOMPATIBLELIST),
14292        Builtin::Type(&TYPE_ANYCOMPATIBLEMAP),
14293        Builtin::Type(&TYPE_ANYCOMPATIBLERANGE),
14294        Builtin::Type(&TYPE_UINT2),
14295        Builtin::Type(&TYPE_UINT2_ARRAY),
14296        Builtin::Type(&TYPE_UINT4),
14297        Builtin::Type(&TYPE_UINT4_ARRAY),
14298        Builtin::Type(&TYPE_UINT8),
14299        Builtin::Type(&TYPE_UINT8_ARRAY),
14300        Builtin::Type(&TYPE_MZ_TIMESTAMP),
14301        Builtin::Type(&TYPE_MZ_TIMESTAMP_ARRAY),
14302        Builtin::Type(&TYPE_INT4_RANGE),
14303        Builtin::Type(&TYPE_INT4_RANGE_ARRAY),
14304        Builtin::Type(&TYPE_INT8_RANGE),
14305        Builtin::Type(&TYPE_INT8_RANGE_ARRAY),
14306        Builtin::Type(&TYPE_DATE_RANGE),
14307        Builtin::Type(&TYPE_DATE_RANGE_ARRAY),
14308        Builtin::Type(&TYPE_NUM_RANGE),
14309        Builtin::Type(&TYPE_NUM_RANGE_ARRAY),
14310        Builtin::Type(&TYPE_TS_RANGE),
14311        Builtin::Type(&TYPE_TS_RANGE_ARRAY),
14312        Builtin::Type(&TYPE_TSTZ_RANGE),
14313        Builtin::Type(&TYPE_TSTZ_RANGE_ARRAY),
14314        Builtin::Type(&TYPE_MZ_ACL_ITEM),
14315        Builtin::Type(&TYPE_MZ_ACL_ITEM_ARRAY),
14316        Builtin::Type(&TYPE_ACL_ITEM),
14317        Builtin::Type(&TYPE_ACL_ITEM_ARRAY),
14318        Builtin::Type(&TYPE_INTERNAL),
14319    ];
14320
14321    let mut builtin_funcs = Vec::new();
14322    for (schema, funcs) in &[
14323        (PG_CATALOG_SCHEMA, &*mz_sql::func::PG_CATALOG_BUILTINS),
14324        (
14325            INFORMATION_SCHEMA,
14326            &*mz_sql::func::INFORMATION_SCHEMA_BUILTINS,
14327        ),
14328        (MZ_CATALOG_SCHEMA, &*mz_sql::func::MZ_CATALOG_BUILTINS),
14329        (MZ_INTERNAL_SCHEMA, &*mz_sql::func::MZ_INTERNAL_BUILTINS),
14330        (MZ_UNSAFE_SCHEMA, &*mz_sql::func::MZ_UNSAFE_BUILTINS),
14331    ] {
14332        for (name, func) in funcs.iter() {
14333            builtin_funcs.push(Builtin::Func(BuiltinFunc {
14334                name,
14335                schema,
14336                inner: func,
14337            }));
14338        }
14339    }
14340
14341    let mut builtin_items = vec![
14342        Builtin::Source(&MZ_CATALOG_RAW),
14343        Builtin::Log(&MZ_ARRANGEMENT_SHARING_RAW),
14344        Builtin::Log(&MZ_ARRANGEMENT_BATCHES_RAW),
14345        Builtin::Log(&MZ_ARRANGEMENT_RECORDS_RAW),
14346        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_RECORDS_RAW),
14347        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_SIZE_RAW),
14348        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_CAPACITY_RAW),
14349        Builtin::Log(&MZ_ARRANGEMENT_BATCHER_ALLOCATIONS_RAW),
14350        Builtin::Log(&MZ_DATAFLOW_CHANNELS_PER_WORKER),
14351        Builtin::Log(&MZ_DATAFLOW_OPERATORS_PER_WORKER),
14352        Builtin::Log(&MZ_DATAFLOW_ADDRESSES_PER_WORKER),
14353        Builtin::Log(&MZ_DATAFLOW_OPERATOR_REACHABILITY_RAW),
14354        Builtin::Log(&MZ_COMPUTE_EXPORTS_PER_WORKER),
14355        Builtin::Log(&MZ_COMPUTE_DATAFLOW_GLOBAL_IDS_PER_WORKER),
14356        Builtin::Log(&MZ_CLUSTER_PROMETHEUS_METRICS),
14357        Builtin::Log(&MZ_MESSAGE_COUNTS_RECEIVED_RAW),
14358        Builtin::Log(&MZ_MESSAGE_COUNTS_SENT_RAW),
14359        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_RECEIVED_RAW),
14360        Builtin::Log(&MZ_MESSAGE_BATCH_COUNTS_SENT_RAW),
14361        Builtin::Log(&MZ_ACTIVE_PEEKS_PER_WORKER),
14362        Builtin::Log(&MZ_PEEK_DURATIONS_HISTOGRAM_RAW),
14363        Builtin::Log(&MZ_ARRANGEMENT_HEAP_CAPACITY_RAW),
14364        Builtin::Log(&MZ_ARRANGEMENT_HEAP_ALLOCATIONS_RAW),
14365        Builtin::Log(&MZ_ARRANGEMENT_HEAP_SIZE_RAW),
14366        Builtin::Log(&MZ_SCHEDULING_ELAPSED_RAW),
14367        Builtin::Log(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_RAW),
14368        Builtin::Log(&MZ_SCHEDULING_PARKS_HISTOGRAM_RAW),
14369        Builtin::Log(&MZ_COMPUTE_FRONTIERS_PER_WORKER),
14370        Builtin::Log(&MZ_COMPUTE_IMPORT_FRONTIERS_PER_WORKER),
14371        Builtin::Log(&MZ_COMPUTE_ERROR_COUNTS_RAW),
14372        Builtin::Log(&MZ_COMPUTE_HYDRATION_TIMES_PER_WORKER),
14373        Builtin::Log(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES_PER_WORKER),
14374        Builtin::Table(&MZ_KAFKA_SINKS),
14375        Builtin::Table(&MZ_KAFKA_CONNECTIONS),
14376        Builtin::Table(&MZ_KAFKA_SOURCES),
14377        Builtin::Table(&MZ_OBJECT_DEPENDENCIES),
14378        Builtin::Table(&MZ_ICEBERG_SINKS),
14379        Builtin::MaterializedView(&MZ_DATABASES),
14380        Builtin::MaterializedView(&MZ_SCHEMAS),
14381        Builtin::Table(&MZ_COLUMNS),
14382        Builtin::Table(&MZ_INDEXES),
14383        Builtin::Table(&MZ_INDEX_COLUMNS),
14384        Builtin::Table(&MZ_TABLES),
14385        Builtin::Table(&MZ_SOURCES),
14386        Builtin::Table(&MZ_SOURCE_REFERENCES),
14387        Builtin::Table(&MZ_POSTGRES_SOURCES),
14388        Builtin::Table(&MZ_POSTGRES_SOURCE_TABLES),
14389        Builtin::Table(&MZ_MYSQL_SOURCE_TABLES),
14390        Builtin::Table(&MZ_SQL_SERVER_SOURCE_TABLES),
14391        Builtin::Table(&MZ_KAFKA_SOURCE_TABLES),
14392        Builtin::Table(&MZ_SINKS),
14393        Builtin::Table(&MZ_VIEWS),
14394        Builtin::Table(&MZ_TYPES),
14395        Builtin::Table(&MZ_TYPE_PG_METADATA),
14396        Builtin::Table(&MZ_ARRAY_TYPES),
14397        Builtin::Table(&MZ_BASE_TYPES),
14398        Builtin::Table(&MZ_LIST_TYPES),
14399        Builtin::Table(&MZ_MAP_TYPES),
14400        Builtin::Table(&MZ_ROLES),
14401        Builtin::Table(&MZ_ROLE_AUTH),
14402        Builtin::MaterializedView(&MZ_ROLE_MEMBERS),
14403        Builtin::Table(&MZ_ROLE_PARAMETERS),
14404        Builtin::Table(&MZ_PSEUDO_TYPES),
14405        Builtin::Table(&MZ_FUNCTIONS),
14406        Builtin::Table(&MZ_OPERATORS),
14407        Builtin::Table(&MZ_AGGREGATES),
14408        Builtin::Table(&MZ_CLUSTERS),
14409        Builtin::MaterializedView(&MZ_CLUSTER_WORKLOAD_CLASSES),
14410        Builtin::Table(&MZ_CLUSTER_SCHEDULES),
14411        Builtin::MaterializedView(&MZ_SECRETS),
14412        Builtin::MaterializedView(&MZ_CONNECTIONS),
14413        Builtin::Table(&MZ_SSH_TUNNEL_CONNECTIONS),
14414        Builtin::Table(&MZ_CLUSTER_REPLICAS),
14415        Builtin::Source(&MZ_CLUSTER_REPLICA_METRICS_HISTORY),
14416        Builtin::View(&MZ_CLUSTER_REPLICA_METRICS),
14417        Builtin::Table(&MZ_CLUSTER_REPLICA_SIZES),
14418        Builtin::Source(&MZ_CLUSTER_REPLICA_STATUS_HISTORY),
14419        Builtin::View(&MZ_CLUSTER_REPLICA_STATUSES),
14420        Builtin::MaterializedView(&MZ_INTERNAL_CLUSTER_REPLICAS),
14421        Builtin::MaterializedView(&MZ_PENDING_CLUSTER_REPLICAS),
14422        Builtin::Table(&MZ_AUDIT_EVENTS),
14423        Builtin::Table(&MZ_STORAGE_USAGE_BY_SHARD),
14424        Builtin::Table(&MZ_EGRESS_IPS),
14425        Builtin::Table(&MZ_AWS_PRIVATELINK_CONNECTIONS),
14426        Builtin::Table(&MZ_AWS_CONNECTIONS),
14427        Builtin::Table(&MZ_SUBSCRIPTIONS),
14428        Builtin::Table(&MZ_SESSIONS),
14429        Builtin::Table(&MZ_DEFAULT_PRIVILEGES),
14430        Builtin::Table(&MZ_SYSTEM_PRIVILEGES),
14431        Builtin::Table(&MZ_COMMENTS),
14432        Builtin::Table(&MZ_WEBHOOKS_SOURCES),
14433        Builtin::Table(&MZ_HISTORY_RETENTION_STRATEGIES),
14434        Builtin::MaterializedView(&MZ_MATERIALIZED_VIEWS),
14435        Builtin::Table(&MZ_MATERIALIZED_VIEW_REFRESH_STRATEGIES),
14436        Builtin::Table(&MZ_CONTINUAL_TASKS),
14437        Builtin::MaterializedView(&MZ_NETWORK_POLICIES),
14438        Builtin::MaterializedView(&MZ_NETWORK_POLICY_RULES),
14439        Builtin::Table(&MZ_LICENSE_KEYS),
14440        Builtin::Table(&MZ_REPLACEMENTS),
14441        Builtin::View(&MZ_RELATIONS),
14442        Builtin::View(&MZ_OBJECT_OID_ALIAS),
14443        Builtin::View(&MZ_OBJECTS),
14444        Builtin::View(&MZ_OBJECT_FULLY_QUALIFIED_NAMES),
14445        Builtin::View(&MZ_OBJECTS_ID_NAMESPACE_TYPES),
14446        Builtin::View(&MZ_OBJECT_HISTORY),
14447        Builtin::View(&MZ_OBJECT_LIFETIMES),
14448        Builtin::Table(&MZ_OBJECT_GLOBAL_IDS),
14449        Builtin::View(&MZ_ARRANGEMENT_SHARING_PER_WORKER),
14450        Builtin::View(&MZ_ARRANGEMENT_SHARING),
14451        Builtin::View(&MZ_ARRANGEMENT_SIZES_PER_WORKER),
14452        Builtin::View(&MZ_ARRANGEMENT_SIZES),
14453        Builtin::View(&MZ_DATAFLOWS_PER_WORKER),
14454        Builtin::View(&MZ_DATAFLOWS),
14455        Builtin::View(&MZ_DATAFLOW_ADDRESSES),
14456        Builtin::View(&MZ_DATAFLOW_CHANNELS),
14457        Builtin::View(&MZ_DATAFLOW_OPERATORS),
14458        Builtin::View(&MZ_DATAFLOW_GLOBAL_IDS),
14459        Builtin::View(&MZ_COMPUTE_EXPORTS),
14460        Builtin::View(&MZ_MAPPABLE_OBJECTS),
14461        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS_PER_WORKER),
14462        Builtin::View(&MZ_DATAFLOW_OPERATOR_DATAFLOWS),
14463        Builtin::View(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES),
14464        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY_PER_WORKER),
14465        Builtin::View(&MZ_DATAFLOW_OPERATOR_REACHABILITY),
14466        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION),
14467        Builtin::View(&MZ_CLUSTER_REPLICA_UTILIZATION_HISTORY),
14468        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS_PER_WORKER),
14469        Builtin::View(&MZ_DATAFLOW_OPERATOR_PARENTS),
14470        Builtin::View(&MZ_DATAFLOW_ARRANGEMENT_SIZES),
14471        Builtin::View(&MZ_EXPECTED_GROUP_SIZE_ADVICE),
14472        Builtin::View(&MZ_COMPUTE_FRONTIERS),
14473        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS_PER_WORKER),
14474        Builtin::View(&MZ_DATAFLOW_CHANNEL_OPERATORS),
14475        Builtin::View(&MZ_COMPUTE_IMPORT_FRONTIERS),
14476        Builtin::View(&MZ_MESSAGE_COUNTS_PER_WORKER),
14477        Builtin::View(&MZ_MESSAGE_COUNTS),
14478        Builtin::View(&MZ_ACTIVE_PEEKS),
14479        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM_PER_WORKER),
14480        Builtin::View(&MZ_COMPUTE_OPERATOR_DURATIONS_HISTOGRAM),
14481        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR_PER_WORKER),
14482        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_OPERATOR),
14483        Builtin::View(&MZ_RECORDS_PER_DATAFLOW_PER_WORKER),
14484        Builtin::View(&MZ_RECORDS_PER_DATAFLOW),
14485        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM_PER_WORKER),
14486        Builtin::View(&MZ_PEEK_DURATIONS_HISTOGRAM),
14487        Builtin::View(&MZ_SCHEDULING_ELAPSED_PER_WORKER),
14488        Builtin::View(&MZ_SCHEDULING_ELAPSED),
14489        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM_PER_WORKER),
14490        Builtin::View(&MZ_SCHEDULING_PARKS_HISTOGRAM),
14491        Builtin::View(&MZ_SHOW_ALL_OBJECTS),
14492        Builtin::View(&MZ_SHOW_COLUMNS),
14493        Builtin::View(&MZ_SHOW_CLUSTERS),
14494        Builtin::View(&MZ_SHOW_SECRETS),
14495        Builtin::View(&MZ_SHOW_DATABASES),
14496        Builtin::View(&MZ_SHOW_SCHEMAS),
14497        Builtin::View(&MZ_SHOW_TABLES),
14498        Builtin::View(&MZ_SHOW_VIEWS),
14499        Builtin::View(&MZ_SHOW_TYPES),
14500        Builtin::View(&MZ_SHOW_ROLES),
14501        Builtin::View(&MZ_SHOW_CONNECTIONS),
14502        Builtin::View(&MZ_SHOW_SOURCES),
14503        Builtin::View(&MZ_SHOW_SINKS),
14504        Builtin::View(&MZ_SHOW_MATERIALIZED_VIEWS),
14505        Builtin::View(&MZ_SHOW_INDEXES),
14506        Builtin::View(&MZ_SHOW_CONTINUAL_TASKS),
14507        Builtin::View(&MZ_CLUSTER_REPLICA_HISTORY),
14508        Builtin::View(&MZ_CLUSTER_REPLICA_NAME_HISTORY),
14509        Builtin::View(&MZ_TIMEZONE_NAMES),
14510        Builtin::View(&MZ_TIMEZONE_ABBREVIATIONS),
14511        Builtin::View(&PG_NAMESPACE_ALL_DATABASES),
14512        Builtin::Index(&PG_NAMESPACE_ALL_DATABASES_IND),
14513        Builtin::View(&PG_NAMESPACE),
14514        Builtin::View(&PG_CLASS_ALL_DATABASES),
14515        Builtin::Index(&PG_CLASS_ALL_DATABASES_IND),
14516        Builtin::View(&PG_CLASS),
14517        Builtin::View(&PG_DEPEND),
14518        Builtin::View(&PG_DATABASE),
14519        Builtin::View(&PG_INDEX),
14520        Builtin::View(&PG_TYPE_ALL_DATABASES),
14521        Builtin::Index(&PG_TYPE_ALL_DATABASES_IND),
14522        Builtin::View(&PG_TYPE),
14523        Builtin::View(&PG_DESCRIPTION_ALL_DATABASES),
14524        Builtin::Index(&PG_DESCRIPTION_ALL_DATABASES_IND),
14525        Builtin::View(&PG_DESCRIPTION),
14526        Builtin::View(&PG_ATTRIBUTE_ALL_DATABASES),
14527        Builtin::Index(&PG_ATTRIBUTE_ALL_DATABASES_IND),
14528        Builtin::View(&PG_ATTRIBUTE),
14529        Builtin::View(&PG_PROC),
14530        Builtin::View(&PG_OPERATOR),
14531        Builtin::View(&PG_RANGE),
14532        Builtin::View(&PG_ENUM),
14533        Builtin::View(&PG_ATTRDEF_ALL_DATABASES),
14534        Builtin::Index(&PG_ATTRDEF_ALL_DATABASES_IND),
14535        Builtin::View(&PG_ATTRDEF),
14536        Builtin::View(&PG_SETTINGS),
14537        Builtin::View(&PG_AUTH_MEMBERS),
14538        Builtin::View(&PG_CONSTRAINT),
14539        Builtin::View(&PG_TABLES),
14540        Builtin::View(&PG_TABLESPACE),
14541        Builtin::View(&PG_ACCESS_METHODS),
14542        Builtin::View(&PG_LOCKS),
14543        Builtin::View(&PG_AUTHID_CORE),
14544        Builtin::Index(&PG_AUTHID_CORE_IND),
14545        Builtin::View(&PG_AUTHID),
14546        Builtin::View(&PG_ROLES),
14547        Builtin::View(&PG_USER),
14548        Builtin::View(&PG_VIEWS),
14549        Builtin::View(&PG_MATVIEWS),
14550        Builtin::View(&PG_COLLATION),
14551        Builtin::View(&PG_POLICY),
14552        Builtin::View(&PG_INHERITS),
14553        Builtin::View(&PG_AGGREGATE),
14554        Builtin::View(&PG_TRIGGER),
14555        Builtin::View(&PG_REWRITE),
14556        Builtin::View(&PG_EXTENSION),
14557        Builtin::View(&PG_EVENT_TRIGGER),
14558        Builtin::View(&PG_LANGUAGE),
14559        Builtin::View(&PG_SHDESCRIPTION),
14560        Builtin::View(&PG_INDEXES),
14561        Builtin::View(&PG_TIMEZONE_ABBREVS),
14562        Builtin::View(&PG_TIMEZONE_NAMES),
14563        Builtin::View(&INFORMATION_SCHEMA_APPLICABLE_ROLES),
14564        Builtin::View(&INFORMATION_SCHEMA_COLUMNS),
14565        Builtin::View(&INFORMATION_SCHEMA_ENABLED_ROLES),
14566        Builtin::View(&INFORMATION_SCHEMA_KEY_COLUMN_USAGE),
14567        Builtin::View(&INFORMATION_SCHEMA_REFERENTIAL_CONSTRAINTS),
14568        Builtin::View(&INFORMATION_SCHEMA_ROUTINES),
14569        Builtin::View(&INFORMATION_SCHEMA_SCHEMATA),
14570        Builtin::View(&INFORMATION_SCHEMA_TABLES),
14571        Builtin::View(&INFORMATION_SCHEMA_TABLE_CONSTRAINTS),
14572        Builtin::View(&INFORMATION_SCHEMA_TABLE_PRIVILEGES),
14573        Builtin::View(&INFORMATION_SCHEMA_ROLE_TABLE_GRANTS),
14574        Builtin::View(&INFORMATION_SCHEMA_TRIGGERS),
14575        Builtin::View(&INFORMATION_SCHEMA_VIEWS),
14576        Builtin::View(&INFORMATION_SCHEMA_CHARACTER_SETS),
14577        Builtin::View(&MZ_SHOW_ROLE_MEMBERS),
14578        Builtin::View(&MZ_SHOW_MY_ROLE_MEMBERS),
14579        Builtin::View(&MZ_SHOW_SYSTEM_PRIVILEGES),
14580        Builtin::View(&MZ_SHOW_MY_SYSTEM_PRIVILEGES),
14581        Builtin::View(&MZ_SHOW_CLUSTER_PRIVILEGES),
14582        Builtin::View(&MZ_SHOW_MY_CLUSTER_PRIVILEGES),
14583        Builtin::View(&MZ_SHOW_DATABASE_PRIVILEGES),
14584        Builtin::View(&MZ_SHOW_MY_DATABASE_PRIVILEGES),
14585        Builtin::View(&MZ_SHOW_SCHEMA_PRIVILEGES),
14586        Builtin::View(&MZ_SHOW_MY_SCHEMA_PRIVILEGES),
14587        Builtin::View(&MZ_SHOW_OBJECT_PRIVILEGES),
14588        Builtin::View(&MZ_SHOW_MY_OBJECT_PRIVILEGES),
14589        Builtin::View(&MZ_SHOW_ALL_PRIVILEGES),
14590        Builtin::View(&MZ_SHOW_ALL_MY_PRIVILEGES),
14591        Builtin::View(&MZ_SHOW_DEFAULT_PRIVILEGES),
14592        Builtin::View(&MZ_SHOW_MY_DEFAULT_PRIVILEGES),
14593        Builtin::Source(&MZ_SINK_STATUS_HISTORY),
14594        Builtin::View(&MZ_SINK_STATUSES),
14595        Builtin::Source(&MZ_SOURCE_STATUS_HISTORY),
14596        Builtin::Source(&MZ_AWS_PRIVATELINK_CONNECTION_STATUS_HISTORY),
14597        Builtin::View(&MZ_AWS_PRIVATELINK_CONNECTION_STATUSES),
14598        Builtin::Source(&MZ_STATEMENT_EXECUTION_HISTORY),
14599        Builtin::View(&MZ_STATEMENT_EXECUTION_HISTORY_REDACTED),
14600        Builtin::Source(&MZ_PREPARED_STATEMENT_HISTORY),
14601        Builtin::Source(&MZ_SESSION_HISTORY),
14602        Builtin::Source(&MZ_SQL_TEXT),
14603        Builtin::View(&MZ_SQL_TEXT_REDACTED),
14604        Builtin::View(&MZ_RECENT_SQL_TEXT),
14605        Builtin::View(&MZ_RECENT_SQL_TEXT_REDACTED),
14606        Builtin::Index(&MZ_RECENT_SQL_TEXT_IND),
14607        Builtin::View(&MZ_ACTIVITY_LOG_THINNED),
14608        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_THINNED),
14609        Builtin::View(&MZ_RECENT_ACTIVITY_LOG),
14610        Builtin::View(&MZ_RECENT_ACTIVITY_LOG_REDACTED),
14611        Builtin::Index(&MZ_RECENT_ACTIVITY_LOG_THINNED_IND),
14612        Builtin::View(&MZ_SOURCE_STATUSES),
14613        Builtin::Source(&MZ_STATEMENT_LIFECYCLE_HISTORY),
14614        Builtin::Source(&MZ_STORAGE_SHARDS),
14615        Builtin::Source(&MZ_SOURCE_STATISTICS_RAW),
14616        Builtin::Source(&MZ_SINK_STATISTICS_RAW),
14617        Builtin::View(&MZ_SOURCE_STATISTICS_WITH_HISTORY),
14618        Builtin::Index(&MZ_SOURCE_STATISTICS_WITH_HISTORY_IND),
14619        Builtin::View(&MZ_SOURCE_STATISTICS),
14620        Builtin::Index(&MZ_SOURCE_STATISTICS_IND),
14621        Builtin::View(&MZ_SINK_STATISTICS),
14622        Builtin::Index(&MZ_SINK_STATISTICS_IND),
14623        Builtin::View(&MZ_STORAGE_USAGE),
14624        Builtin::Source(&MZ_FRONTIERS),
14625        Builtin::View(&MZ_GLOBAL_FRONTIERS),
14626        Builtin::Source(&MZ_WALLCLOCK_LAG_HISTORY),
14627        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTORY),
14628        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY),
14629        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG),
14630        Builtin::Source(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM_RAW),
14631        Builtin::View(&MZ_WALLCLOCK_GLOBAL_LAG_HISTOGRAM),
14632        Builtin::Source(&MZ_MATERIALIZED_VIEW_REFRESHES),
14633        Builtin::Source(&MZ_COMPUTE_DEPENDENCIES),
14634        Builtin::View(&MZ_MATERIALIZATION_DEPENDENCIES),
14635        Builtin::View(&MZ_MATERIALIZATION_LAG),
14636        Builtin::View(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW),
14637        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS_PER_WORKER),
14638        Builtin::View(&MZ_COMPUTE_ERROR_COUNTS),
14639        Builtin::Source(&MZ_COMPUTE_ERROR_COUNTS_RAW_UNIFIED),
14640        Builtin::Source(&MZ_COMPUTE_HYDRATION_TIMES),
14641        Builtin::Log(&MZ_COMPUTE_LIR_MAPPING_PER_WORKER),
14642        Builtin::View(&MZ_LIR_MAPPING),
14643        Builtin::Source(&MZ_COMPUTE_OPERATOR_HYDRATION_STATUSES),
14644        Builtin::Source(&MZ_CLUSTER_REPLICA_FRONTIERS),
14645        Builtin::View(&MZ_COMPUTE_HYDRATION_STATUSES),
14646        Builtin::View(&MZ_HYDRATION_STATUSES),
14647        Builtin::Index(&MZ_HYDRATION_STATUSES_IND),
14648        Builtin::View(&MZ_SHOW_CLUSTER_REPLICAS),
14649        Builtin::View(&MZ_SHOW_NETWORK_POLICIES),
14650        Builtin::View(&MZ_CLUSTER_DEPLOYMENT_LINEAGE),
14651        Builtin::Index(&MZ_SHOW_DATABASES_IND),
14652        Builtin::Index(&MZ_SHOW_SCHEMAS_IND),
14653        Builtin::Index(&MZ_SHOW_CONNECTIONS_IND),
14654        Builtin::Index(&MZ_SHOW_TABLES_IND),
14655        Builtin::Index(&MZ_SHOW_SOURCES_IND),
14656        Builtin::Index(&MZ_SHOW_VIEWS_IND),
14657        Builtin::Index(&MZ_SHOW_MATERIALIZED_VIEWS_IND),
14658        Builtin::Index(&MZ_SHOW_SINKS_IND),
14659        Builtin::Index(&MZ_SHOW_TYPES_IND),
14660        Builtin::Index(&MZ_SHOW_ALL_OBJECTS_IND),
14661        Builtin::Index(&MZ_SHOW_INDEXES_IND),
14662        Builtin::Index(&MZ_SHOW_COLUMNS_IND),
14663        Builtin::Index(&MZ_SHOW_CLUSTERS_IND),
14664        Builtin::Index(&MZ_SHOW_CLUSTER_REPLICAS_IND),
14665        Builtin::Index(&MZ_SHOW_SECRETS_IND),
14666        Builtin::Index(&MZ_SHOW_ROLES_IND),
14667        Builtin::Index(&MZ_CLUSTERS_IND),
14668        Builtin::Index(&MZ_INDEXES_IND),
14669        Builtin::Index(&MZ_ROLES_IND),
14670        Builtin::Index(&MZ_SOURCES_IND),
14671        Builtin::Index(&MZ_SINKS_IND),
14672        Builtin::Index(&MZ_MATERIALIZED_VIEWS_IND),
14673        Builtin::Index(&MZ_CONTINUAL_TASKS_IND),
14674        Builtin::Index(&MZ_SOURCE_STATUSES_IND),
14675        Builtin::Index(&MZ_SOURCE_STATUS_HISTORY_IND),
14676        Builtin::Index(&MZ_SINK_STATUSES_IND),
14677        Builtin::Index(&MZ_SINK_STATUS_HISTORY_IND),
14678        Builtin::Index(&MZ_CLUSTER_REPLICAS_IND),
14679        Builtin::Index(&MZ_CLUSTER_REPLICA_SIZES_IND),
14680        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUSES_IND),
14681        Builtin::Index(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_IND),
14682        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_IND),
14683        Builtin::Index(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_IND),
14684        Builtin::Index(&MZ_CLUSTER_REPLICA_HISTORY_IND),
14685        Builtin::Index(&MZ_CLUSTER_REPLICA_NAME_HISTORY_IND),
14686        Builtin::Index(&MZ_OBJECT_LIFETIMES_IND),
14687        Builtin::Index(&MZ_OBJECT_HISTORY_IND),
14688        Builtin::Index(&MZ_OBJECT_DEPENDENCIES_IND),
14689        Builtin::Index(&MZ_COMPUTE_DEPENDENCIES_IND),
14690        Builtin::Index(&MZ_OBJECT_TRANSITIVE_DEPENDENCIES_IND),
14691        Builtin::Index(&MZ_FRONTIERS_IND),
14692        Builtin::Index(&MZ_WALLCLOCK_GLOBAL_LAG_RECENT_HISTORY_IND),
14693        Builtin::Index(&MZ_KAFKA_SOURCES_IND),
14694        Builtin::Index(&MZ_WEBHOOK_SOURCES_IND),
14695        Builtin::Index(&MZ_COMMENTS_IND),
14696        Builtin::Index(&MZ_DATABASES_IND),
14697        Builtin::Index(&MZ_SCHEMAS_IND),
14698        Builtin::Index(&MZ_CONNECTIONS_IND),
14699        Builtin::Index(&MZ_TABLES_IND),
14700        Builtin::Index(&MZ_TYPES_IND),
14701        Builtin::Index(&MZ_OBJECTS_IND),
14702        Builtin::Index(&MZ_COLUMNS_IND),
14703        Builtin::Index(&MZ_SECRETS_IND),
14704        Builtin::Index(&MZ_VIEWS_IND),
14705        Builtin::Index(&MZ_CONSOLE_CLUSTER_UTILIZATION_OVERVIEW_IND),
14706        Builtin::Index(&MZ_CLUSTER_DEPLOYMENT_LINEAGE_IND),
14707        Builtin::Index(&MZ_CLUSTER_REPLICA_FRONTIERS_IND),
14708        Builtin::Index(&MZ_COMPUTE_HYDRATION_TIMES_IND),
14709        Builtin::View(&MZ_RECENT_STORAGE_USAGE),
14710        Builtin::Index(&MZ_RECENT_STORAGE_USAGE_IND),
14711        Builtin::Connection(&MZ_ANALYTICS),
14712        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_METRICS_HISTORY_CT),
14713        Builtin::ContinualTask(&MZ_CLUSTER_REPLICA_STATUS_HISTORY_CT),
14714        Builtin::ContinualTask(&MZ_WALLCLOCK_LAG_HISTORY_CT),
14715        Builtin::View(&MZ_INDEX_ADVICE),
14716        Builtin::View(&MZ_MCP_DATA_PRODUCTS),
14717        Builtin::View(&MZ_MCP_DATA_PRODUCT_DETAILS),
14718    ];
14719
14720    builtin_items.extend(notice::builtins());
14721
14722    // Generate builtin relations reporting builtin objects last, since they need a complete view
14723    // of all other builtins.
14724    let mut builtin_builtins = builtin::builtins(&builtin_items).collect();
14725
14726    // Construct the full list of builtins, retaining dependency order.
14727    let mut builtins = Vec::new();
14728    builtins.append(&mut builtin_types);
14729    builtins.append(&mut builtin_funcs);
14730    builtins.append(&mut builtin_builtins);
14731    builtins.append(&mut builtin_items);
14732
14733    builtins
14734});
14735pub const BUILTIN_ROLES: &[&BuiltinRole] = &[
14736    &MZ_SYSTEM_ROLE,
14737    &MZ_SUPPORT_ROLE,
14738    &MZ_ANALYTICS_ROLE,
14739    &MZ_MONITOR_ROLE,
14740    &MZ_MONITOR_REDACTED,
14741];
14742pub const BUILTIN_CLUSTERS: &[&BuiltinCluster] = &[
14743    &MZ_SYSTEM_CLUSTER,
14744    &MZ_CATALOG_SERVER_CLUSTER,
14745    &MZ_PROBE_CLUSTER,
14746    &MZ_SUPPORT_CLUSTER,
14747    &MZ_ANALYTICS_CLUSTER,
14748];
14749pub const BUILTIN_CLUSTER_REPLICAS: &[&BuiltinClusterReplica] = &[
14750    &MZ_SYSTEM_CLUSTER_REPLICA,
14751    &MZ_CATALOG_SERVER_CLUSTER_REPLICA,
14752    &MZ_PROBE_CLUSTER_REPLICA,
14753];
14754
14755#[allow(non_snake_case)]
14756pub mod BUILTINS {
14757    use mz_sql::catalog::BuiltinsConfig;
14758
14759    use super::*;
14760
14761    pub fn logs() -> impl Iterator<Item = &'static BuiltinLog> {
14762        BUILTINS_STATIC.iter().filter_map(|b| match b {
14763            Builtin::Log(log) => Some(*log),
14764            _ => None,
14765        })
14766    }
14767
14768    pub fn types() -> impl Iterator<Item = &'static BuiltinType<NameReference>> {
14769        BUILTINS_STATIC.iter().filter_map(|b| match b {
14770            Builtin::Type(typ) => Some(*typ),
14771            _ => None,
14772        })
14773    }
14774
14775    pub fn views() -> impl Iterator<Item = &'static BuiltinView> {
14776        BUILTINS_STATIC.iter().filter_map(|b| match b {
14777            Builtin::View(view) => Some(*view),
14778            _ => None,
14779        })
14780    }
14781
14782    pub fn materialized_views() -> impl Iterator<Item = &'static BuiltinMaterializedView> {
14783        BUILTINS_STATIC.iter().filter_map(|b| match b {
14784            Builtin::MaterializedView(mv) => Some(*mv),
14785            _ => None,
14786        })
14787    }
14788
14789    pub fn funcs() -> impl Iterator<Item = &'static BuiltinFunc> {
14790        BUILTINS_STATIC.iter().filter_map(|b| match b {
14791            Builtin::Func(func) => Some(func),
14792            _ => None,
14793        })
14794    }
14795
14796    pub fn iter(cfg: &BuiltinsConfig) -> impl Iterator<Item = &'static Builtin<NameReference>> {
14797        let include_continual_tasks = cfg.include_continual_tasks;
14798        BUILTINS_STATIC.iter().filter(move |x| match x {
14799            Builtin::ContinualTask(_) if !include_continual_tasks => false,
14800            _ => true,
14801        })
14802    }
14803}
14804
14805pub static BUILTIN_LOG_LOOKUP: LazyLock<HashMap<&'static str, &'static BuiltinLog>> =
14806    LazyLock::new(|| BUILTINS::logs().map(|log| (log.name, log)).collect());
14807/// Keys are builtin object description, values are the builtin index when sorted by dependency and
14808/// the builtin itself.
14809pub static BUILTIN_LOOKUP: LazyLock<
14810    HashMap<SystemObjectDescription, (usize, &'static Builtin<NameReference>)>,
14811> = LazyLock::new(|| {
14812    // BUILTIN_LOOKUP is only ever used for lookups by key, it's not iterated,
14813    // so it's safe to include all of them, regardless of BuiltinConfig. We
14814    // enforce this statically by using the mz_ore HashMap which disallows
14815    // iteration.
14816    BUILTINS_STATIC
14817        .iter()
14818        .enumerate()
14819        .map(|(idx, builtin)| {
14820            (
14821                SystemObjectDescription {
14822                    schema_name: builtin.schema().to_string(),
14823                    object_type: builtin.catalog_item_type(),
14824                    object_name: builtin.name().to_string(),
14825                },
14826                (idx, builtin),
14827            )
14828        })
14829        .collect()
14830});
14831
14832#[cfg(test)]
14833mod tests {
14834    use std::collections::{BTreeMap, BTreeSet};
14835
14836    use mz_pgrepr::oid::FIRST_MATERIALIZE_OID;
14837    use mz_sql_parser::ast::visit::{self, Visit};
14838    use mz_sql_parser::ast::{Raw, RawItemName, UnresolvedItemName};
14839
14840    use super::*;
14841
14842    #[mz_ore::test]
14843    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14844    fn test_builtin_type_schema() {
14845        for typ in BUILTINS::types() {
14846            if typ.oid < FIRST_MATERIALIZE_OID {
14847                assert_eq!(
14848                    typ.schema, PG_CATALOG_SCHEMA,
14849                    "{typ:?} should be in {PG_CATALOG_SCHEMA} schema"
14850                );
14851            } else {
14852                // `mz_pgrepr::Type` resolution relies on all non-PG types existing in the
14853                // mz_catalog schema.
14854                assert_eq!(
14855                    typ.schema, MZ_CATALOG_SCHEMA,
14856                    "{typ:?} should be in {MZ_CATALOG_SCHEMA} schema"
14857                );
14858            }
14859        }
14860    }
14861
14862    /// Visitor that collects the last component of all referenced
14863    /// item names from a SQL AST.
14864    struct ItemNameCollector {
14865        names: BTreeSet<String>,
14866    }
14867
14868    impl<'ast> Visit<'ast, Raw> for ItemNameCollector {
14869        fn visit_item_name(&mut self, name: &'ast <Raw as mz_sql_parser::ast::AstInfo>::ItemName) {
14870            let unresolved: &UnresolvedItemName = match name {
14871                RawItemName::Name(n) | RawItemName::Id(_, n, _) => n,
14872            };
14873            let parts = &unresolved.0;
14874            if !parts.is_empty() {
14875                let obj_name = parts[parts.len() - 1].as_str().to_string();
14876                self.names.insert(obj_name);
14877            }
14878            visit::visit_item_name(self, name);
14879        }
14880    }
14881
14882    /// Tests that `BUILTINS_STATIC` is ordered respecting dependencies:
14883    /// if builtin A references builtin B in its SQL, then B must appear
14884    /// before A in the list. (This ordering is assumed by, e.g.,
14885    /// `sort_updates` during catalog migrations.)
14886    #[mz_ore::test]
14887    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
14888    fn test_builtins_static_dependency_order() {
14889        // Build a map from name -> (schema, index) for all builtins.
14890        // We look up by just the name (last component) to catch
14891        // unqualified references in SQL.
14892        let mut builtin_by_name: BTreeMap<&str, (&str, usize)> = BTreeMap::new();
14893        let mut duplicate_names = Vec::new();
14894        for (idx, builtin) in BUILTINS_STATIC.iter().enumerate() {
14895            if let Some((prev_schema, prev_idx)) =
14896                builtin_by_name.insert(builtin.name(), (builtin.schema(), idx))
14897            {
14898                // Only flag duplicates across different schemas.
14899                // Same-schema duplicates (e.g., range types that
14900                // appear as both Type and Func) are fine because
14901                // they resolve to the same schema.
14902                if prev_schema != builtin.schema() {
14903                    duplicate_names.push(format!(
14904                        "name {:?} appears in both {}.{} (index \
14905                         {}) and {}.{} (index {})",
14906                        builtin.name(),
14907                        prev_schema,
14908                        builtin.name(),
14909                        prev_idx,
14910                        builtin.schema(),
14911                        builtin.name(),
14912                        idx,
14913                    ));
14914                }
14915            }
14916        }
14917        assert!(
14918            duplicate_names.is_empty(),
14919            "BUILTINS_STATIC has duplicate names across different \
14920             schemas (this test needs adjustment if such duplicates \
14921             are intentional):\n{}",
14922            duplicate_names.join("\n"),
14923        );
14924
14925        // Get the `CREATE ...` SQL for builtins that have it.
14926        let get_create_sql = |builtin: &Builtin<NameReference>| -> Option<String> {
14927            match builtin {
14928                Builtin::View(v) => Some(v.create_sql()),
14929                Builtin::MaterializedView(mv) => Some(mv.create_sql()),
14930                Builtin::Index(idx) => Some(idx.create_sql()),
14931                Builtin::ContinualTask(ct) => Some(ct.create_sql()),
14932                _ => None,
14933            }
14934        };
14935
14936        // For each SQL-bearing builtin, parse its SQL, walk the AST to
14937        // find referenced item names, and check that all referenced
14938        // builtins appear earlier in BUILTINS_STATIC.
14939        let mut violations = Vec::new();
14940        for (idx, builtin) in BUILTINS_STATIC.iter().enumerate() {
14941            let create_sql = match get_create_sql(builtin) {
14942                Some(sql) => sql,
14943                None => continue,
14944            };
14945
14946            let stmts = mz_sql_parser::parser::parse_statements(&create_sql).unwrap_or_else(|e| {
14947                panic!(
14948                    "failed to parse SQL for {}.{}: \
14949                         {e}\nSQL: {create_sql}",
14950                    builtin.schema(),
14951                    builtin.name(),
14952                )
14953            });
14954
14955            let mut collector = ItemNameCollector {
14956                names: BTreeSet::new(),
14957            };
14958            for stmt in &stmts {
14959                collector.visit_statement(&stmt.ast);
14960            }
14961
14962            for ref_name in &collector.names {
14963                if let Some(&(ref_schema, dep_idx)) = builtin_by_name.get(ref_name.as_str()) {
14964                    if dep_idx > idx {
14965                        violations.push(format!(
14966                            "{}.{} (index {}) references \
14967                             {}.{} (index {}), but the \
14968                             dependency appears later in \
14969                             BUILTINS_STATIC",
14970                            builtin.schema(),
14971                            builtin.name(),
14972                            idx,
14973                            ref_schema,
14974                            ref_name,
14975                            dep_idx,
14976                        ));
14977                    }
14978                }
14979            }
14980        }
14981
14982        assert!(
14983            violations.is_empty(),
14984            "BUILTINS_STATIC has dependency ordering violations:\n{}",
14985            violations.join("\n"),
14986        );
14987    }
14988}